ReactJs: How to recover errors in child component?

I am creating a live code editor for my library and because of this some components may throw an exception on rendering due to invalid input. This is expected behavior.

My problem now is that the whole page crashes when the input is invalid.

What I wanted was an exception way catch

and show a red alert where the component should be. Again, this is a live code editor, things are expected to break.

I cannot find a way to get around this. Any idea?

+3


source to share


2 answers


IME, each implementation render()

must correctly handle exceptions when building its component subtree.

Due to the React DOM update buffers, however, the subcomponents are not in - render

for deeper in the stack, this is more like:

class Main extends React.Component {
  render() { return <div className="wrapper"><Child question={think()} /></div> }
}

class Child extends React.Component {
  render() { return <div className="child-stuff" /> }
}

React.render(<Main answer={42} />, document.getElementById('reactRoot'))

      

.. will call Main#render

, which will then execute the queue Child.render

for execution, then execute it either later in the event loop, or at the next tick, etc.



This asynchronous execution means that you can only reliably throw exceptions in a method #render

for the code it executes directly ( think()

), but not what the child component does #render

.

I believe this precludes using higher-order components to handle arbitrary exceptions (e.g. program / data errors), although I agree with Philip that this is a great answer for general (predictable) error handling.

See React # 2461 for details , but I believe this is the current state of affairs.

+1


source


Good point, which you can insert - is when you create React elements, through React.render

, React.createElement

, React.cloneElement

:

try {
  React.render(<Editor />, container);
} catch (e) {
  // Something went wrong. Let recover.
  React.render(<ItsNotMeItsYourComputer />, container);
}

      



So something like this in a global context will help you restore when you create and set your editor to the DOM. However, for better control, you probably want to write either higher-order components or custom controller views that have a concrete way to create and manipulate child components, with the added ability to display a general view Error

in case of things wrong.

0


source







All Articles