Tuesday, August 7, 2018

Parent - Child components example in React

We have so far seen some simple components which don't have a parent - child relationship, but when we create larger page we cannot implement the full application in a single component. Large page often have a root parent component and multiple levels of child components each acting like a widget in the parent component. In this example we shall see on how to embed child components into a parent component and render the output from both the components.

In this example we will have 2 separate files for the parent and the child components, we will import the child component into the parent component and display the child component in the parent components render method.
child.jsx
import React, { Component } from 'react';

class ChildComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  render() {
return (
  <div> 
   <div style={{color: 'red',border: '2px solid red', height: '100px', width: '100px', margin: '10px'}}>
Hello from Child Component
</div>
  </div>
);
  }
}

export default ChildComponent;

parent.jsx
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import ChildComponent from './child.jsx';

class ParentComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  render() {
return (
  <div>
<div style={{color: 'blue',border: '2px solid blue', height: '200px', width: '200px', margin: '10px'}}>
Hello from Parent Component. <br/>
<ChildComponent/>
</div>
  </div>
);
  }
}

ReactDOM.render(<ParentComponent />, document.getElementById('app'));

Output


Search Flipkart Products:
Flipkart.com

No comments: