close

How to access a child’s state in React

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How to access a child’s state in React in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How to access a child’s state in React ?

  1. How to access a child's state in React ?

    access a child's state in React As the previous answers said, try to move the state to a top component and modify the state through callbacks passed to its children.

  2. access a child's state in React

    access a child's state in React As the previous answers said, try to move the state to a top component and modify the state through callbacks passed to its children.

Method 1

As the previous answers said, try to move the state to a top component and modify the state through callbacks passed to its children.

In case that you really need to access to a child state that is declared as a functional component (hooks) you can declare a ref in the parent component, and then pass it as a ref attribute to the child, but you need to use React.forwardRef and then the hook useImperativeHandle to declare a function you can call in the parent component.

Take a look at the following example:

const Parent = () => {
    const myRef = useRef();
    return <Child ref={myRef} />;
}

const Child = React.forwardRef((props, ref) => {
    const [myState, setMyState] = useState('This is my state!');
    useImperativeHandle(ref, () => ({getMyState: () => {return myState}}), [myState]);
})

Then you should be able to get myState in the Parent component by calling:

myRef.current.getMyState();

Method 2

Now you can access the InputField’s state which is the child of FormEditor.

Basically, whenever there is a change in the state of the input field (child), we are getting the value from the event object and then passing this value to the Parent where in the state in the Parent is set.

On a button click, we are just printing the state of the input fields.

The key point here is that we are using the props to get the input field’s id/value and also to call the functions which are set as attributes on the input field while we generate the reusable child input fields.

class InputField extends React.Component{
  handleChange = (event)=> {
    const val = event.target.value;
    this.props.onChange(this.props.id , val);
  }

  render() {
    return(
      <div>
        <input type="text" onChange={this.handleChange} value={this.props.value}/>
        <br/><br/>
      </div>
    );
  }
}


class FormEditorParent extends React.Component {
  state = {};
  handleFieldChange = (inputFieldId , inputFieldValue) => {
    this.setState({[inputFieldId]:inputFieldValue});
  }
  // On a button click, simply get the state of the input field
  handleClick = ()=>{
    console.log(JSON.stringify(this.state));
  }

  render() {
    const fields = this.props.fields.map(field => (
      <InputField
        key={field}
        id={field}
        onChange={this.handleFieldChange}
        value={this.state[field]}
      />
    ));

    return (
      <div>
        <div>
          <button onClick={this.handleClick}>Click Me</button>
        </div>
        <div>
          {fields}
        </div>
      </div>
    );
  }
}

const App = () => {
  const fields = ["field1", "field2", "anotherField"];
  return <FormEditorParent fields={fields} />;
};

ReactDOM.render(<App/>, mountNode);

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment