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'
}
You can't change the value of props but you still have options to change values that you can use. You have two options: Either you change it from the parent component or you use state instead of props. Where ChildComponent has your code to use this.props.name .
To update state when props change in React: Pass the props as dependencies to the useEffect hook. Every time the props change, the logic in useEffect is reran.
@Gopika, yes you can change props value in child component as but it is not a best practise.
For example, let's create a CustomButton class in React that takes color as a prop. To set a default value for the color prop, use the defaultProps property of CustomButton to set the default value of color to blue .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With