Props.children react – A quick intro to React’s props.children

INTRODUCTION

Props.children react: At the first sight, the this.props.children can be a bit overwhelming when studying class based components. As many developers and tutorials use React class based components as it gives access to state, it is very necessary to be familiar with props.children (if you are using stateless functional components) and this.props.children (if you are using class components)

What is ‘children’?

What this.props.children  does is that it displays whatever you include between the opening and closing tags when invoking a component.

A simple example

For example, in a class based component.

import React, { Component } from "react";

class Welcome extends Component {
  render(props) {
    return (
      <div>
        <p>Hello Class Component</p>
        <p>{this.props.children}</p>
      </div>
    );
  }
}
export default Welcome;

Here the component is receiving children from , say, app.js which can be passed in the manner shown below.

import Welcome from "./components/React/Welcome";

function App() {
  return (
    <>
      <div className="App">
        <Welcome children="I am a child" />
      </div>
    </>
  );
}

export default App;

As you can see, when the string “I am a child” is passed through to the Welcome component the output looks similar to what is shown below.

Hello Class Component.

I am a child 

Whenever this component is invoked {props.children} will also be displayed and this is just a reference to what is between the opening and closing tags of the component.

 

A complex example

I will now demonstrate an error solving method via this.props.children , where if there is an error in code it will display Something Went Wrong  or if it is error free code it will simply say Error Free Code

import React, { Component } from "react";

class ErrorBoundary extends Component {
  constructor(props) {
    super(props);

    this.state = {
      hasError: true,
    };
  }

  componentDidCatch(error, info) {
    console.log(error);
  }

    render() {
        if (this.state.hasError) {
        return <h1>Something Went Wrong</h1>;
        } else if (!this.state.hasError) {
        return (<>
                   <h1>Error Free Code</h1>
                   {this.props.children};
                </>);
        }
    }
    }
export default ErrorBoundary;

So, if there is error in the code, then the first return statement will be implemented and all others will be ignored. Or else, the this.props.children that is passed via another (parent) component will be displayed.

 

CONCLUSION

I hope this shed a little bit more light on React and how you can use props.children to help you customize your app’s content while still being able to reuse the same components in my case for error checking purposes.