Saturday, November 16, 2024
Google search engine
HomeLanguagesHow to access child’s state in React?

How to access child’s state in React?

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:

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