DEV Community

Faith Morante
Faith Morante

Posted on

3 2

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

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

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs