view raw
steven steven - 5 months ago 43
React JSX Question

ReactJS assign click handler in for loop

Hi so I have this fiddle here 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>);


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.


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

  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" />

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