/
Routes (navigation links)

Routes (navigation links)

Some thoughts on how Routers, Routes, Switches etc work

Create a new React app using the command npx create-react-app <app name>

Create a new file called routes-example.jsx and copy the code below into it

 

import React from "react"; import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom"; function RouterExample() { return ( <Router> <div> <ul> <li> <Link to="/"><h1>Home</h1></Link> </li> <li> <Link to="/about">About</Link> </li> <li> <Link to="/topics">Topics</Link> </li> </ul> <hr /> <Switch> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> <Route path="/topics" component={Topics} /> <Route component={NoMatch} /> </Switch> </div> </Router> ); } function Home() { return ( <div> <h2>Home</h2> </div> ); } function About() { return ( <div> <h2>About</h2> </div> ); } function NoMatch() { return ( <div> <h2>Nothing found here...</h2> </div> ); } function Topics({ match }) { return ( <div> <h2>Topics</h2> <ul> <li> <Link to={'${match.url}/rendering'}>Rendering with React</Link> </li> <li> <Link to={`${match.url}/components`}>Components</Link> </li> <li> <Link to={`${match.url}/props-v-state`}>Props v. State</Link> </li> </ul> <Route path={`${match.path}/:topicId`} component={Topic} /> <Route exact path={match.path} render={() => <h3>Please select a topic.</h3>} /> </div> ); } function Topic({ match }) { return ( <div> <h3>{match.path + '/' + match.params.topicId}</h3> </div> ); } export default RouterExample;

Here is my package.json so that you can get the required dependencies

Run the code using the command npm start

Related content