boba poorna
boba poorna

Reputation: 251

deselect radio button from array list in react js

I have an array list, where every record will have radio button, when user clicks on one radio it should select it and when user clicks on another radio button the first selected record button should deselect radio button.

Please find sanbox link below: sandbox link

code:

  const handlesubmit = (formdata) => {
    console.log(formdata);
  };

  const renderCard = (card, index) => {
    return (
      <Col span={7} className="card-background">
        <h3 style={{ textAlign: "center" }}>{card.planType}</h3>
        <hr />
        <Form.Item name="selectedPlan">
          <Row>
            <Col span={16} offset={2}>
              {card.planDetails[0].name}
            </Col>{" "}
            <Col span={5} offset={1}>
              {card.planDetails[0].numOfSession}
            </Col>
            <Col span={16} offset={2}>
              {card.planDetails[1].name}
            </Col>{" "}
            <Col span={5} offset={1}>
              {card.planDetails[1].numOfSession}
            </Col>
            <Col span={16} offset={2}>
              {card.planDetails[2].name}
            </Col>{" "}
            <Col span={5} offset={1}>
              {card.planDetails[2].numOfSession}
            </Col>
          </Row>
        </Form.Item>
        <hr />
        <div style={{ textAlign: "center" }}>
          <Radio onChange={() => setSelectedPlan(card)}>
            Pay {card.planAmount}
          </Radio>
        </div>
      </Col>
    );
  };

Upvotes: 0

Views: 335

Answers (2)

Majid M.
Majid M.

Reputation: 4954

You can define your state like:

const [selectedPlan, setSelectedPlan] = useState(0);

And do something like:

  const setSelected = (event, index) => {
    setSelectedPlan(index);
  };

Finally Change Radio to :

  <Radio
    checked={selectedPlan == index ? true : false}
    name="radio"
    onChange={(e) => setSelected(e, index)}
  >
    Pay {card.planAmount}
  </Radio>

Edit Form Validations (forked)

Upvotes: 1

mehran gnaji
mehran gnaji

Reputation: 24

you need checked your radio buttons based on plan state

for example

      <Radio 
           checked={selectedPlan === card.planAmount}
          onChange={() => setSelectedPlan(card.planAmount)}>
        Pay {card.planAmount}
      </Radio>
    

Upvotes: 1

Related Questions