What is this.props.children for React error boundaries returned when there is no error?

1.1k Views Asked by At

I understand that a higher component can pass props in between open and closing tags of a functional component that it will render. In react error boundary component this.props.children is being returned to the component that its wrapping (App.js). What is this.props.children thats is being returned if there is no error?

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // You can also log the error to an error reporting service
    logErrorToMyService(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children; 
  }
}

Then you can use it as a regular component:

<ErrorBoundary>
  <MyWidget />
</ErrorBoundary>
1

There are 1 best solutions below

1
On

From what i can gather here this piece of code shows that if there is an error it returns the error message and if there isnt an error it returns the children of the component.

As you can see below the children props are any other components placed in between the open and closing tags of a functional component.

function FancyBorder(props) {
  return (
    <div className={'FancyBorder FancyBorder-' + props.color}>
      {props.children}
    </div>
  );
}

function WelcomeDialog() {
  return (
    <FancyBorder color="blue">
      <h1 className="Dialog-title">
        Welcome
      </h1>
      <p className="Dialog-message">
        Thank you for visiting our spacecraft!
      </p>
    </FancyBorder>
  );
}

See below for reference:

https://reactjs.org/docs/composition-vs-inheritance.html#containment