Installing React Router in Redux Application
In previous lessons we installed the basic tools for working with Redux. It often happens that an application needs a router to navigate its web pages, and our application will not be an exception. To do this, we will install the React Router library.
Let's open our project and type the following command in the terminal:
npm install react-router-dom
Jumping ahead a bit, I will say that our Redux application is traditionally dedicated to products, information about which is posted by some sellers. Therefore, now we will slightly rework the main component App
, and also add functionality to the application for implementing routing.
First, let's go to the src
folder, then to app
and create a file root.jsx
here. This will be the root of our site: on the left we will have a menu, and on the right - content (for now we only have a heading here):
function Root() {
return (
<div id="main">
<div id="menu">
<nav>
<a>Products</a>
<a>Sellers</a>
</nav>
</div>
<div id="main_page">
<h2>This is my first Redux app!</h2>
<hr></hr>
</div>
</div>
)
}
export default Root
And we will remake the App
component. First, we will completely delete its contents. Then we will import two functions for the router and our root component Root
:
import { createBrowserRouter, RouterProvider } from 'react-router-dom'
import Root from './app/root'
Below, after import, we will create a router and write the first route, passing it our Root
as a display element and, accordingly, setting the path to '/'
. Later, we will add other necessary routes to App
:
const router = createBrowserRouter([{ path: '/', element: <Root /> }])
Below we write the code for the function App
:
function App() {
return <RouterProvider router={router} />
}
export default App
That's it. Let's launch. In the next section, we'll implement the components for the Redux application to work.
Finally, let's add a little beauty by writing styles for this in index.css
:
body {
font-size: 24px;
line-height: 1.5;
}
nav {
display: flex;
flex-direction: column;
}
ul {
list-style: none;
padding: 0;
}
h1, h2, h3 {
margin: 0;
}
a {
text-decoration: none;
color: blue;
cursor: pointer;
}
#main {
display: flex;
margin: 20px;
}
#menu {
margin-right: 50px;
padding-top: 50px;
padding-right: 50px;
border-right: 2px solid lightgray;
font-weight: bold;
}
Add React Router to your app.
Let your app be about students, whose information will be posted by teachers. With this in mind, create a root component Root
. Redesign the component App
as described in the tutorial.