⊗jsrtPmRtPR 47 of 47 menu

Route without path in React Router

In this lesson we will look at another useful property of the route without a path.

You know that for each route object you can add a errorElement property and set its value to the element you want to display when an error occurs.

But what if we have the same errorElement for all routes? Of course, we can slap the same thing on each one, or we can use a route without a path, wrap the child routes we are interested in in it. Then, if an error occurs on one of them, our route without a path will catch them and display its errorElement.

Let's go to the main.jsx file and wrap all our child routes in a route without a path, making them children of it (in turn, this route will become a child of the root), don't forget to add the errorElement property to it as well:

const router = createBrowserRouter([ { path: '/', element: <Root />, errorElement: <ErrorPage404 />, loader: rootLoader, action: rootAction, children: [ { errorElement: <ErrorPage404 />, children: [ { index: true, element: <Index /> }, { path: 'products/:productId', element: <Product />, loader: productLoader, }, { path: 'products/:productId/edit', element: <EditProduct />, loader: editProductLoader, action: editAction, }, { path: 'products/:productId/delete', action: deleteAction, }, ], }, ], }, ]);

How can we test this code now? We can add a line that throws an error (don't forget to remove it when you test it). Let's, for example, add it as the first line in the action function for the product deletion route, then when we try to delete a product we'll see an error:

export async function action({ params }) { throw new Error('error'); await deleteProduct(params.productId); return redirect('/'); }

Now try to remove some product.

Take the app you created in the previous lessons. Using the lesson materials, wrap your child routes in a route without a path with the errorElement property and test that it works.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline