Hammer
Hammer

Reputation: 3

change the state of the child component

I am having a Parent Component and a child component

export default class CityPart extends Component {
    constructor(props)
    {
        super(props);
        this.state ={
            citylist: citylist
            selectedflag:1
        }

    }
    Clickme(idd){
     this.setstate({selectedflag:idd})
}
    render() {
        return (
        <div className="CityPartMain">
            {this.state.citylist.map((item)=>{
                return (
                <EachCity name ={item.name} key={item.id}
                id={item.id}
                selected={this.state.selected}
                Clickme ={this.Clickme}
                />
                )
            })}
        </div>
        );

    }
}
export default class EachCity extends Component { 
    render() {
        const {name,id,selected,Clickme} = this.props;    
        return (
            <button 
            onClick={this.Clickme(id)}
            className={selected===parseInt(id,10)?"selectedcity": "EachCityMain"}>
            <p>{name}</p>
            </button>
        );
    }
}

whenever i click on the button i want that id should come to my parent component and it should get updated in the selectedflag of the parent state.

Thanks for help in advance.

Upvotes: 0

Views: 41

Answers (2)

blonial
blonial

Reputation: 81

You have made two mistakes. First one is in your parent - this is how you should implement method Clickme:

Clickme = (id) => {
    this.setState({selectedflag:idd})
}

In your implementation this means object, which is calling method (child), so this.setState() will work for child. When you use lambda expression - it will work for parent.

Second mistake is how are you calling Clickme in your child component. You should make it like:

<button 
    onClick={() => Clickme(id)}
    className={selected === parseInt(id,10) ? "selectedcity" : "EachCityMain"}
    >
        <p>{name}</p>
</button>

If you are calling function without parameters, you can just pass function to onClick. In your case you have to create anonymous function to call it with parameter. Additionaly this is unnecessary.

Upvotes: 3

Drew Reese
Drew Reese

Reputation: 203418

Your Clickme callback is getting called right away (remember, function() is called right then) and you are just storing the result of that call in the onClick handler. You're also using this. Try instead setting it as a callback using an anonymous arrow function.

export default class EachCity extends Component { 
  render() {
    const { name, id, selected, Clickme} = this.props;    
    return (
      <button 
        onClick={() => Clickme(id)}
        className={selected===parseInt(id,10) ? "selectedcity" : "EachCityMain"}
      >
        <p>{name}</p>
      </button>
    );
  }
}

If this is unclear to you and how and why it works, I can add a codesandbox example with more detail.

Upvotes: 0

Related Questions