Reputation: 1500
I have a modal component for saving recipes to a list.
modal = <Modal saveRecipe={this.saveRecipe} closeModal={this.toggleModal}/>
Also I want to use this same modal component to edit the recipe, so i do this
if(this.state.editItem){
modal = <Modal content={editContent} saveRecipe={this.saveRecipe} closeModal={this.toggleModal}/>
}
else{
modal = <Modal saveRecipe={this.saveRecipe} closeModal={this.toggleModal}/>
}
so I'm able to pass down the object to be edited to Modal Component. The modal component has a text input and a textarea element.
constructor(props) {
super(props);
this.state = {dish: '', ingredients:[]};
}
componentWillReceiveProps(nextProps){
console.log(nextProps) // Never fired..why??
let {dish, ingredients} = nextProps.content
this.setState({
dish:dish, ingredients:ingredients
})
}
render(){
let {dish, ingredients} = this.state
console.log(this.props) // {dish:"new dish", ingredients:['ingreds']}
return(
<div className="modal">
<input type="text" ref="title" value={dish} />
<textarea ref="ingredients" value={ingredients}></textarea>
</div>
)
I want to prepopulate the modal form elements when edit is clicked. I am able to populate the input and textarea field if I provide
let {dish, ingredients} = this.props
instead of this.state
. But then the form field become uneditable. So referring to forms, I am trying to change state of Modal Component. In my code componentWillReceiveProps
is never fired? How does the componentWillRecieveProps work exactly in this situation? How to update modal component with new props?
Upvotes: 0
Views: 1226
Reputation: 16472
In your case you have to use componentDidMount
because when editItem
state is set, then you are unmounting Model
component and remounting it with content
prop. So in that case componentWillRecceiveProps
will not get fired but componentDidMount
will get fired. So move your componentWillReceiveProps
logic to componentDidMount
like
componentDidMount(){
console.log(this.props) // Never fired..why??
let {dish, ingredients} = this.props.content
this.setState({
dish:dish, ingredients:ingredients
})
}
Upvotes: 2