steven steven - 9 days ago 7
React JSX Question

ReactJS assign click handler in for loop

Hi so I have this fiddle here http://jsfiddle.net/cmrunhow/5/ and it is working fine. However I was wondering why can't I replace

var clickHandler = this.props.onRatingSelected && this.props.onRatingSelected.bind(null, i);
items.push(<li key={i} className={i <= this.props.value && 'filled'} onClick={clickHandler}>{'\u2605'}</li>);


with

items.push(<li key={i} className={i <= this.props.value && 'filled'} onClick={this.props.onRatingSelected.bind(null, i)}>{'\u2605'}</li>);


assuming I skip the sanity check.

Answer

in your fiddle FundooRating component is called with and without onRatingSelected props.

 <div>
  Rating is {this.state.rating} <br/>
  Clickable Rating <br/>
  <FundooRating value={this.state.rating} max="10" onRatingSelected={this.handleRatingSelected.bind(this)} />
  <br />
  Readonly rating <br/>
  <FundooRating value={this.state.rating} max="10" />
</div>

so you will have to check for null case in replaced code too

items.push(<li key={i} className={i <= this.props.value && 'filled'} onClick={this.props.onRatingSelected && this.props.onRatingSelected.bind(null, i)}>{'\u2605'}</li>);

Sample Fiddle