'react-router-dom router change the url but nothing else. All of components are not changed
I can't solve why it doesn't work. When I clck on the link new page the url is changing but the page not (it should change to new page with div witch some content of the new page). I have to refresh it and then the component changes proprely.
version
"react-dom": "^18.1.0",
"react-router-dom": "^5.3.1",
App.js
import React, { Component } from 'react';
import './App.css';
import HomePage from './components/HomePage';
import New from './components/NewComponents';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
function App() {
return (
<div className="App">
<BrowserRouter>
<Switch>
<Route exact path="/" component={HomePage}>
</Route>
<Route patch="/new" component={New}>
</Route>
</Switch>
</BrowserRouter>
</div>
);
}
export default App;
HomePage.js
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
const HomePage = () => {
return (
<div>
<h1>home page</h1>
<Link to="/">home page</Link>
<h1>new page</h1>
<Link to="/New">new page</Link>
</div>
)
}
export default HomePage;
NewComponent.js
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
const New = () => {
return (
<div>
<h1>some content of the new page</h1>
<Link to="/">home</Link>
</div>
)
}
export default New;
Solution 1:[1]
You need to add the "/New" route to your switch in the App component:
<Switch>
<Route exact path="/" component={Home}></Route>
<Route path="/create" component={Create}></Route>
<Route path="/New" component={New}></Route>
</Switch>
You also don't import the "Create" component in that module either.
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 | Sean Lawton |