October 15, 2018

ReactJS | Radio Button Content Toggle in ReactJS

Hey People,

Today we are going to learn who we can create radio buttons and as well as toggling content on click on Radio Buttons.


Code : https://codesandbox.io/s/oz4lqrvl6 


1) We have just 1 component here and it will do all the job. showContent.js.



We are toggling 2 things here - className and selected. On the basis of the className we will hide and show the content and on the basis of selected value we will show which radio button is selected.


handleChange=e=>{
if(e.target.value ==="show"){
this.setState({
show:"show",
selected:e.target.value
});
else{
this.setState({
show:"hide",
selected:e.target.value
});
}
};

In JSX all we need to  just handle these values.



<form>
<input
type="radio"
value="show"
name="content"
id="show"
onClick={this.handleChange}
checked={this.state.selected ==="show"}
/>
<labelfor="show">Show</label>

<input
type="radio"
value="hide"
name="content"
id="hide"
onClick={this.handleChange}
checked={this.state.selected ==="hide"}
/>
<labelfor="hide">Hide</label>
</form>

<divclassName={this.state.show}>
This is the sample text. It will come when the radio button will
click.
</div>

No comments: