React-router: How to handle/catch errors when rendering components in router

Created on 21 Oct 2015  路  4Comments  路  Source: ReactTraining/react-router

Hi Guys,

When we have errors in a component of the router, the entire tree might get taken down.
For example, in the router below, we have many route paths, and each path is a react component. When rendering any component, if there is an error, the router then gets to a bad state, and any further actions(e.g. a user click a link to render another route component ) may fail.
What would be the work around to catch/handle the errors in component rendering? And is there a way to handle the errors in the components level?

The use case here is:
In a component, I am rendering a basic framework + some other children components. Then I get errors when rendering the children components.
In this scenario, I want to keep the basic framework + render some errors messages to user, so I might need to find a way to handle/catch the errors in the component. Any ideas or suggestions?

render((
  <Router>
    <Route path="/" component={App}>
      <Route path="about" component={About}/>
      <Route path="users" component={Users}>
        <Route path="/user/:userId" component={User}/>
      </Route>
    </Route>
  </Router>
), document.body)

All 4 comments

This is not really React Router specific. You'd catch the component error however you do normally with buggy render functions, and then handle that error somehow.

But otherwise this is no different from if you were rendering the component tree without React Router.

How to catch the errors if my render function simply just returns some other children components, and the errors are thrown from the children components? And sometimes the components we use may come from some third party libraries where not all the errors are handled.

    render () {
        return (
            <div className="Framework">
                <some layouts in general framework>
                <Component1>
                <Component2>
                <Component3>
            </div>
        );
    }

And if any error occurs in the children render function,
I want to catch/handle the errors in the parent component level, because I want to show something like

    render () {
        return (
            <div className="Framework">
                <some layouts in general framework>
                <some errors>
            </div>
        );
    }

@taion

The same way you'd do it without React Router. There's just nothing RR specific here.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

davetgreen picture davetgreen  路  3Comments

ackvf picture ackvf  路  3Comments

maier-stefan picture maier-stefan  路  3Comments

Radivarig picture Radivarig  路  3Comments

sarbbottam picture sarbbottam  路  3Comments