Friday, April 18, 2025
Google search engine
HomeLanguagesHow to embed two components in one component ?

How to embed two components in one component ?

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.

Javascript




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


Javascript




// 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.

Javascript




// 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.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments