⊗jsrtPmRtANR 26 of 47 menu

Adding another route to React Router

We have a root route that goes to the home page where we have links for products. Let's now add another route so that when we click one of the links, we get the product page instead of an error screen.

First, let's open our application that we made in the previous lessons and create a file product.jsx in the routes folder. Let's create a component Product in it:

function Product() {} export default Product;

Now let's create inside Product an object product, with properties name, cost and amount, for now these will be some fixed values:

function Product() { const product = { name: 'Product', cost: 400, amount: 5, }; } export default Product;

And on the product page we will display, accordingly, its name, cost and quantity:

return ( <div> <h2>Product page</h2> <p>Name: {product.name}</p> <p>Cost: {product.cost}</p> <p>Amount: {product.amount}</p> </div> );

Be sure to add the import of the Product component to the main.jsx file:

import Product from './routes/product';

And finally, let's add another route to our application, we'll do it right after the root one. We'll specify 'products/:productId' as the path, and the Product component will act as the display element:

{ path: '/', element: <Root />, errorElement: <ErrorPage404 />, }, { path: 'products/:productId', element: <Product />, },

Now we launch the application, click on the links and find ourselves on the page with the product (for now it is the same for all links), and not with an error.

Take the application you created in the previous lessons. Using the lesson materials, create a file student.jsx in a similar way, let the student page display their first name, last name, year of admission and specialty. Add a new route for the student page in the file main.jsx, set the value of path to 'students/:studentId'. Make sure that when you click on the links, you are now taken to the student page.

enru