How to prevent Router from accessing routed without valid id?

Viewed 73

In my my App.js file I used this Switch logic:

              <Switch>
                <Route path='/' exact component={Dashboard}/>
                <Route path='/question/:id' exact component={QPage}/>
                <Route path='/new' exact component={CreateQ}/>
                <Route path='/leaderboard' exact component={Leaderboard}/>
                <Route component={Error}/> 
              </Switch>

The code above works as expected. My only problem is, when the Router accesses /question/:id and therefore renders the QPage component. Then, React throws an error of undefinded because inside of the QPage component, elements try to access the id and other props (which they take out of the url). How can I prevent the Router from accessing routes with invalid ids?

1 Answers

Two options come to mind, both relying on history package:

  1. wrap the Qpage component in an Error Boundaries class, and call history.goBack() within componentDidCatch method https://reactjs.org/docs/error-boundaries.html

  2. Within Qpage's componentDidMount, call history.goBack() if API fails to return a question. Also, conditionally render the return around the state property you store the API result in.

{!this.state.property? <div/> : <div> . . . </div>}

Make sure to use history version 4.10.1 if React-Router-DOM is 5.2.0

history.js

import { createBrowserHistory } from 'history';
const history = createBrowserHistory();
export default history;

index.js

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import {Router} from 'react-router-dom'
import history from './history.js'

ReactDOM.render(
    <Router history={history}>
        <App />
    </Router>,
    document.getElementById('root')
)

Qpage or Error Boundaries

import history from './history'
Related