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

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up