Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

Understanding this.props.children with an example

Understanding this.props.children with example

In this chapter, you will learn how to use this.props.children with an example. In the last chapter, we studied what is props and how to pass it to the component. As we know we are passing the attributes inside the Employee component. We can pass some list or paragraph from the outside of the component Employee.
As we can see in the below output, we are accessing the children property of a component by using this.props.children method. We haven’t passed the children for the component stark and Mickel so its empty here. We can see the children output for the component John as we passed the children property to it.
Step 1:
Create the file src/Employee/Employee.js if you have it already paste the below code snippet
import React from 'react';

const employee = (props) => {
return (
        <div>
                <p>Hi I am {props.name} and my employee ID: {props.empId}</p>
                <p> {props.children}</p>
        </div>
    )
}

export default employee;
Steps 2:
Create the file src/App.js if you have it already paste the below code snippet
import React, {Component} from 'react';
import './App.css';
import Employee from './Employee/Employee'
class App extends Component {
  render() {
    return (
      <div className="App">
        <h1>Welcome to react JS tutorial</h1>
        <Employee name='Stark' empId='123'/>
        <Employee name='Mickel' empId='124'/>
        <Employee name='John' empId='125'> My department is IT</Employee>
      </div>
    );
  }
}

export default App;
Now look at the URL: http://localhost:3000/
You should be able to see the output
children property example

One thought on “Understanding this.props.children with an example

Comments are closed.