Reputation: 161
How to change the value of props, how to setProps, suppose the value of this.props.contact.name is John, I want to change it to Johnny.
How can I do this?
For example:
changeValue(){
this.props.contact.name='Johnny'
}
Upvotes: 11
Views: 61744
Reputation: 7601
I would suggest rather then change the props value you can pass the function into props and then change the parent component state so it will change the child component props like
your Parent Component should be
class SendData extends React.Component{
constructor(props) {
super(props);
this.state = {
images: [
'http://via.placeholder.com/350x150',
'http://via.placeholder.com/350x151'
],
currentImage: 0
};
this.fadeImage=this.fadeImage.bind(this);
}
fadeImage(e) {
e.preventDefault();
this.setState({currentImage: (this.state.currentImage + 1) % this.state.images.length})
}
render()
{
return(
<FadeImage images={this.state.images} currentImage={this.state.currentImage} fadeImage={this.fadeImage}/>
)
}
}
your Child Component should be like
class FadeImage extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="image">
<CSSTransitionGroup
transitionName="example"
transitionEnterTimeout={300}
transitionLeaveTimeout={300}
>
<section>
<button className="button" onClick={this.props.fadeImage.bind(this)}>Click!</button>
<img src={this.props.images[this.props.currentImage]}/></section>
</CSSTransitionGroup>
</div>
);
}
}
Please check working example here Demo
Upvotes: 4
Reputation: 1728
Props are immutable, that means you can not change them! https://facebook.github.io/react/docs/components-and-props.html
If you want to save a new value build it as a state and use this.setState(...)
https://facebook.github.io/react/docs/state-and-lifecycle.html
Upvotes: 3
Reputation: 1782
You would change the prop
in the parent component, as that is what holds the value of the prop
itself. This would force a re-render of any child components that use the specific prop
being changed. If you want to intercept the props
as they're sent, you can use the lifecycle method componentWillReceiveProps
.
Upvotes: 7