Skip to content
Related Articles

Related Articles

How to apply an id attribute to a child element of a ReactJS component ?
  • Difficulty Level : Easy
  • Last Updated : 07 Apr, 2021

We can get the ID attribute of a ReactJS component from the props of the ReactJS component. As we are inside a ReactJS component here we are going to use this.props instead of props. If the ID attribute has been passed as id to the ReactJS component then we can use the following to get the ID attribute passed:

this.props.id

Once we get the ID attribute we can easily pass it to any child element to which we wish to pass it as shown below.

<child_element_name id = {this.props.id}>

Creating React Application:

  • Step 1: Create a React application using the following command:

    npx create-react-app foldername
  • Step 2: After creating your project folder i.e. foldername, move to it using the following command:



    cd foldername

Project Structure: It will look like the following.

Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.

App.js




import BodyComponent from './Bodycomponent.js';
  
function App() {
    return (
        <div>
            <header>Hello and Welcome</header>
            <BodyComponent id='childid' />
        </div>
    );
}
  
export default App;

Bodycomponent.js




import React from 'react';
  
function BodyComponent(props) {
    return (
        <p id={props.id}>
            This is the content with the ID 'childid'.
            It has been supplied with the ID attribute of 
            the React component.
        </p>
  
    );
}
  
export default BodyComponent;

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

My Personal Notes arrow_drop_up
Recommended Articles
Page :