reactjsreact-routerreact-router-domreact-router-component

React router - How to redirect to child component if parent component path is entered in url


I would like to redirect my url for e.g to '/questions/1' when I only write /questions


Solution

  • You can render a redirect from one path to the other.

    If using react-router-dom v5 use the Redirect component:

    <Redirect from="/questions" to="/questions/1" />
    

    If using react-router-dom v6 use the Navigate component:

    <Route path="/questions" element={<Navigate to="/questions/1" replace />} />