Adding Data to React Router
In previous lessons we prepared a loader and data unloading along a specific route from the storage. Let's now get acquainted with the example of our application how to add a new product and write its data to the storage.
Let's open the root.jsx file and add a button to the layout to add a new product before nav, wrapping it in a form tag. We'll also now wrap the button and our list in another div with #menu. The layout will now look like this:
return (
<div id="main">
<div id="menu">
<form method="post">
<button type="submit">add product</button>
</form>
{products.length ? (
<nav>
{products.map((product) => (
<Link key={product.id} to={`products/${product.id}`}>
{product.name ? product.name : <i>Unnamed</i>}
</Link>
))}
</nav>
) : (
<p>
<i>no products here ...</i>
</p>
)}
</div>
<div id="product">
<Outlet />
</div>
</div>
);
If we now go to the 'Network' tab of the developer toolbar and then click our button, we'll see an erroneous document request to the server. With React Router, we'll use client-side routing again, eliminating the request to the server.
To do this, let's change the form tag to the Form React Router component. First, let's add the Form import:
import { Form } from 'react-router-dom';
Now let's replace the form tags in the code snippet:
<Form method="post">
<button type="submit">add product</button>
</Form>
Restart our application and look at the developer panel again. Click the add product button - now there is no request to the server (ignore the error for now).
Take the application you created in the assignments for the previous lessons. Using the lesson materials, correct the layout of the Root function, add a button for adding a student in the form tag. Make sure that when you click the button, a request is made to the server.
Now replace the form tag with the Form component. Make sure that when you click the add student button, no request is sent to the server.