Home > Back-end >  Radio button checked value from state in React
Radio button checked value from state in React

Time:09-30

i have a list of radio button (they are printed from a map loop that contains a list of number, for example 1,2,3), when i select/check it, it sets a state:

<ul className="flex gap-6 justify-center">
          {maxPaxArr.map((keypax) => (
            <li key={keypax}>
              <input
                id={`pax-${keypax}`}
                className=""
                type="radio"
                value={keypax}
                name="pax"
                onChange={(e) => {
                  setPax(e.target.value);
                }}
              />
            </li>
          ))}
        </ul>

The setPax function, simply set a state:

 const [pax, changePax] = useState();
 function setPax(e) {
    changePax(e);
  }

everything works as expected, the state is set correctly, when i move to another form step and get back the state is correctly stored, but im not able (when getting back to the step with the radio buttons) to autoselect the radio from the state. I tried to add the following to the input:

checked={pax===keypax}

but this way (even if when i click the radio the state is set), the radio cant be checked

i think this is due to the fact that the input come from a map, becuase if i put the manually on the page it looks like it is working.

CodePudding user response:

Instead of getting selected value from `e.target.value', you can define callback that returns value corresponding to radio button. And no need to set value.

    const [pax, changePax] = useState(initialValue);
    
    .......
    
    <ul className="flex gap-6 justify-center">
      {maxPaxArr.map((keypax) => (
        <li key={keypax}>
          <span style={{color: "white"}}>{keypax}</span>
          <input
            id={`pax-${keypax}`}
            className=""
            type="radio"
            checked={keypax === pax}
            name="pax"
            onChange={(e) => {
              setPax(keypax);
            }}
          />
        </li>
      ))}
    </ul>
  • Related