Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to embed two components in one component ?

  • Last Updated : 22 Oct, 2021

In the ReactJS Components, it is easy to build a complex UI of any application. We can divide the UI of the application into small components and render every component individually on the web page.

React allows us to render one component inside another component. It means, we can create the parent-child relationship between the 2 or more components.

Prerequisites: The pre-requisites for this project are:

Creating Application: The below command will help you to start a new react app.

npx create-react-app testapp

Next, you have to move to the testapp project folder from the terminal.



cd testapp

Create a new components folder inside the src folder and create two components named child1.jsx and child2.jsx files inside it.

Project directory: It should look like this.

Example: Write down the following codes in respective files.

child1.jsx




import React, { Component } from 'react';
   
class Child1 extends Component {
  render() {
    return (
      <li>
        This is child1 component.
      </li>
    );
  }
}
   
export default Child1;

child2.jsx




import React, { Component } from 'react';
   
class Child2 extends Component {
  render() {
    return (
      <li>
        This is Child2 component.
      </li>        
    );
  }
}
   
export default Child2;

Now, we will change the default code of the App.js component file. Also, we will embed the child1 and child2 components inside the App component.

App.js




import React, { Component } from 'react';
import Child1 from './components/child1';
import Child2 from './components/child2';
   
class App extends Component {
  render() {
    return (
      <div>
        <div>This is a parent component</div>
        <Child1 />
        <Child2 />
      </div>
    );
  }
}
   
export default App;

Steps to Run: To start the react app, run the below command on your terminal and verify that react app is working fine.

npm start

Output: You will see react app is started on localhost:3000 without any difficulty. Here, the App component is a parent component of the child1 and child2 components.




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!