Deleting a Route in React Router
We have written a function for deleting data from the storage. Let's now add a piece of code with a button for deleting the product to the product page layout. Let's add it right after the edit button. Wrap both forms with buttons in a div #control. Then in action we will write the value 'delete'. We will also add a dialog box for the user to confirm again whether he wants to delete the product:
<div id="control">
<Form action="edit">
<button type="submit">edit</button>
</Form>
<Form
method="post"
action="delete"
onSubmit={(event) => {
if (!confirm('Do you want to delete this product?')) {
event.preventDefault();
}
}}
>
<button type="submit">delete</button>
</Form>
</div>
Let's also add some styles to our CSS file:
div#control {
display: flex;
}
button {
margin-right: 5px;
}
Now we will create a new route for deleting a product. To do this, open the routes folder and create a delete.jsx file in it. Add the redirect import and the deleteProduct delete functions to it:
import { redirect } from 'react-router-dom';
import { deleteProduct } from '../forStorage';
And then, naturally, we write our function action, which will call deleteProduct by id, and after deleting, will redirect us to the main page:
export async function action({ params }) {
await deleteProduct(params.productId);
return redirect('/');
}
All we have to do is open main.jsx. Import our action:
import { action as deleteAction } from './routes/delete';
And set it as the value for the action method of the delete route. We will add the route object itself to the end of the children array:
{
path: 'products/:productId/delete',
action: deleteAction,
},
Now we can click on any product and delete it using the delete button. You can check the localforage of the developer panel to see this.
Take the app you created in the previous lesson assignments. Using the lesson materials, add a button to delete a student, make a new route to delete, add it to the child routes. Make sure everything works.