Open In App

How to embed two components in one component ?

Last Updated : 30 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

Prerequisites

Approach

To show embed components in one component in React we will create two functional components named child1 and child2 and import them in the App.js directory to render them on the UI.

Creating React Application

Step 1: Use this command to create a new react project

npx create-react-app testapp

Step 2: Move to the testapp project folder from the terminal.

cd testapp

Project Structure:

It should look like this.

Example: Shows two child components embeded in App.js component.

Javascript




// Filename - App.js
 
import React, { Component } from "react";
import Child1 from "./components/child1";
import Child2 from "./components/child2";
import "./App.css";
 
class App extends Component {
    render() {
        return (
            <div className="App">
                <h1 className="geeks">GeeksforGeeks</h1>
                <h3>Embedding two child components</h3>
                <div>This is a parent component</div>
                <br />
                <Child1 />
                <Child2 />
            </div>
        );
    }
}
 
export default App;


Javascript




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


Javascript




// Filename - components/child2.jsx
 
import React, { Component } from "react";
 
class Child2 extends Component {
    render() {
        return <li>This is child2 component.</li>;
    }
}
 
export default Child2;


CSS




/* Filename - App.css */
 
.App {
    text-align: center;
    margin: auto;
}
 
.geeks {
    color: green;
}


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.

Screenshot-from-2023-10-25-15-21-07



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads