Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change value of prop in react?

Tags:

reactjs

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'
}
like image 374
Smith Steve Avatar asked Jun 13 '17 10:06

Smith Steve


People also ask

Can we change the value of props?

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 .

How do I change state of props in React?

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.

Can we change the value of props in child component in React?

@Gopika, yes you can change props value in child component as but it is not a best practise.

How do I change the default value of props in React?

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 .


1 Answers

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

like image 194
Dhaval Patel Avatar answered Oct 23 '22 04:10

Dhaval Patel