Home > front end >  How to set radio button 'checked' based on value from database? - React
How to set radio button 'checked' based on value from database? - React

Time:10-12

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>
  )
}

CodePudding user response:

Just a few minutes after posting this question I found the answer I was searching for hours. Turns out its pretty easy.

Just add checked={radioValue === "pick"} for the Pick Up radio button & the same for other radio button by replacing "pick" with "delivery"

ref - Option 1" rel="nofollow noreferrer">react.tips/radio-buttons-in-reactjs

CodePudding user response:

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

  • Related