Ankita Sinha
Ankita Sinha

Reputation: 109

Multiselect in react bootstrap dropdown

I am trying to implement a multi select(something like a select all) and deselect all in React Bootstrap drop down as a drop down item.

<Dropdown>
  <Dropdown.Toggle variant="success" id="dropdown-basic">
    Dropdown Button
  </Dropdown.Toggle>

  <Dropdown.Menu>
    <Dropdown.Item href="#/action-1">**Select All**</Dropdown.Item>
    <Dropdown.Item href="#/action-1">Action</Dropdown.Item>
    <Dropdown.Item href="#/action-2">Another action</Dropdown.Item>
    <Dropdown.Item href="#/action-3">Something else</Dropdown.Item>
    <Dropdown.Item href="#/action-1">**Deselect All**</Dropdown.Item>
  </Dropdown.Menu>
</Dropdown>

How can I implement the select all and deselect all functionality?

Upvotes: 1

Views: 3986

Answers (1)

Agent K
Agent K

Reputation: 351

I believe this code should work for you:

import React, { useState } from "react";
import { Col, Form } from "react-bootstrap";

export default function App() {
  const [field, setField] = useState([]);

  return (
    <Form.Group as={Col} controlId="my_multiselect_field">
      <Form.Label>My multiselect</Form.Label>
      <Form.Control as="select" multiple value={field} onChange={e => setField([].slice.call(e.target.selectedOptions).map(item => item.value))}>
        <option value="field1">Field 1</option>
        <option value="field2">Field 2</option>
        <option value="field3">Field 3</option>
      </Form.Control>
    </Form.Group>
  );
}

Just replace Form.Group with Dropdown.Menu and option with Dropdown.Item

Upvotes: 3

Related Questions