hu7sy
hu7sy

Reputation: 961

how to update parent state in child component and pass to parent state back?

I am passing object from parent componet to child component and there some input fields in child component which handled in parent component as follow:

import React, { Component } from "react";
import Child from 'path';

class parent extends Component {
    constuctor(props){
        super(props);
        this.state = {
            obj :{
                //object
            }
        }
        this.handlerInput =  this.handlerInput.bind(this);
    }

    handlerInput(e){
        //logic to update state obj
    }
    render(){
        return(
            <div className="content">
                <Child changeHandle={this.handlerInput}  />
            </div>
        );
    };
}



export default parent;



import React, { Component } from "react";

class Child extends Component {
    render(){
        return(
            <div className="content">
                <input type="text" onChange={ this.props.changeHandle } name="xyz" />
            </div>
        );
    };
}



export default Child;

Now lets suppose if i have to use child component at multiple places so every time i have to define changeHandle function in parent component?

Any suggestion to update parent state from child ?

Upvotes: 1

Views: 86

Answers (1)

Harshal T
Harshal T

Reputation: 26

You can try something like that

import React, { Component } from "react";
import Child from "./Child";
class Parent extends Component {
    constructor(props){
        super(props);
    }
  state = {
      name: 'Parent',
  };

  changeHandle = e => {
    this.setState({ name: e.target.value });
  };

  render() {
    return (
      <div>
        <Child changeHandle={this.changeHandle} name={this.state.name}/>
      </div>
    );
  }
}

export default Parent;


import React, { Component } from "react";
class Child extends Component {
  constructor(props) {
    super(props);
  }
  state = {
    name: "Child"
  };
  render() {
    return (
      <div className="content">
        <input
          type="text"
          onChange={this.props.changeHandle}
          name="xyz"
          value={this.props.name}
        />
      </div>
    );
  }
}

export default Child;

Upvotes: 1

Related Questions