7

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?

3
  • Could you share the github repo? That's the only way to check your code. Never had this issue with create-react-app and react-router v4, so there must be something wrong on your side.
    – Win
    Aug 30, 2017 at 6:53
  • Sorry for late reply, this is my github repo. github.com/fadeltd/mall-app Aug 31, 2017 at 8:06
  • the problem lies with how you serve the page. if you access it with something like localhost/myproject. then it will assume that the route needs to render will be the route with myproject path, so add prefix if this is the case
    – Rei Dien
    Sep 1, 2017 at 17:59

1 Answer 1

0

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.

2
  • nope. everything loaded fine. console empty. dropbox.com/sh/2anki8hncblooq6/AACySxivCMakTdH5-SW8KRQ3a Aug 31, 2017 at 22:10
  • Only one possibility: your browser has HTML5 History API problem. Because it is needed by the BrowserRouter. As for your question regarding the webpack config, you need to run npm run eject. It will "extract" all the config files to your project folder. It is a one way operation though, so if you do not understand how to use babel, webpack, lint, etc.. don't do this.
    – Win
    Sep 1, 2017 at 4:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.