Reputation: 135
I am trying to do router with react-router-dom but my URL is getting updated but page is not routing to my specified component. This is my App.js
import "./App.css";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import Menu from "./layouts/Menu";
import Dashboard from "./layouts/Dashboard";
import Content from "./layouts/Content";
function App() {
return (
<BrowserRouter>
<Switch>
<Route path="/">
<Menu></Menu>
</Route>
<Route path="/dashboard">
<Dashboard></Dashboard>
</Route>
<Route path="/content">
<Content></Content>
</Route>
</Switch>
</BrowserRouter>
);
}
export default App;
Below is Menu component in which I am trying to use Link from react-router-dom
import React from "react";
import { Link } from "react-router-dom";
function Menu() {
return (
<div>
<Link to="/dashboard">
<h1>go to dashboard</h1>
</Link>
<Link to="/content">
<h1>go to content</h1>
</Link>
</div>
);
}
export default Menu;
The other pages i.e Dashboard and Content has nothing in them, just one h1 tag to check if they are getting displayed or not.
Below is my package.json and my app folder structure if that helps
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.11.10",
"@testing-library/react": "^11.2.5",
"@testing-library/user-event": "^12.8.3",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.3",
"web-vitals": "^1.1.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
I am beginner in react and I am stuck on this issue, if any expert can help me or give reference to any source where I can get help. Thanks in advance
Upvotes: 1
Views: 1222
Reputation: 135
I was not putting exact
with root path. I already tried this way but did not put exact
with root path.
Lesson learned:
exact
if every path in case your react-router is not redirecting you to pages you want to :)Edit: Looks like the practice following in point number 2 is not good, so always try to arrange your paths in a way that the more specific paths will be on Top and so on
Upvotes: 0
Reputation: 141
Your paths are always matching your first route.
<Route path="/">
That would match any route that starts with "/", and since it's the first route in your switch, it would always match this route. IE: "/dashboard" starts with "/", "/content" starts with "/".
Using exact will match the route only if it is precisely "/".
<Route exact path="/">
That would not match "/dashboard" or "/content"
Depending on your intention with the code, either:
Upvotes: 3