I am trying to make a ponent 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 ponent 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 });
}
I am trying to make a ponent 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 ponent 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 });
}
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 es 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.