0

I am trying to make a component which receiving a function as a props. i want to pass some value into function while calling it:

class Course extends Component {
    render() {
        return (
             <div>
                 <div id="courses">
                      <p onClick={this.props.sumPrice}>{this.props.name}<b>{this.props.price}</b></p>
                 </div>
             </div>
        );
     }
 }

sumPrice is a function define in parent component and its need a value. This is my sumPrice function and parent class constructor code:

constructor(props) {
    super(props);

    this.state = {
        active: false,
        total: 0
    };

    this.sumPrice = this.sumPrice.bind(this);
}

sumPrice(price) {
    this.setState({ total: this.state.total + price });
}

1 Answer 1

4

Usually the closure, arrow function in render handles such situations exactly how it is needed:

<div id="courses">
    <p
      onClick={() => this.props.sumPrice(this.props.price)}
    >
      { this.props.name }<b>{ this.props.price }</b>
    </p>
</div>

While it works as expected, unfortunately it comes at cost ot performance penalty Why shouldn't JSX props use arrow functions or bind?. The impact does not have to be dramatic problem but should be generally avoided.


The optimal solution is to use the functions which are not recreated on each re-render, like class method:

class Course extends Component {
    constructor(props) {
        super(props)

        this.onClick = this.onClick.bind(this)
    }

    onClick () {
      const { sumPrice, price } = this.props

      sumPrice(price)
    }

    render() {
        return (
             <div>
                 <div id="courses">
                      <p onClick={this.onClick}>{this.props.name}<b>{this.props.price}</b></p>
                 </div>
             </div>
        )
     }
  }

Avoiding performance issues.

Sign up to request clarification or add additional context in comments.

2 Comments

this solution is giving Cannot read property 'props' of undefined error
The second solution also needs manually binding eg in constructor like it was in this.sumPrice.bind(this). this.onClick = this.onClick.bind(this)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.