React - home page doesn't change (routing)
Why does React display the home page when the path
changes?
My code:
import React from "react";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
// Pages to render --------------------
const Home = () => {
return <h2>Home</h2>;
};
const Gallery = () => {
return <h2>Gallery</h2>;
};
const About = () => {
return <h2>About</h2>;
};
// Routing --------------------
const App = () => {
return (
<Router>
<div>
<div>
<Link to="/">Home</Link>
<Link to="/gallery">Gallery</Link>
<Link to="/about">About</Link>
</div>
<Switch>
<Route path="/">
<Home />
</Route>
<Route path="/about">
<About />
</Route>
<Route path="/gallery">
<Gallery />
</Route>
</Switch>
</div>
</Router>
);
};
export default App;
It is necessary to add exact
property to Route
that has path="/"
(<Home>
case).
The reasone why the react-router
matches home always is: path
property value is treat as path beginning that should appear in current browser url path to select route (something like location.path.startWith('/')
).
In your case each one url starts with /
- so first one is matched all typed urls in web browser address field.
To understand better how it works we can write paths as regexes, they can be presented as:
^/
, ^/gallery
, ^/about
- each one path matches first one path!
Note:
Switch
selects first one matchedpath
 always.
By adding exact
property in the Route
with path="/"
we tell to use ^/$
expresson.
That implementaion let to type:
/gallery/john/2021
that will be intepreted as/gallery
path
with additional informationÂ/john/2021
whitch can be used as specific sub-gallery name,/gallery/john/2020
 that will be intepreted as/gallery
path
with additional informationÂ/john/2020
 whitch can be used as specific sub-gallery name,/about/company
that will be intepreted as/about
path
with additional informationÂ/company
whitch can be used as specific sub-page name or if there is not defined sub-page just/about
will be displayed always.
To deal wiith subpages we can use sub-switch (nested Switch
component in specific Route
).
Â
The solution was to use exact path
 to the Route
with <Home/>
component inside Switch
, because Router
goes through all of the defined routes and returns the first match it finds.
The solution:
import React from "react";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
// Pages to render --------------------
const Home = () => {
return <h2>Home</h2>;
};
const Gallery = () => {
return <h2>Gallery</h2>;
};
const About = () => {
return <h2>About</h2>;
};
// Routing --------------------
const App = () => {
return (
<Router>
<div>
<div>
<Link to="/">Home</Link>
<Link to="/gallery">Gallery</Link>
<Link to="/about">About</Link>
</div>
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/about">
<About />
</Route>
<Route path="/gallery">
<Gallery />
</Route>
</Switch>
</div>
</Router>
);
};
export default App;
You can run this example here.Â