Kamrul Islam
Kamrul Islam

Reputation: 265

Reactjs radio button isnt getting checked properly

I'm trying to build a filter that filters the all the candidates based on experience. I've build the filter using radio buttons which is sending working fine but the problem is that it isn't getting checked. BY default I want every radio btns to be not checked when the user clicks one btn then it should be checked. when I click the btn, it filter the candidates but the radio button itself is not being checked. My component is big that's why I just provided the code you all would need. PLease help me set the check on the radio buttons properly. Thanks

        //i'm importing this array and using it in my component
export const filtersByExp = [
  {
    value: 0,
    label: "Fresher",
  },
  {
    value: 1,
    label: "1 year above ",
  },
  {
    value: 2,
    label: "2 year above ",
  },
  {
    value: 3,
    label: "3 year above  ",
  },
  {
    value: 4,
    label: "4 year above  ",
  },
  {
    value: 5,
    label: "5 year above  ",
  },
];

      //component
  const [filter, setFilter] = useState({
    stage: "all",
    exp: null,
    job_id: null,
  });
 const handleRadioChange = ({ target }) => {
            let value = target.value;
            let name = target.name;
            setFilter({
              ...filter,
              [name]: value,
            });
          };
        
    //jsx
        {[...filtersByExp].map((item) => (
                        <div key={item.value} className="mb-2">
                          <Form.Check
                            type="radio"
                            label={item.label}
                            name="exp"
                            checked={filter.exp === item.value}
                            onChange={handleRadioChange}
                            value={item.value}
                          />
                        </div>
                      ))}

Upvotes: 1

Views: 2496

Answers (1)

Danial
Danial

Reputation: 1633

You must use defaultChecked in jsx. Because if use checked, final value never changed, but defaultChecked load just in initial render in react.

<div key={item.value} className="mb-2">
    <Form.Check
        type="radio"
        label={item.label}
        name="exp"
        defaultChecked={filter.exp === item.value}
        onChange={handleRadioChange}
        value={item.value}
    />
</div>

Upvotes: 5

Related Questions