I am to create an app which utilizes react-router-dom. I am currently trying to us eversion 5.2.0. I have tried to isolate the issue and focused on just making the routing work but have not succeeded yet. I made the app using npx create-react-app.
Package.json
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.2.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.1.0",
"react-dom": "^18.1.0",
"react-router-dom": "^5.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
App.js
import React from "react";
import { Route } from "react-router-dom";
import { withRouter } from "react-router-dom";
import { Switch } from "react-router-dom";
import { BrowserRouter} from "react-router-dom";
import { About, Contact, Home } from "./Components";
function App() {
return (
<BrowserRouter>
<Switch>
<Route exact path="/contact" component={withRouter(Contact)}/>
<Route exact path="/about">
<About/>
</Route>
<Route path="/">
<Home/>
</Route>
</Switch>
</BrowserRouter>
);
}
export default App;
Components.js
import React from "react";
import { useHistory } from "react-router-dom";
const Links = () => {
const history = useHistory();
const buttonClicked = (link) => {
history.push(link);
}
return(
<>
<button onClick={() => buttonClicked('/')}>home</button>
<button onClick={() => buttonClicked('/about')}>about</button>
<button onClick={() => buttonClicked('/contact')}>contact</button>
</>
)
}
export const Contact = () => {
return(
<div>
<Links/>
Contact page
</div>
)
}
export const Home = () => {
return(
<div>
<Links/>
Home page
</div>
)
}
export const About = () => {
return(
<div>
<Links/>
About page
</div>
)
}
I have tried using withRouter in various places without success. I have also changed how the Routes are written to include exact paths and non exact paths so am unsure what is causing the issue.
This is my current code. When a button is clicked, the URL changes accordingly. However, the component is not rendered again with the correct route. If you could help I would appreciate it.