Clear values in number input in React - reactjs

I have two radio buttons, under each there are two number inputs. The goal is to clear the values that belong to deselected radio immediately on selecting the other radio.
I tried to resolve it by adding the ternary operator to defaultValue:
defaultValue={props.xxx ? props.yyy.toString() : ''}
But this works only when I refresh the page after selecting the radio, which isn't what I need. What is the way to clear the fields immediately when I select the other radio? I have read all similar questions here, but nothing helped in my situation.
The code is like this:
<Input
type="radio"
id="radio1"
label=""
name="radio"
onChange={() => onSomeChange(AbC, true)}
defaultChecked={props.aaa === true}
/>
<div className={cx({hidden: props.ooo})}>
{props.xxx === AbC && (
<div>
<Input
type="number"
id="min-number"
name="min-max1"
label=""
defaultValue={props.xxx ? props.yyy.toString() : ''}
onBlur={(e) => onOtherChange(true, inputValue(e.target.value))}
/>
<Input
type="number"
id="max-number"
name="min-max1"
label=""
defaultValue={props.xxx ? props.yyy.toString() : ''}
onBlur={(e) => onOtherChange(false, inputValue(e.target.value))}
/>
</div>
)}
<Input
type="radio"
id="radio2"
label=""
name="radio"
onChange={() => onSomeChange(AbC, true)}
defaultChecked={props.aaa === true}
/>
<div className={cx({hidden: !props.ooo})}>
{props.xxx === AbC && (
<div>
<Input
type="number"
id="min-number2"
name="min-max2"
label=""
defaultValue={props.xxx ? props.yyy.toString() : ''}
onBlur={(e) => onOtherChange(true, inputValue(e.target.value))}
/>
<Input
type="number"
id="min-number2"
name="min-max2"
label=""
defaultValue={props.xxx ? props.yyy.toString() : ''}
onBlur={(e) => onOtherChange(false, inputValue(e.target.value))}
/>
</div>
)}

If you just have only 2 radio inputs and 2 text inputs, you could handle it like this for 1 radio (you could do the same for other radios in your components).
const [radioValueA, setRadioValueA] = setState(false);
const [textValueA, setTextValueA] = setState(false);
onChangeRadio = (radioType, changedValue) => {
if (radioType === 'A') {
setTextValueA('');
setRadioValueA(changedValue);
} else {
// handle other radio button - should be switch if there are many radio input
}
}
// Radio A
<Input
type="radio"
checked={radioValueA}
onChange={event => onChangeRadio('A', event.target.value)}
/>
// Text A
<Input
type="text"
checked={textValueA}
onChange={event => setTextValueA(event.target.value)}
/>
The main ideas is you must control the input text value then set it to empty (clear) when radio button onChange event trigger

Related

Validating radio button with React Hook Form

I have a custom radio button component in React looking like this:
export default function SingleSelectionButton(props) {
const {
values, name, required, errors, defaultData,
xs, md, register, infoBox, infoBoxContent, validateField } = props;
return (
<>
<Form.Group>
<Form.Label>
<FormattedMessage
id={name}
/>
</Form.Label>
{values.map((value) => (
<span key={value} className="SingleSelectionButton">
<input
{...register(name, { required: required}
id={name + value}
type="radio"
name={name}
value={value}
defaultChecked={defaultData.primary[name] === value}
/>
<label htmlFor={name + value}>
<FormattedMessage id={value} />
</label>
</span>
))}
</Form.Group>
</>
);
};
I call it like this, using an array for the different values:
<SingleSelectionButton
name="us_person"
md={6}
values={["yes", "no"]}
register={register}
required={true}
errors={errors}
validateField="no"
/>
The validation with required is working fine.
The problem is that I don't manage to validate a value in particular.
I have tried the following:
<input
{...register(name, { required: required, validate: value => value === validateField })}
id={name + value}
type="radio"
name={name}
value={value}
defaultChecked={defaultData.primary[name] === value}
/>
And also:
<input
{...register(name, { required: required, pattern: validateField })}
id={name + value}
type="radio"
name={name}
value={value}
defaultChecked={defaultData.primary[name] === value}
/>
So far no joy. What am I missing?

Toggle Password Visibility for multiple password inputs

So if I'm using on input I can toggle password visibility.
I'm having trouble with it only toggling one input at a time.
D
Currently my code looks like this..
const [isPasswordShown, setPasswordShown] = useState(false);
const togglePassword = () => {
setPasswordShown(isPasswordShown ? false : true);
};
const renderTogglePasswordIcon = () => {
return (
<FontAwesomeIcon
onClick={togglePassword}
icon={isPasswordShown ? faEye : faEyeSlash}
/>
);
};
<Input
variant={InputVariants.text}
type={isPasswordShown ? "text" : "password"}
name="password"
label="Password"
error={errors.password?.message}
onChange={(e) => handlePasswordInput(e)}
ref={register}
/>
<i>{renderTogglePasswordIcon()}</i>
<Input
variant={InputVariants.text}
type={isPasswordShown ? "text" : "password"}
name="passwordConfirmation"
label="Confirm Password"
error={errors.passwordConfirmation?.message}
ref={register}
onChange={(e) => confirmPassword(e)}
/>
<i>{renderTogglePasswordIcon()}</i>
Do you want to toggle the inputs separately or only one of the inputs?
I would only use the toggle function for one input element. So you can set the html type to password hardcoded in the second element:
<Input
variant={InputVariants.text}
type={isPasswordShown ? "text" : "password"}
name="password"
label="Password"
error={errors.password?.message}
onChange={(e) => handlePasswordInput(e)}
ref={register}
/>
<i>{renderTogglePasswordIcon()}</i>
<Input
variant={InputVariants.text}
type="password"
name="passwordConfirmation"
label="Confirm Password"
error={errors.passwordConfirmation?.message}
ref={register}
onChange={(e) => confirmPassword(e)}
/>
<i>{renderTogglePasswordIcon()}</i>
Otherwise you can use a second parameter

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>

Resources