I want to select only one option in the group of radio buttons. i can only find class component code online.
Also help me with a onChange function to handle this.
const [radioOption, setradioOption]= useState(true)
const handleRadioChange = () =>{
}
return(
<>
<Form.Group
inline
style={{
display:'flex',
justifyContent:'space-between'}}
>
<Form.Radio
onChange={handleRadioChange}
value="All devices"
label='All devices'
defaultChecked/>
<Form.Radio
onChange={handleRadioChange}
value='Mobile only'
label='Mobile only'/>
<Form.Radio
onChange={handleRadioChange}
value='Desktop only'
label='Desktop only'/>
</Form.Group>
</>)
To select only one option in the group of radio buttons you need to use same name in every input of radio. To save your choice we can use useState. Here is the complete example:
import React, { useState } from "react";
function Demo() {
const [gender, setGender] = useState("Male");
function onChangeValue(event) {
setGender(event.target.value);
console.log(event.target.value);
}
return (
<div onChange={onChangeValue}>
<input type="radio" value="Male" name="gender" checked={gender === "Male"} /> Male
<input type="radio" value="Female" name="gender" checked={gender === "Female"}/> Female
<input type="radio" value="Other" name="gender" checked={gender === "Other"} /> Other
</div>
);
}
export default Demo;
Related
I am new to react and I got a scenario where I have multiple checkboxes on my form. I want the user to check all the checkboxes only then enable the submit button on the form. On Load, the submit button will be disabled. How to do this?
Here is the code that I have written so far:
const MultipleCheckboxes = () => {
const handleChange = () => {
}
const allChecked = () => {
}
return (
<div>
<form>
<div className="form-check">
<input
type="checkbox"
className="some-class-name-chk"
name="someName"
value="Java"
id="languageChkDefault"
onChange={handleChange}
/>
<label
className="form-check-label"
htmlFor="languageChkDefault"
>
Javascript
</label>
</div>
<div className="form-check">
<input
type="checkbox"
className="some-class-name-chk"
name="someName"
value="Angular"
id="languageChkDefault"
onChange={handleChange}
/>
<label
className="form-check-label"
htmlFor="languageChkDefault"
>
Angular
</label>
</div>
<div className="form-check">
<input
type="checkbox"
className="some-class-name-chk"
name="someName"
value="Python"
id="languageChkDefault"
onChange={handleChange}
/>
<label
className="form-check-label"
htmlFor="languageChkDefault"
>
Python
</label>
</div> <br />
<button disabled={!allChecked}>Submit</button>
</form>
</div>
);
};
export default MultipleCheckboxes;
Can anybody help me on this? thank you
This is my solution, I hope it helps you
import { useState, useEffect } from "react";
const MultipleCheckboxes = () => {
const [allChecked, setAllChecked] = useState(false);
const [checkboxes, setCheckboxes] = useState({
javaCheckbox: false,
angularCheckbox: false,
pythonCheckbox: false
});
function handleChange(e) {
setCheckboxes({
...checkboxes,
[e.target.id]: e.target.checked
})
}
useEffect(() => {
const result = Object.values(checkboxes).every(v => v);
console.log(result);
setAllChecked(result);
}, [checkboxes]);
return (
<div>
<form>
<div className="form-check">
<input
type="checkbox"
className="some-class-name-chk"
name="someName"
value={checkboxes.javaCheckbox}
id="javaCheckbox"
onChange={handleChange}
/>
<label
className="form-check-label"
htmlFor="languageChkDefault"
>
Javascript
</label>
</div>
<div className="form-check">
<input
type="checkbox"
className="some-class-name-chk"
name="someName"
value={checkboxes.angularCheckbox}
id="angularCheckbox"
onChange={handleChange}
/>
<label
className="form-check-label"
htmlFor="languageChkDefault"
>
Angular
</label>
</div>
<div className="form-check">
<input
type="checkbox"
className="some-class-name-chk"
name="someName"
value={checkboxes.pythonCheckbox}
id="pythonCheckbox"
onChange={handleChange}
/>
<label
className="form-check-label"
htmlFor="languageChkDefault"
>
Python
</label>
</div> <br />
<button disabled={!allChecked}>Submit</button>
</form>
</div>
);
};
export default MultipleCheckboxes;
You can use react useState hook and set its default value to false.
const [state, setstate] = useState(false)
When the user clicks on an input box set the state to true. You may encounter some problems when the user unchecks the box, so you can use an if statement to handle state change
For example:
if (state === true){
setstate(false)
}else{
setstate(true)
}
or you can just use this code inside the handleChange function:
!state
It inverses the state to true/false accordingly.
After that you can use a ternary operator inside the component to check whether the user has checked all the boxes, if the user hasn't checked all the boxes, disable the button or else do otherwise.
For example, if the state is true (or in other words, if the user has checked the box), render the normal styled button, else render the disabled button:
{state? <button className = "styled"/>: <button disabled className="styled"/>}
Of course, I have only checked the state of one input box. Now you can simply check for multiple conditions by declaring multiple states for each box.
{state1 && state2 && state3 ? <button className = "styled"/>: <button disabled className="styled"/>}
If you are not yet familiar with ternary operators, you should go through this doc Ternary operators.
If you haven't heard of useState and react hooks yet, feel free to look the React's documentation. Welcome to the React ecosystem!
I am working on form which have combination of input field and radio button. Whenever I select the radio button, it is not getting selected but value is getting update in form state . For some reason, radio button is not showing selected
const InputForm = () => {
const [form, setForm] = useState({name: "", job: "no" });
const {name, job} = form;
const handleJob = (e) => {
let value = e.target.value;
setForm({ ...form, job: value });
};
const onInputChange = (e) => {
setForm({...form, [e.target.name]: e.target.value});
}
return (
<>
<input
type="text"
className="form-control input-text-box"
placeholder="Name"
value={name}
onChange={onInputChange}
/>
<div className="form-check-inline mx-2">
<input
type="radio"
className="form-check-input"
name="radioOption"
value="yes"
onChange={handleJob}
checked={job === "yes"}
/>{" "}
<label className="form-check-label" for="radioOption">
Yes
</label>
<input
type="radio"
name="radioOption"
className="form-check-input"
value="no"
onChange={handleJob}
checked={job === "no"}
/>{" "}
<label className="form-check-label" for="radioOption">
No
</label>
</div>
</>
);
};
export default InputForm;
I am trying to get useFormik to validate radio groups, but it seems not to work, here is a brief example of what I am doing, whenever I submit the form after checking any of the radio input, formik throws validation error, ({currState:"you must choose property state"}), even though I choose an option.
I realized getFieldProps attaches value field to the radio, so i tried using defaultValue then react throws an error about choosing one of controlled and uncontrolled components.
import { useFormik } from "formik"
export function ListProperty(){
const { handleSubmit, getFieldProps, touched, errors } = useFormik(
{
initialValues: {
currState:"",
},
validationSchema:Yup.object().shape({
currState:Yup.string().required("you must choose property state")
}),
return (
<form onSubmit={handleSubmit} >
<div className="form-group inline">
<div className="form-control">
<input type="radio"
name="currState"
{...getFieldProps("currState")}
value="serviced"
/>
<label>serviced</label>
</div>
<div className="form-control">
<input
type="radio"
value="furnished"
name="currState"
{...getFieldProps("currState")}
/>
<label>furnished</label>
</div>
<div className="form-control">
<input
type="radio"
value="newlybuilt"
name="currState"
{...getFieldProps("currState")}
/>
<label>newly built</label>
</div>
</div>
<button type="submit">submit </button>
</form>
)
}
I gave up on the implementation with getFieldProps and did it simpler, like this:
import { useFormik } from 'formik'
export default function Component() {
const formik = useFormik({
initialValues: {
radioButtonValue: ''
},
onSubmit: values => console.log(values)
})
const handleRadioButtons = e => formik.values.radioButtonValue = e.target.value
return (
<form onSubmit={formik.handleSubmit}>
<input
type="radio"
id="one"
name="group"
value="One"
onChange={e => handleRadioButtons(e)}
required
/>
<label htmlFor="one">One</label>
<br />
<input
type="radio"
id="two"
name="group"
value="Two"
onChange={e => handleRadioButtons(e)}
/>
<label htmlFor="two">Two</label>
<button type="submit">Submit</button>
</form>
)
}
Beware, if you use formik.values.radioButtonValue value as a useEffect dependency, then setting it like this: formik.values.radioButtonValue = e.target.value not gonna trigger the change, and useEffect won't launch (at least in my case it didn't). As an alternative, you gonna have to implement some kind of condition check with this value in your useEffect code
You need to map onChange like below.
<input
type="radio"
value="furnished"
name="currState"
onChange={getFieldProps("currState").onChange}
/>
I am trying to use defaultChecked in reactjs when using map function to only one radio button. But How can I acomplish it?
{colors.map((color, index) => {
return (
<label className="color-checkmark" key={index}>
<input
type="radio"
checked="checked"
name="color"
value={color}
// defaultChecked
/>
</label>
);
})}
If I use defaultChecked there it will be set to every radio button.
You need to remove the checked="checked" attribute as it conflicts with the defaultChecked attribute. And then add defaultChecked={index === 0}
If you want the first item checked
{colors.map((color, index) => {
return (
<label className="color-checkmark" key={index}>
<input
type="radio"
name="color"
value={color}
defaultChecked={!(!!index)}
/>
</label>
);
})}
what does !! do?
the !! ensures that the value will always be a boolean or converted to a boolean.
You need to add a condition to your defaultChecked, and remove the checked property:
const colors = ['blue', 'green', 'red']
function App() {
return colors.map((color, index) => (
<label key={index}>
<input
type="radio"
name="color"
value={color}
defaultChecked={index === 0}
/>
<span style={{color}}>{color}</span>
</label>
))
}
ReactDOM.render(<App />, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app">euoeu</div>
I'm new to react and redux and i want to create component which contain two radio buttons so i write something like this:
import React, { PropTypes } from 'react';
const renderCashRadioButtons = currentCashSelector => (
<form onClick={currentCashSelector}>
<input
type="radio"
name="cash-transaction"
value="Transcation"
onChange={value => currentCashSelector(value)}
/>
<input
type="radio"
name="cash-transfer"
value="Transfer"
onChange={value => currentCashSelector(value)}
/>
</form>
);
const CashRadioButtons = ({ currentCashSelector }) => (
<div className="container">
{renderCashRadioButtons(currentCashSelector)}
</div>
);
CashRadioButtons.propTypes = {
currentCashSelector: PropTypes.func.isRequired
};
export default CashRadioButtons;
currentCashSelector is a function. When i render this it does not seem to work. The value does not change and i'm not seeing the state to be updated. Do you have any ideas?
You probably want your radio buttons to have the same name, so that when one is selected, the other is deselected.
It looks like your onChange functions are expecting the value, but they're actually receiving the event.
You likely have unwanted duplication between the onChange on your form, and the ones on your radio buttons.
Possible Solution
<form onClick={event => currentCashSelector(event.target.value)}>
<input
type="radio"
name="cash-type"
value="Transaction"
/>
<input
type="radio"
name="cash-type"
value="Transfer"
/>
</form>