Routing on URLs

Each page in the QuizBuzz app is a separate component. Therefore, you add these three components in their respective source files: Quizzes, Quiz, and Question. You keep them simple for the time being, including just a heading in each one:

function Quizzes(props) {
return (
<h2>Quizzes</h2>
);
}

Quiz and Question are similar but with the function name and heading changed.

When the user types the route /quizzes after the domain in the browser's location bar, you want to load the Quizzes component. When the user types the route /quiz, you want to load the Quiz component. You could achieve this by writing your own JavaScript code to extract the path from the global variable window.location and then do some conditional rendering based on the path. However, this is what React Router does for you.

You already installed react-router-dom as a dependency when you set up the project. Now you must inject a router into the component hierarchy. In index.js you add a BrowserRouter:

// ...
import {BrowserRouter} from 'react-router-dom';

ReactDOM.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>,
document.getElementById('root')
);

Descendent components now have access to the features that the BrowserRouter provides.

Back in App, you add a Routes component to select which page is shown. The Routes component behaves like a switch statement. The value it switches on is implicitly the path from the URL. Each case that the path is matched against is expressed using a Route component:

// ...
import {Route, Routes} from 'react-router-dom';
import {Quizzes} from './Quizzes';
import {Quiz} from './Quiz';
import {Question} from './Question';

function App() {
return (
<div className="App">
<Routes>
<Route path="/quizzes" element={<Quizzes />} />
<Route path="/quiz" element={<Quiz />} />
</Routes>
</div>
);
}

When you add this to your app, what shows up in the browser? Probably nothing. That's because your URL doesn't match any of the routes. Try adding the path /quizzes to the URL. Do you see the Quizzes component load? Does /quiz work too?

This is the core mechanic of switching between pages in a React app using React Router. However, you want the user to navigate to a particular page without having to manually enter a path. In a normal web site, the user navigates between pages using links. Can you use them here?