Skip to content
Advertisement

How to make this code compatible for react-router v6

In ProtectedRoute.js I have coded:

JavaScript

and in App.js I have written as:

JavaScript

Error says: [ProtectedRoute] is not a Route component. All component children of Routes must be a Route or <React.Fragment>.

Is there something missing! Thank you

Advertisement

Answer

In react-router-dom custom route components are no longer used. Routes components can have only Route and React.Fragment components as children, and Route components can have only Routes or other Route components as a parent.

Instead wrapper components handle the business logic and either render the children prop or an Outlet for nested Route components, or the Navigate for redirection.

Render children

JavaScript

JavaScript

Render Outlet

JavaScript

JavaScript

The benefit of using the Outlet is you can use a single auth wrapper component and render any number of nested Route children into them, whereas with the children method you cannot render nested routes unless you wrap them in a Routes component.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement