adding color to the active radio button - reactjs

I have two radio buttons and I want to add a background color to the active radio button.
I tried to add it via a condition but it seems to be not working. What am i doing wrong here?
I'm getting Cannot read property 'gender' of undefined error
import React from "react";
import "./App.css";
export default function App() {
const [gender, setGender] = React.useState();
return (
<div className="App">
<Radio
label="male"
value="male"
checked={gender}
setter={setGender}
style={{backgroundColor: this.state.gender == 'male' ? 'red': 'white'}}
/>
<Radio
label="female"
value="female"
checked={gender}
setter={setGender}
style={{backgroundColor: this.state.gender == 'female' ? 'red': 'white'}}
/>
</div>
);
}
const Radio = ({ label, value, checked, setter }) => {
return (
<div className="radio">
<label>
<input
type="radio"
checked={checked === value}
onChange={() => setter(value)}
/>
<span>{label}</span>
</label>
</div>
);

When using react hooks, you do not need to use this.state.gender...
Try this:
<div className="App">
<Radio
label="male"
value="male"
checked={gender}
setter={setGender}
style={{backgroundColor: gender === 'male' ? 'red': 'white'}}
/>
<Radio
label="female"
value="female"
checked={gender}
setter={setGender}
style={{backgroundColor: gender === 'female' ? 'red': 'white'}}
/>
</div>

Few changes required
1-Always provide initial value
const [gender, setGender] = React.useState('');
2- Since you are using hooks, don't need to use this.state
style={{backgroundColor: gender === 'male' ? 'red': 'white'}}
If you are trying to change background color on selection of radio button, Replace Radio component with below.
const Radio = ({ label, value, checked, setter, style }) => {
return (
<div className="radio" style={style}>
<label>
<input
type="radio"
checked={checked === value}
onChange={() => setter(value)}
/>
<span>{label}</span>
</label>
</div>
);
};
Live demo

Related

Why when I use onClick with radio button make them have to click twice to make radio button to be selected?

now, I using radio button to render 2 components differently I use onClick with radio button to [isRepeat,setisRepeat] setState value
<input
required
id="singleClass"
name="classType"
type="radio"
className="inputContainer"
value={1}
OnClick={() => setisRepeat("oneTime")}
></input>
<label>ครั้งเดียว</label>
<input
required
id="repeatClass"
name="classType"
type="radio"
className="inputContainer"
value={2}
onClick={() => setisRepeat("repeat")}
></input>
and render component like this
{isRepeat === "oneTime" && (
<>...</>
)}
{isRepeat === "repeat" && (
<div>...</div>
)}
but when I using onClick() with radio button, It's make user to click "twice" to make radio button checked
(actually, setState work fine when click radio button but radio button didn't be checked. It should be checked and setState at the same time to make user not confuse)
ps. I already using document.getElementByName('classType').value === 1 or 2 to render different items, but didn't work
You should use onChange with input as:
onChange={() => setisRepeat("oneTime")}
instead of onClick
Demo
export default function App() {
const [isRepeat, setisRepeat] = useState(""); // You can also give the initial value
return (
<div>
<input
required
id="singleClass"
name="classType"
type="radio"
className="inputContainer"
value={1}
onChange={() => setisRepeat("oneTime")}
></input>
<label>ครั้งเดียว</label>
<input
required
id="repeatClass"
name="classType"
type="radio"
className="inputContainer"
value={2}
onChange={() => setisRepeat("repeat")}
></input>
<br />
{isRepeat === "oneTime" && <> One Time </>}
{isRepeat === "repeat" && <div> Repeat </div>}
</div>
);
}
You can use onChange instead of onClick handler and checked property along with it.
import { useState } from "react";
export default function App() {
const [isRepeat, setisRepeat] = useState("");
const onClickHandler = (type) => {
if (type === "singleClass") {
setisRepeat("singleClass");
} else {
setisRepeat("repeatClass");
}
};
return (
<div className="App">
<input
required
name="singleClass"
type="radio"
className="inputContainer"
value={1}
checked={isRepeat === "singleClass"}
onChange={() => {
onClickHandler("singleClass");
}}
></input>
<label>ครั้งเดียว</label>
<input
required
name="repeatClass"
type="radio"
className="inputContainer"
value={2}
checked={isRepeat === "repeatClass"}
onChange={() => {
onClickHandler("repeatClass");
}}
></input>
{isRepeat === "singleClass" && (
<>
<p>One time component Triggered </p>
</>
)}
{isRepeat === "repeatClass" && <div>Repeat component Triggered </div>}
</div>
);
}
Demo
In the first input you have a typo. You have OnClick but you want onClick
It works for me with one click like this
(I removed a few props to make it shorter)
import React from 'react';
import { useState } from 'react';
const Demo = () => {
const [isRepeat, setIsRepeat] = useState('');
return (
<>
<input type="radio" value={1} onClick={() => setIsRepeat('oneTime')}></input>
<label>ครั้งเดียว</label>
<input type="radio" value={2} onClick={() => setIsRepeat('repeat')}></input>
{isRepeat === 'oneTime' && <span>One Time</span>}
{isRepeat === 'repeat' && <span>repeat</span>}
</>
);
};
export default Demo;

React radio not resetting the values

I am new to reactjs. I have radio buttons that say UserA, UserB, UserC, and User D. I have multiple permission for UserA based on sub-selection of radio buttons(Like Admin, Editor, User). Similarly, for UserD I can have only one permission like SuperAdmin. Whenever I select UserD, it should set the permission to 'Super Admin' which is working. But If I select another radio button, User D is not unselecting.
I believe it is because I am using the name as 'permission' on both the input fields(User D and UserA Admin sub option) which is not resetting the values in the state.
Here is the codepen for your reference. Any help would be much appreciated.
Thank you
You must have all input[radio-button]'s structure similar. You must be updating the state based on a condition. This code worked for me based on the given requirement. I have made some minor changes to the input userD and setState method. I hope this resolves your problem.
export default function Form() {
const [state, setState] = React.useState({
user: '',
testRequest: false,
permission: ''
});
const [disableuserA, setdisableuserA] = React.useState(false);
const [value, setValue] = React.useState(0);
const [selected, setSelected] = React.useState('');
function handleChange(e) {
const value =
e.target.type === 'checkbox' ? e.target.checked : e.target.value;
setState({
...state,
[e.target.name]: value,
...(e.target.name == 'user' &&
e.target.value == 'userD' && { permission: 'superAdmin' })
});
setSelected(e.target.value);
}
return (
<div className="app">
<form onSubmit={handleFormSubmit}>
<div>
<div>
<input
type="checkbox"
name="testRequest"
value={value}
onClick={() => setdisableuserA(!disableuserA)}
checked={state.testRequest}
onChange={handleChange}
/>
Enable this to hide the User A option
</div>
<div className="heading">user</div> <br />
<input
disabled={disableuserA}
type="radio"
name="user"
value="userA"
checked={selected === 'userA' || selected === 'admin'}
onChange={handleChange}
/>
UserA
<input
type="radio"
name="user"
value="userB"
checked={state.user === 'userB'}
onChange={handleChange}
/>
UserB
<input
type="radio"
name="user"
value="userC"
checked={state.user === 'userC'}
onChange={handleChange}
/>
UserC
<input
type="radio"
name="user"
value="userD"
checked={state.user === 'userD'}
onChange={handleChange}
/>
UserD
<br /> <hr />
<div
aria-hidden={
selected !== 'userA' &&
selected !== 'admin' &&
selected !== 'editor' &&
selected !== 'publisher'
? true
: false
}
>
<input
type="radio"
name="permission"
value="admin"
checked={state.permission === 'admin'}
onChange={handleChange}
/>{' '}
Admin
<input
type="radio"
name="permission"
value="editor"
checked={state.permission === 'editor'}
onChange={handleChange}
/>{' '}
Editor
<input
type="radio"
name="permission"
value="publisher"
checked={state.permission === 'publisher'}
onChange={handleChange}
/>{' '}
Publisher
</div>
<br /> <br />
<button type="submit" className="btn-default btn">
Submit{' '}
</button>
</div>
</form>
<pre>{JSON.stringify(state, null, 3)}</pre>
</div>
);
}
Live Demo

setting defaultChecked in radio button is not working in react

I need to set the defaultChecked on page load which can later be changed by the user
<input
ref={(element) => (this['input' + item.key] = element)}
name={item.key}
placeholder='Config value'
defaultChecked={item.value === true}
value='true'
type='radio'
onChange={(event) => this.validateCValue(event.target.value, item)}
/>
<label> True</label>
Radio inputs can only be checked but not unchecked, if you set it to true, the user will not be able to uncheck it, maybe you meant to use a checkbox?
const [checked, setChecked] = useState(true);
const handleChange = () => {
setChecked(checked => !checked);
};
return (
<div className="App">
<input
placeholder="Config value"
defaultChecked={checked}
type="checkbox"
onChange={handleChange}
/>
<label>{checked ? "checked" : "not checked"}</label>
</div>
);
this works for me use "checked" tp set radio button default value
<div onChange={this.sethandleValueChange.bind(this)} className={` ${(this.state.IsControlSet && this.state.RadioBtnVal=="" ? styles.control_border_red : "")}`}>
<input type="radio" value="Yes" name="RadioBtnVal" checked={this.state.RadioBtnVal=="Yes"} disabled={(this.state.FormName!="View") ? false : true}/> Yes<br/>
<input type="radio" value="No" name="RadioBtnVal" checked={this.state.RadioBtnVal==="No"} disabled={(this.state.FormName!="View") ? false : true}/> No
</div>

Correct way of using useState hook on radio buttons

I followed the ReactJS documentation regarding the useState hook but I cannot get it to work with radio buttons. It doesn't select any radio button at all.
By the way I am using react-semantic ui for the component.
The radio buttons should select the gender assigned to the state. I've tried to console.log the gender variable and it changes but does not reflect on the ui.
Here's my code for your reference.
import React, { useState } from 'react';
const ListCreateNew = () => {
const [gender, setGender] = useState('Male');
return (
<Form.Group inline>
<label>Gender</label>
<Form.Field control={Radio} label="Male" checked={gender === 'Male'} value="Male" onClick={() => setGender('Male')} />
<Form.Field control={Radio} label="Female" checked={gender === 'Female'} value="Female" onClick={() => setGender('Female')} />
</Form.Group>
);
}
EDIT:
I apologize everyone. I've missed the anonymous function on the onClick attrib.
You should use annonymous function to update the state,
<Form.Field control={Radio} label="Male" checked={gender === 'Male'} value="Male" onClick={() => setGender('Male')} />
<Form.Field control={Radio} label="Female" checked={gender === 'Female'} value="Female" onClick={() => setGender('Female')} />
Update
For the radio button, you have Form.Radio
<Form.Group inline>
<label>Gender</label>
<Form.Radio label="Male" checked={gender === 'Male'} value="Male" onClick={() => setGender('Male')} />
<Form.Radio label="Female" checked={gender === 'Female'} value="Female" onClick={() => setGender('Female')} />
</Form.Group>
const [radio,setRadio] = useState('false')
<Form>
<Form.Check inline label="Response A" type="radio" id="radioA" value="radioA" checked={radio === "radioA"} onChange={(e)=>{setRadio(e.target.value)}}/>
<Form.Check inline label="Response B" type="radio" id="radioB" value="radioB" checked={radio === "radioB"} onChange={(e)=>{setRadio(e.target.value)}}/>
<Form.Check inline label="Response C" type="radio" id="radioC" value="radioC" checked={radio === "radioC"} onChange={(e)=>{setRadio(e.target.value)}}/>
<Form.Check inline label="Response D" type="radio" id="radioD" value="radioD" checked={radio === "radioD"} onChange={(e)=>{setRadio(e.target.value)}}/>
</Form>

redux-form renderField type radio undefined value

I try to implement renderField for radio buttons, i can display it but when i click on radio field does not fill.
When i check the console, value of input is equal to undefined, always !
This is my code :
render(){
const {input, array, meta, label} = this.props;
return(
<div className="input-row">
<div className="radio-box">
{array.map((option,i) =>
<div className="radio-field" key={i}>
<input type='radio' name={option.name} onChange={() => {input.onChange('oui')}} value={option.value} checked={input.value === option.value} />
{/* Try this before <input type='radio' {...input} name={option.name} value={option.value} checked={input.value == option.value}/> */}
<label>{option.name}</label>
</div>
)}
</div>
</div>
)
}
I call this with :
<Field name="courtage" type="radio" label="Courtage ?" component={renderRadioField} array={selectOptions.courtage} {...courtage} />
SelectOptions.courtage is an array of object.
After few hours, I find a solution, I play with the state :
setRadioState(a) {
const obj = {};
obj[a.target.name] = a.target.value;
this.setState(obj);
}
render(){
const {input, array, meta, label, name} = this.props;
return(
<div className="input-row">
<div className="label-box">
<label>{label}</label>
</div>
<div className="radio-box">
{array.map((option,i) =>
<div className="radio-field" key={i}>
<input type='radio' name={name} {...input} onChange={this.setRadioState.bind(this)} value={option.value} checked={this.state.name} />
<label>{option.name}</label>
</div>
)}
{/* <div className="errors">{meta.touched && ((error && <span>{error}</span>))}</div> */}
</div>
</div>
)

Resources