Aytac
Aytac

Reputation: 335

React: Set checkboxes to checked on uptade form with antd

I am using Ant Design on my form.
There is users with checkboxes. When I check them, users details input are shown and I set value.
On update form I want to set checkboxes checked = true and show details inputs of users which was checked on create form.

What is the best way to do it?

    <Form.Item name="employeeIds">
      <Checkbox.Group style={{ width: "100%" }}>
         <Row>
         {props.employees.map((employee) => (
            <Col key={employee.id} span={6}>
              <Checkbox defaultChecked={employee.id} onChange={(e) => 
               selectEmployees(e, employee.name, employee.surname)} value={employee.id}>
                                {employee.name} {employee.surname}
                            </Checkbox>
                        </Col>
                    ))}
                </Row>
            </Checkbox.Group>
        </Form.Item>

 {selectedEmployees?.map((i, b) => (
    <Card>
       <Row>
        <Col span={5}>
         <label> {i.employeeName}:</label>
          </Col>
           <Col >
            <Form.Item
              {...b}
              name={[b, 'employeeId']}
              >
         <Input/> 
           </Form.Item>
             </Col>
                </Row>
                     </Card>  
                )   )}


const selectEmployees = (e, employeeName, employeeSurname) => {
    var fullName = employeeName + " " + employeeSurname
    if (!selectedEmployees.some(person => person.id == e.target.value)) {
        setSelectedEmployees(prev => [...prev, {
            employeeName: fullName,
            id: e.target.value
        }]);
    }
    else {
        setSelectedEmployees(selectedEmployees.filter(item => item.id !== e.target.value))
    }
}

Upvotes: 0

Views: 2337

Answers (1)

windmaomao
windmaomao

Reputation: 7661

You have list of items and if any of them has been selected. Suppose we use a separate array to keep track of the selection.

  const [selection, seSelection] = useState([])

when you click the checkbox, it'll either add or remove the item, depending on if it's already in selection.

  const onCheck = (item) => {
    if (selection.includes(item)) {
      setSelection(selection.filter(v => v !== item))
    } else {
      setSelection([...selection, item])
    }    
  }

Wire this event with the checkbox,

<Checkbox onChange={onCheck} />

Now you can display the selections.

  selection.map(item => { render })

This is a simple example. The best way is to send the flag of selected into onCheck

  const onCheck = (item, selected) => {

This way you don't get sync issue between checkbox and your selection.

Upvotes: 1

Related Questions