Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set radio button 'checked' based on value from database? - React

I have a radio button group in a component. I want to set which radio is selected based on it's value taken from the database in an Update/Edit scenario.

export default function updateRadioSelection(){
  const [radioValue, setRadiovalue] = useState("");

  useState(()=>{
    setRadiovalue("pick");    // <-- Assume this value is taken from database, value may be either "delivery" or "pick"
  }, [])

  const changeSelection = (e)=>{
    setRadiovalue(e.target.value);
  }

  return(
    <div>
      <input type="radio" id="delivery" name="orderType" value="delivery" required onChange={changeSelection} />
      <label htmlFor="delivery">Delivery</label>
      
      <input type="radio" id="pick" name="orderType" value="pick" onChange={changeSelection} />
      <label htmlFor="pick">Pick Up</label>
    </div>
  )
}
like image 838
Priyantha Fernando Avatar asked Feb 17 '26 13:02

Priyantha Fernando


1 Answers

To make a checkbox or radio checked you must use the checked prop for the input element, it receives a boolean value. And you can do something like this

export default function updateRadioSelection(){
  const [radioValue, setRadiovalue] = useState("");

  // useState will not execute any kind of callback function, for this case you need to use useEffect
  useEffect(() => {
    const dbResult = getRadioFromDb();
    setRadiovalue(dbResult);
  }, [])

  const changeSelection = (e)=>{
    setRadiovalue(e.target.value);
  }

  return(
    <div>
      <input type="radio" id="delivery" name="orderType" value="delivery" required onChange={changeSelection} checked={radioValue === 'delivery'} />
      <label htmlFor="delivery">Delivery</label>
      
      <input type="radio" id="pick" name="orderType" value="pick" onChange={changeSelection} checked={radioValue === 'pick'} />
      <label htmlFor="pick">Pick Up</label>
    </div>
  )
}

You can read more about radio input in its documentation

like image 69
MaCadiz Avatar answered Feb 20 '26 04:02

MaCadiz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!