Skip to content
Related Articles

Related Articles

Improve Article
How to get key attribute of parent div when button is clicked in ReactJS ?
  • Last Updated : 07 Apr, 2021

In ReactJs we can pass properties in the child component from the parent component. So, we are going to do the same and pass the key of a parent as a property in the child component.

Creating React Application And Installing Module:

  • 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

Step 3: Create Parent.js and Child.js components.



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 React, { Component }  from 'react';
  
import Parent from './Parent';
  
class App extends Component {
  
  state = {
    key: "GFG",
  }
  
  render() {
    return (
      <div>
        <h2>GeeksforGeeks</h2>
        <Parent key={this.state.key} keyValue={this.state.key}/>
      </div>
    );
  }
}
  
export default App;

Parent.js




import React, { Component }  from 'react';
  
import Child from './Child';
  
class Parent extends Component {
  
  render() {
    return (
        // Passing key in child
        <div>
            <h3>(Parent.js) Key = {this.props.keyValue}</h3>
            <Child keyValue={this.props.keyValue}/>
        </div>
    );
  }
}
  
export default Parent;

Child.js




import React, { Component }  from 'react';
  
class Child extends Component {
  
  state = {
    key: "",
  }
  
  handleClick = () => {
    this.setState({key: this.props.keyValue});
  }
  
  render() {
    return (
      <div>
        <h3>(Child.js) Key = {this.state.key}</h3>
        <button onClick={this.handleClick}>
            Get Parent Key
        </button>
      </div>
    );
  }
    
}
  
export default Child;

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 :