Radioboxes in ReactJs, use state for a controlled experience

Posted on

Control your radioboxes with state, to automatically select/unselect a radiobox.

Example, in a rating system, If I were giving a review 3 stars and change my mind to 5 stars, the 4th star should be sleected authomatically. This is just a design choice.

Here is the code below:

</pre>
import React, { Component } from 'react';

class AddReview extends Component {
 state={
 rating1: false,
 rating2: false,
 rating3: false,
 rating4: false,
 rating5: false
 }

handleRating = (event)=&gt;{
 switch (event.target.name) {
 case "rating5":
 this.setState({rating1: true, rating2: true, rating3: true, rating4: true, rating5: true})
 break;
 case "rating4":
 this.setState({rating1: true, rating2: true, rating3: true, rating4: true, rating5: false})
 break;
 case "rating3":
 this.setState({rating1: true, rating2: true, rating3: true, rating4: false, rating5: false})
 break;
 case "rating2":
 this.setState({rating1: true, rating2: true, rating3: false, rating4: false, rating5: false})
 break;
 case "rating1":
 this.setState({rating1: true, rating2: false, rating3: false, rating4: false, rating5: false})
 break;
 default:

}
 }

render(){
return(
<div>
example input below: just make the rest. doesnt render correctly in wordpress but should give you an idea where to get started if you needed direction

input type="radio" id="star2" name="rating2" value={this.state.rating2} checked={this.state.rating2} onClick={this.handleRating}</div>
)
}

}
<pre>

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s