1

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>
Thomasjd
  • 31
  • 1
  • 4

1 Answers1

0

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

Obsidianlab
  • 667
  • 1
  • 4
  • 24
  • I understand that props.children is whats passed from parent component to functional component. However in this case its different because ErrorBoundary is a class component that wraps around other component that you might want to catch for error. I have an analogy that props.children is like your mail box to receive mail from a mail man. The mail man is like a parent component. In ErrorBoundaryClass its acting like a parent component so its like the mail man delivering a mail box to lower components. – Thomasjd Jul 14 '22 at 18:11