Robson Robson - 2 months ago 14
jQuery Question

React: change value of hidden input to the number of clicked 'span'

I have a div with rating like this in one of my components:

var Rating = React.createClass({
render: function () {
return (
<div className="rate-line">
<div className="rate-title">{this.props.name}</div>
<div className="rating">
<span>☆</span>
<span>☆</span>
<span>☆</span>
<span>☆</span>
<span>☆</span>
</div>
<input type="hidden" id={this.props.id}/>
</div>
);
}
});


And I have now tag in other component:

<div>
<div className="result-label">Score</div>
<Rating/>
</div>


How can I add value to hidden input like number 3 if I click on third span ? How can I to do this properly in react?

Many thanks for help.

Answer

Assign value to your input from state:

<input type="hidden" id={this.props.id} value={this.state.starRating} />

Now the question is how and when do we set state. When is easy — it should be done on click:

<span onClick={this.handleStarClick}>☆</span>

All that's left is writing actual handler:

handleStarClick: function(starRating){this.setState({starRating})}

Oh, but we don't have our starRating parameter in onClick handler! Let's add just that. Final version:

<span onClick={() => this.handleStarClick(1)}>☆</span>` ... <span onClick={() => this.handleStarClick(5)}>☆</span>