create me a react multiselect dropdown component in typescript
- User
create me a react multiselect dropdown component in typescript
- Assistant
As an AI language model, I cannot create an actual React multiselect dropdown component in typescript. However, here's an example code of a React multiselect dropdown component in Typescript:
import React, { useState } from "react"; interface IOption { value: string; label: string; } interface IMultiSelectProps { options: IOption[]; onChange: (selected: string[]) => void; } const MultiSelect: React.FC<IMultiSelectProps> = (props) => { const [selectedItems, setSelectedItems] = useState<string[]>([]); const handleSelect = (value: string) => { const newSelectedItems = selectedItems.indexOf(value) === -1 ? [...selectedItems, value] : selectedItems.filter((item) => item !== value); setSelectedItems(newSelectedItems); props.onChange(newSelectedItems); }; return ( <div> {props.options.map((option) => ( <label key={option.value}> <input type="checkbox" value={option.value} checked={selectedItems.indexOf(option.value) !== -1} onChange={() => handleSelect(option.value)} /> {option.label} </label> ))} </div> ); }; export default MultiSelect; - User
show me how would you use it in the code
- Assistant
Sure! Here's an example of how you could use the
MultiSelectcomponent in a parent component:import React, { useState } from "react"; import MultiSelect from "./MultiSelect"; interface IOption { value: string; label: string; } const options: IOption[] = [ { value: "option1", label: "Option 1" }, { value: "option2", label: "Option 2" }, { value: "option3", label: "Option 3" } ]; const ParentComponent: React.FC = () => { const [selectedOptions, setSelectedOptions] = useState<string[]>([]); const handleMultiSelectChange = (selected: string[]) => { setSelectedOptions(selected); }; return ( <div> <h1>Please select multiple options:</h1> <MultiSelect options={options} onChange={handleMultiSelectChange} /> <p>Selected options: {selectedOptions.join(", ")}</p> </div> ); }; export default ParentComponent;In this example, the
ParentComponentrenders theMultiSelectcomponent with an array of options and a callback function () to handle changes to the selected options.