DEV Community

Faith Morante
Faith Morante

Posted on

Custom dropdowns with React

Ok if you followed my last post:
https://dev.to/idiglove/create-custom-components-from-json-with-react-1oeb

I showed there how to create custom components from a json file with React.
How about dropdowns where you need to store its values and each dropdown has its own toggle (if you're using a library like Reactstrap)?

Here's how I did it:

const [dropdowns, setDropdowns] = useState({})
const [savedDropdowns, setSavedDropdowns] = useState({})

const toggleDropdown = (i) => {
    setDropdowns({...dropdowns, [i]: !dropdowns[i]})
}

const onChangeDropdown = (value, id) => {
    setSavedDropdowns({...savedDropdowns, [id]: value})
}
Enter fullscreen mode Exit fullscreen mode

Inside your function where you render your custom components:

<Dropdown 
   isOpen={dropdowns[id]} toggle={() => toggleDropdown(id)}
    >
        <DropdownToggle caret>
            {id}
        </DropdownToggle>
        <DropdownMenu>
            {options.map((o, oi) => {
                return <DropdownItem key={oi} value={o.value}
onClick={() => onChangeDropdown(o.value, id)}>{o.name}</DropdownItem>
            })}
        </DropdownMenu>
</Dropdown>
Enter fullscreen mode Exit fullscreen mode

Hope you get something out of this.

Cheers,
FM

Top comments (2)

Collapse
 
jacqueline profile image
Jacqueline Binya

Love you content Faith🌼🌻

Collapse
 
idiglove profile image
Faith Morante

Thanks! I will try to post more