Learn

In order to use React Router, you will need to include the react-router-dom package (the version of React Router built specifically for web browsers) in your project by using npm like so:

npm install --save [email protected]

Once you have added react-router-dom to your project, you can import one of its routers to add routing to your project. React Router provides multiple routers, however, the most common one is createBrowserRouter. The other options, and the reasons you might choose one over the other, are outside the scope of this lesson. If you are interested, you can read more about alternative routing options here.

To add a router to our project, we can import it at the top of our file, like so:

import { createBrowserRouter } from 'react-router-dom';

Next, we’ll initialize our router by calling createBrowserRouter. This method accepts a list of JSX components (we’ll discuss this more in the upcoming exercises):

import { createBrowserRouter } from 'react-router-dom'; const router = createBrowserRouter( /* application routes are defined here */ );

The router serves as the basis for all the React Router logic. Without it, we’d get errors if we tried using React Router components or methods. Let’s practice defining a router for our application.

Instructions

Task 1

Before we can install react-router-dom, we need to install all of the dependencies for this project. This can be done by running the command below in your terminal:

npm install
Hint

In the root directory of the project, run the command
npm install

You should see a folder called node_modules appear in your file system.


Task 2

Next, install [email protected].

To verify that you have successfully added the package to your project, navigate to package.json and check that react-router-dom appears in the “dependencies”.

Hint

Your terminal command should look like this:
npm install --save [email protected]

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?