How to Show Div When a Radio Button Is Clicked in React

How to Show div when a Radio Button is Clicked in React

Here are two solutions.

With standard React

import React, { Component } from "react";

class Radio extends Component {
constructor(props) {
super(props);
this.state = { status: 0 }; // 0: no show, 1: show yes, 2: show no.
}

radioHandler = (status) => {
this.setState({ status });
};

render() {
const { status } = this.state;

return (
<>
<input type="radio" name="release" checked={status === 1} onClick={(e) => this.radioHandler(1)} />
<input type="radio" name="release" checked={status === 2} onClick={(e) => this.radioHandler(2)} />
{status === 1 && drawYesContent()}
{status === 2 && drawNoContent()}
</>
);
}
}

export default Radio;

With React Hook

import React from "react";

function Radio () {
const [status, setStatus] = React.useState(0) // 0: no show, 1: show yes, 2: show no.

const radioHandler = (status) => {
setStatus(status);
};

return (
<>
<input type="radio" name="release" checked={status === 1} onClick={(e) => radioHandler(1)} />
<input type="radio" name="release" checked={status === 2} onClick={(e) => radioHandler(2)} />
{status === 1 && drawYesContent()}
{status === 2 && drawNoContent()}
</>
);
}

export default Radio;

hide div by selecting radio button "no" - reactjs

To make no as your initial radio checked value you can set default value in your useState.
add a checked property based on the state value.
you code will look like that

import { useState } from "react";

export default function Test() {
const [value2, setValue2] = useState("no");

return (
<>
<div className="col-sm-6">
<div className="form-check">
<input
className="form-check-input"
type="radio"
name="radio1"
value="no"
checked={value2 === "no"}
onChange={(e) => setValue2(e.currentTarget.value)}
/>
<label className="form-check-label">NO</label>
         
<input
className="form-check-input"
type="radio"
value="si"
name="radio1"
checked={value2 === "si"}
onChange={(e) => setValue2(e.currentTarget.value)}
/>
<label className="form-check-label">SI</label>
</div>
</div>
<div className="col-sm-7">
{value2 === "si" && (
<div className="card">
<div className="card-body">
<h1>DIV OK</h1>
</div>
</div>
)}
</div>
</>
);
}

Hide another component on the click of radio button

for this situation, you need to keep the state of selected trip type in HomePage component and then based on that state render the Return flight or not!

like below:

const HomePage = (props) => {

const [rSelected, setRSelected] = useState(null);



return (

// some code


// trip type button handler
<TripTypeButton handleSelectedTripType={setRSelected} rSelected={rSelected} />


// the button section of code
{ rSelected !== 1
&& <Col md={3}>
<FormGroup>
<Label for="exampleState">Return</Label>
<Input type="date" name="return" id="return"/>
</FormGroup>
</Col>
}


// rest of jsx code

)

}

and your TripTypeButton would be like below:

const TripTypeButton = ({ handleSelectedTripType, rSelected }) => {

return (
<div>
<ButtonGroup>
<Button color="primary" onClick={() => handleSelectedTripType(1)} active={rSelected === 1}>Round Trip</Button>
<Button color="secondary" onClick={() => handleSelectedTripType(2)} active={rSelected === 2}>One Way</Button>
</ButtonGroup>
</div>
);
}

this is called lifting state up in React! and by that you keep your state in top level components and manage data manipulation by passing required handlers down to the child components by directly props or context!

How to use divs as radio button options in React.js

Here's the stackblitz example.
The idea is to add an active class on the selected radio div.

constructor() {
this.state = {
activeIndex: ''
};

this.radioButtons = [
{
text: 'India'
},
{
text: 'England'
}
]
}

updateRadioGroup(i) {
this.setState({ activeIndex: i })
}

render() {
let { activeIndex } = this.state;
return (
<React.Fragment>
<h4> Who will win the match </h4>
{
this.radioButtons.map((element, i) => (
<div key={i} className={activeIndex === i ? 'radio_div active' : 'radio_div'} onClick={() => this.updateRadioGroup(i)}>
{element.text}
</div>
))
}
</React.Fragment>
);
}

In my example i have added radio options meta in a state. Rendered the html with initial radio activeIndex ' ' empty (so that no radio is selected by default). Now whenever the user clicks on any of the div i update the activeIndex with the clicked radioDiv index and attach the active class on the respective radioDiv conditionally.

Thanks let me know if this is the case you wanted to achieve.

Radio button onclick event in reactjs

I've been working over and over for many hours on the error, and finally i got a solution to my problem!!!
I used "defaultChecked" for both the radio button.
below is the code :

const [registerForm, setRegisterForm] = useState(props.register);
const [loginForm, setLoginForm] = useState(props.login);

