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 });
}
Xarvalus
  • 2,873
  • 1
  • 19
  • 29
vivek modi
  • 800
  • 2
  • 7
  • 23

1 Answers1

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.

Xarvalus
  • 2,873
  • 1
  • 19
  • 29
  • this solution is giving Cannot read property 'props' of undefined error – vivek modi Jun 21 '18 at 23:59
  • 1
    The second solution also needs manually binding eg in constructor like it was in `this.sumPrice.bind(this)`. `this.onClick = this.onClick.bind(this)` – Xarvalus Jun 22 '18 at 00:03