React Router v4 not working

I'm relatively new to reacting, and I'm trying to figure out how to get React router to work. I have a super simple test application that looks like this:

import React from 'react'; import ReactDOM from 'react-dom'; import {BrowserRouter as Router, Route, Switch, IndexRoute, Link} from 'react-router-dom'; const Home = () => <h1><Link to= "/about">Click Me</Link></h1> const About = () => <h1>About Us</h1> const Test = () => ( <Router> <Switch> <Route path ="/" component = {Home} /> <Route path ="/about" component = {About} /> </Switch> </Router> ) ReactDOM.render(<Test />, document.getElementById('app')); 

when I run the application, it loads the home component without any problems, and when I click the "Click Me" link, the url changes to localhost / about, however nothing happens. If I click update, I get the message "Can not GET / about". It is clear that I am doing something wrong, but I could not understand that. I also use Webpack.

+5
source share
2 answers

You need to use the exact path for / , otherwise it will also match /about .

 <Route exact path="/" component={Home} /> 

As mentioned in the comments, for something so simple, I would suggest using the Create React App , which will make sure that your server code and the settings of your web package are all correct. When you use create-react-app , you just need to use npm to install the response package on the v4 router, and then put your code in the App.js file and it should work. There are a few small changes to your code to make it work with create-react-app , as shown below:

 // App.js import React from 'react'; import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom'; const Home = () => <h1><Link to="/about">Click Me</Link></h1> const About = () => <h1>About Us</h1> const App = () => ( <Router> <Switch> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> </Switch> </Router> ) export default App; 

The quick start instructions from the React Router V4 documentation will tell you almost the same thing that I just explained.

+9
source

If you are working with localhost, you need to add historyApiFallback: true to the webpack.config file

+8
source

Source: https://habr.com/ru/post/1266826/


All Articles