Adding a Router to React Router
Having become a little familiar with routers, we can add one of them to the application.
But first, we need to clean up our application template that we created in the previous lessons a little. More specifically, we'll work on the src folder. Throw out the assets folder, the App.css files, and the App.jsx files. In general, you'll only have main.jsx and index.css files left in it.
Open index.css and clear it completely. Let it be empty.
Now let's work on our main file main.jsx. In it we will have the following code:
import './index.css'
import React from 'react';
import ReactDOM from 'react-dom/client';
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
</React.StrictMode>
);
Now we can add the router. We use BrowserRouter because it is most often used in web applications. Let's not forget about the modern syntax. Let's add the import line:
import {
createBrowserRouter,
RouterProvider,
} from 'react-router-dom';
Then, we'll create a constant router and create our BrowserRouter after the import lines. We'll do this so that on the main page we'll display a div with the inscription 'Hello Router!'. To do this, we'll write the path to the main page and the element that we'll display:
const router = createBrowserRouter([
{
path: '/',
element: <div>Hello Router!</div>,
},
]);
We still need to add the RouterProvider component and enter the router we created above. It accepts all router objects, renders our application and connects other APIs:
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>
);
The full code will look like this:
import './index.css'
import React from 'react';
import ReactDOM from 'react-dom/client';
import {
createBrowserRouter,
RouterProvider,
} from 'react-router-dom';
const router = createBrowserRouter([
{
path: '/',
element: <div>Hello world!</div>,
},
]);
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>
);
Save the changes. Congratulations! Our application no longer complains. Now, if we launch it, we will see 'Hello Router!' on the main page in the browser.
Using the material provided, make it so that on the main page of your application, which you created in the homework for the previous lessons, you display a paragraph with the text 'I'm number one in React!'.