const handleForm = (e) => {
// const registerBtn = document.querySelector("label.register");
// const loginBtn = document.querySelector("label.login");

const signInForm = document.querySelector("form.login");
const signInText = document.querySelector(".title-text .login");

if (e.target.id === "register") {
setRegisterForm(true);
signInForm.style.marginLeft = "-50%";
signInText.style.marginLeft = "-50%";
// setLoginForm(false);
}
if(e.target.id === "login") {
setLoginForm(true);
signInForm.style.marginLeft = "0%";
signInText.style.marginLeft = "0%";
// setRegisterForm(false);
}
};
<div className="slide-controls">
<input
type="radio"
name="slider"
id="login"
defaultChecked={loginForm}
onChange={handleForm}
/>
<input
type="radio"
name="slider"
id="register"
defaultChecked={registerForm}
onChange={handleForm}
/>
<label htmlFor="login" className="slide login">
Login
</label>
<label htmlFor="register" className="slide register">
Register
</label>
<div className="slide-tab"></div>
</div>

Radio buttons on a React component take an extra click to be marked

Hope this helps:
basically remove the preventDefault behaviour and defaultChecked instead of checked.

import "./styles.css";

export default function App() {
const radioHandler = (event) => {
console.log(event.target.value);
};

return (
<div className="radioDiv" onChange={radioHandler}>
<label>My label:</label>
<input type="radio" value="1" name="group_x" defaultChecked /> One
<input type="radio" value="2" name="group_x" /> Two
<input type="radio" value="3" name="group_x" /> Three
</div>
);
}

show/hide div after selecting a radio button

You are initializing i in every iteration of loop that makes it =1 always.

and as you needed the division with different text should visible on radio button so I edit it like this...

<?php
$i=1;
foreach ($items as $item){
echo '
<div class="form-check">
<input class="form-check-input" type="radio" name="radio1" id="detail_variant" onchange="showdiv('.$i.');">
<label class="form-check-label">'.$item['title'].'</label>
</div>';

//initially hide all
$detail_variant_html.="
<div style='display:none' id='detail_variant".$i."'>
<p> size: ".$item['size'."<br>
Color: ".$item['color']."<br>
Garment:".$item['garment']."
</p>
</div>";
$i++;

}
echo ' <div class="card-body">'.echo $detail_variant_html.' </div>';
?>
<script>
function showdiv(n){
var div = "detail_variant" + n;
document.getElementById("div").style.display='';//show only division you want
}
</script>

Note:- once the division is displayed it I am not hiding in the above code, you can hide it if you want.
If this worked give me feedback also If you have error tell me.

Grabbing the selected radio button value in react

It is simple, you need to provide a value attribute and an onClick listener, to each of the radio buttons, to gather the results. I have created a minimal working example here:

Handling click events of radio-buttons in React

How to use radio buttons in ReactJS?

Any changes to the rendering should be change via the state or props (react doc).

So here I register the event of the input, and then change the state, which will then trigger the render to show on the footer.

var SearchResult = React.createClass({
getInitialState: function () {
return {
site: '',
address: '',
};
},
onSiteChanged: function (e) {
this.setState({
site: e.currentTarget.value,
});
},

onAddressChanged: function (e) {
this.setState({
address: e.currentTarget.value,
});
},

render: function () {
var resultRows = this.props.data.map(function (result) {
return (
<tbody>
<tr>
<td>
<input
type="radio"
name="site_name"
value={result.SITE_NAME}
checked={this.state.site === result.SITE_NAME}
onChange={this.onSiteChanged}
/>
{result.SITE_NAME}
</td>
<td>
<input
type="radio"
name="address"
value={result.ADDRESS}
checked={this.state.address === result.ADDRESS}
onChange={this.onAddressChanged}
/>
{result.ADDRESS}
</td>
</tr>
</tbody>
);
}, this);
return (
<table className="table">
<thead>
<tr>
<th>Name</th>
<th>Address</th>
</tr>
</thead>
{resultRows}
<tfoot>
<tr>
<td>chosen site name {this.state.site} </td>
<td>chosen address {this.state.address} </td>
</tr>
</tfoot>
</table>
);
},
});

jsbin

Managing selection and state of DIVs as radio button options in React

Barney, you should try declaring your component as a class so you can do state management with it.
Check this docs for instructions on how to use state https://facebook.github.io/react-vr/docs/components-props-and-state.html

Your component should have in the state a list of options and an index of which option is selected. Iterate through the list and do special treatment for the selected index. You can have each option be it's own component with and index that identifies it, a onChange callback funciton to set the state and a isSelected prop. If the prop is selected, you can add the "selected overlay" html to it.



Related Topics



Leave a reply



Submit