1
votes

Problem

When building my project for production with react, react-router V4 and webpack, the "Switch" is not rendering any matching routes. But it works in a development environment.

What I've tried

I used the boilerplate here : https://github.com/KleoPetroff/react-webpack-boilerplate

My Router.js is simply :

import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import App from '../components/App';
import About from '../components/About';

const Root = () => {
return (
    <Router>
      <Switch>
        <Route path="/about" component={About} />
        <Route exact path="/" component={App} />
      </Switch>
    </Router>
);
};

export default Root;

And the components App.js and About.js are simply :

App.js
import React from 'react';
import { Link } from 'react-router-dom';

const App = () => {
  return (
    <h2 id="heading">
      Hello ReactJS
      <Link to="/about">here</Link>
    </h2>
  );
};

export default App;
About.js
import React from 'react';

const About = () => {
  return (
    <h2 id="heading">
      About ReactJS
    </h2>
  );
};

export default About;

My Research

I went through plenty of stackoverflow's similar question (more related about react-router-redux apparently) but I got no working answers for the moment.

I tried to implement the app using different webpack configs like the one with react-create-app repo.

I'm not sure if it's related to the latest version of react-router or with my webpack config.

It sounds like a dumb and easy problem but I can't find answers anywhere in the web.

So my question is, how do I make the switch component match the correct paths ?

1
what do you mean by not rendering any matching routes? do you get completely white page, or your app is not rendering the route itself?Borys Kupar
You might need to configure your webserver (check the asnwer below), or you can use "HashRouter" from react-router. it doesn't require any server configuration.Borys Kupar
Hello and thank you for your answer, actually I get a complete white page because no routes seems matched. If I remove path="/" and do a basic <Route component={App}></Route>, it actually renders the component. So I believe the default location for the router is wrong in production. I also think it has something to do with webserver, I only tried it locally because I thought it would be handled by webpack by default.sudocho

1 Answers

0
votes

I faced a similar issue recently and resolved it by resolving all requests back to my index.html in my .htaccess file.

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>