Skip to content
Related Articles

Related Articles

How to access child’s state in React?
  • Last Updated : 01 Feb, 2021
GeeksforGeeks - Summer Carnival Banner

In React we can access the child’s state using Refs.  we will assign a Refs for the child component in the parent component. then using Refs we can access the child’s state.

Creating Refs Refs are created using React.createRef() and attached to React elements via the ref attribute.

class App extends React.Component {
constructor(props) {
 super(props);
 //creating ref
 this.childRef= React.createRef();
}
render() {
 return (
 //assigning the ref to child component
 <Child ref= {this.myRef } />
 )
}
}

Accessing Refs When we assign a ref to an element or child component in the render, then we can access the element using the current attribute of the ref.

const element = this.myRef.current;

in the same way, we can access the state using element.state.state_name from the parent component.

Create a react app and edit the App.js file as:



Filepath- src/App.js

Javascript




import React from "react";
import Child from './Child'
  
class App extends React.Component {
  constructor(props) {
    super(props);
    this.ChildElement = React.createRef();
  }
  handleClick = () => {
    const childelement = this.ChildElement.current;
      alert("current state of child is :  "+ childelement.state.name);
    childelement.changeName("Aakash");
      
      
  };
  render() {
    return (
      <div >
        <Child ref={this.ChildElement} />
        <button onClick={this.handleClick}>Show real name</button>
      </div>
    );
  }
}
export default App

Create a new Child.js component in src folder and edit it as follow:

Filepath- src/Child.js:

Javascript




import React from 'react'
class Child extends React.Component {
  state = {
    name: "Batman"
  };
  changeName = (newname ) => {
    this.setState({
      name:newname
    });
  };
  render() {
    return <div>{this.state.name}</div>;
  }
}
export default Child

Output:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :