简体   繁体   中英

How to set checked with Radio.Group Antd?

I have dynamic data that radio draw.

There is an id of an active radio, which also comes dynamically.

How to compare id and install cheked with Radio.Group. And in the end I need to get the radio values in the form This code does not work correctly.

dynamiclyData could be much bigger

const dynamiclyData = [
  { id: 1, value: "A" },
  { id: 2, value: "B" },
  { id: 3, value: "C" },
  { id: 4, value: "D" }
];

const idChekedFromRequest = 2;

const App = () => (
  <Form onFinish={val => console.log("val", val)}>
    <Form.Item name="radio">
      <Radio.Group name="radiogroup">
        {dynamiclyData.map(({ value, id }) => {
          return (
            <Radio key={id} checked={id === idChekedFromRequest}>
              {value}
            </Radio>
          );
        })}
      </Radio.Group>
      <Button htmlType="submit">submit</Button>
    </Form.Item>
  </Form>
);

CodeSanbox

import React,{useState} from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Radio, Form, Button } from "antd";

const dynamiclyData = [
  { id: 1, value: "A" },
  { id: 2, value: "B" },
  { id: 3, value: "C" },
  { id: 4, value: "D" }
];

const App = () => {
  const [idChekedFromRequest,setIdChekedFromRequest] = useState(2);
  return (
  <Form onFinish={val => console.log("val", val)}>
    <Form.Item name="radio">
      {/* <Radio.Group name="radiogroup"> */}
      {dynamiclyData.map(({value, id}) => {
        return (
          <Radio key={id} onChange={()=>setIdChekedFromRequest(id)} checked={id===idChekedFromRequest}>
            {value}
          </Radio>
        );
      })}
      {/* </Radio.Group> */}
      <Button htmlType="submit">submit</Button>
    </Form.Item>
  </Form>
  )
}

ReactDOM.render(<App />, document.getElementById("container"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM