'React router dom not working with Link, but refreshing the page loads the component
I've got a create-react-app with a couple of routes. Every now and then as I change branches etc, I notice routing doesn't work. I reckon the only time it has worked its because of caching.
Below are my routes, I've replaced the blog route with a simple p tag for simplicity as I began to think it was relating to the component I was linking to.
App.tsx
const history = createBrowserHistory();
...
<Router history={history} data-test="component-app">
<Switch>
<Route exact path="/" component={Main} />
<Route path="/blog">
<p>test</p>
</Route>
</Switch
</Router>
Main.tsx
import React from "react";
import { Link } from "react-router-dom";
export const Main = () => {
return (
<Link to="/blog">Blog</Link>
)
}
Here's what happens:
- Click on Blog link in Main = route in browser changes to localhost:9600/blog BUT there's no content, just a white page
- Refresh the page whilst on localhost:9600/blog and you get the
<p>test</p>part
But why isn't it showing test as soon as you click on the link?
Versions I'm using:
- react-router-dom: "^5.2.0"
- react-scripts: "4.0.1"
- react: "^17.0.1"
- history: "^5.0.0"
Any ideas?
Solution 1:[1]
Usually when I want to render some JSX inside a ‘Route’ and I don’t want to create a different component I use the ‘render’ prop that receives a function and should return the JSX you want to be rendered.
Try this:
<Route path=“/blog” render={() => <p>test</p>} />
Solution 2:[2]
Changing Router to BrowserRouter in App.js worked!
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
...
return (
<Router history={history} data-test="component-app">
<Switch>
<Route exact path="/">
<Main />
</Route>
<Route path="/blog">
<p>test</p>
</Route>
</Switch>
</Router>
);
Thanks all for your help!
Solution 3:[3]
Thanks this worked for me by importing BrowserRouter as Router:
import { BrowserRouter as Router, Route } from 'react-router-dom';
and updating "react-router-dom": "^5.2.0" to "react-router-dom": "^5.3.0"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Japsz |
| Solution 2 | Nats |
| Solution 3 | Prashika Sonule |
