react-router-dom BrowserRouter not working after build

5k views Asked by At

This is the first time I tried react. I create a project using create-react-app, then for routing, I use React Router V4 for web react-router-dom.

This is my index.js file

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
import App from './App';
import './index.css';

ReactDOM.render(
  <Router>
    <App />
  </Router>,
  document.getElementById('root')
);

There's no problem when I start the server with npm start. But when I build the app with npm run build, putting it in my www folder in my Apache server and access it, I only get empty page with <!-- react-empty: 1 --> inside my root div.

<div id="root">
  <!-- react-empty: 1 -->
</div>

I have tried looking for similar cases, but the answer always about adding historyApiFallback in webpack.config.js or gulp, which I can't find anywhere in the create-react-app template.

I have tried HashRouter, it's working fine, but there's /#/ in the url which is undesirable.

How can I get the BrowserRouter to work after I build the app?

1

There are 1 answers

2
Win On

Well, there was no problem at all. It worked, even if it was built using npm run build. My best guess is: you placed the files in the wrong folder.

When you build your code using npm run build, the static folder should be placed inside the MallApp folder. So your folder structure should be like this:

/var/www/mywebfolder/index.html
/var/www/mywebfolder/MallApp/static

Check your browser's console, I believe it contains errors. Failed to get the js and css files.