npm install react-router-dom
import { BrowserRouter as Router, Switch, Route} from 'react-router-dom'
you can rename longer import by the example of 'BrowserRouter' above.
Rather than placing components directly into App, they are established as routes.
The entire return JSX for App will be wrapped in <Router></Router> tags
function App() {
return (
<Router>
<div className="App">
<Nav />
<Switch>
<Route path="/" component={Home}/>
<Route path="/about" component={About} />
<Route path="/shop" component={Shop} />
</Switch>
</div>
</Router>
);
}
Decide which component is on each route by adding component={yourComponentName}
Also, establish which path it is set at from the root URL by path="/yourComponent"
The above code has an issue to check to see if path has a / for the first item. This causes issues with Routes becoming combined due to the path="/"
Enclose the Routes in <Switch></Switch>
Now the routes wont be combined but it will stop at the first component that fulfills any part of its search criteria.
By adding exact
into the component properties, it will only go to Routes that exactly match the URL directory name.
<Route path="/" exact component={Home}/>
To be able to click between routes rather than having to enter the path into the browser, go to your navigation component and import { Link } from 'react-router-dom'
Then, in the Nav component, we wrap the li's where the links would go in tags.
To direct these Links to the proper page, we would give them the property to="/myComponent"
Ex:
function Nav() {
return (
<nav>
<h3>Logo</h3>
<ul className="nav-links">
<Link to='/about'>
<li>About</li>
</Link>
<Link to='/shop'>
<li>Shop</li>
</Link>
</ul>
</nav>
);
}
Wow, thank you!