6. Next Steps
After installing the dependencies, we can incorporate the library into our app. To ensure a comprehensive understanding of the steps involved, we present the theory alongside a practical example. This approach allows us to observe how the theory is applied in real-world scenarios, highlighting the necessity of each step.
Step 1: Enable routing functionality
To incorporate routing functionality into our application, we must wrap the root component with
Let's open the
index.js file and import the
BrowserRouter component from the
Next, wrap the
App component with the
BrowserRouter (line 9-11):
Routing functionality is available in our application, allowing us to navigate between different pages based on the URL.
Step 2: Define routes
Now, we can specify the routes (paths) that our app will include. It is crucial to define these paths in advance as they determine the overall structure of the app. The React Router library offers
Route components to simplify this implementation. We can use the following syntax to define the routes:
We wrap all the routes with the
Routes component. Each
Route is defined with the
path prop, which specifies the URL configuration, and the
element prop, which determines the component to render when a user navigates to that specific path.
Example: Let's start by opening the
App.jsx file and importing the
Route components from the
Next, within the
return statement, we need to define the routes for our app. It's important to keep in mind that we have three views:
HomePagecomponent represents the home page view.
AboutPagecomponent represents the about page view.
ContactsPagecomponent represents the contacts page view.
Here is the code to be included in the return statement of the App component:
- Line 4, 8:
<Routes>: This component is a container for defining routes in the application. It acts as a parent component for all the individual routes we define within it.
- Line 5: It represents a route definition. It specifies that when the URL path matches
/, the component
<HomePage />should be rendered.
- Line 6: It defines another route. When the URL path matches
/about, the component
<AboutPage />will be rendered.
- Line 7: It defines yet another route. When the URL path matches
<ContactsPage />component will be rendered.
The code provided contains errors because we haven't imported the components necessary for rendering. In the next chapter, we will address this issue and demonstrate the correct syntax for importing components, which is different from what we typically use.
What specific component needs to be used to enable the React Router library in an application?
Select the correct answer
Everything was clear?