I'm trying to update state within an onClick event handler according to props. in the console.log I'm getting empty string as the initial state value.
I already tried to change the component to function using state hooks instead of state. I tried to use method to update the state when onClick is invoke. I already tried to use the suggestions in the answers of a similar questions, this case is different, maybe because I'm using the setState within the event handler.
does any one know what is the problem here ? thanks in advance!
class DropDownItem extends Component {
constructor(props) {
super(props)
this.state = {
selectedItem : ""
}
this.updateItem = this.updateItem.bind(this)
}
updateItem (item) {
this.setState({selectedItem : item})
}
render(){
return (
<div>
<DropdownItem onClick={() => {
this.updateItem(this.props.product)
console.log("item",this.state.selectedItem)
}}
>{this.props.product}</DropdownItem>
<DropdownItem divider/>
</div>
)
}
}
here is the body of the parent component :
render() {
const productItems = this.state.products.map((productValue,index) => {
return(<DropDownItem key={index} product={productValue.name} />)
})
return (
<div>
{this.state.products[0] && Array.isArray(this.state.products) ?
<div>
<DropdownComponent
isOpen={this.state.dropdownOpen}
toggle={this.toggle}
product={productItems}
/>
</div> :
<div>loading...</div>}
</div>
)}
I want to update state in order to show the clicked dropdown item to the user.