I am referring to this dropdown documentation https://reactstrap.github.io/?path=/docs/components-dropdown--dropdown
But I can't seem to find any example that will change the dropdown title on the options selected.. can anyone show me how this is done? It has to be under a function instead of class component
This is the default code:
import React, { useState } from 'react';
import {
Dropdown,
DropdownToggle,
DropdownMenu,
DropdownItem,
} from 'reactstrap';
import PropTypes from 'prop-types';
function Example({ direction, ...args }) {
const [dropdownOpen, setDropdownOpen] = useState(false);
const toggle = () => setDropdownOpen((prevState) => !prevState);
return (
<div className="d-flex p-5">
<Dropdown isOpen={dropdownOpen} toggle={toggle} direction={direction}>
<DropdownToggle caret>Dropdown</DropdownToggle>
<DropdownMenu {...args}>
<DropdownItem header>Header</DropdownItem>
<DropdownItem>Some Action</DropdownItem>
<DropdownItem text>Dropdown Item Text</DropdownItem>
<DropdownItem disabled>Action (disabled)</DropdownItem>
<DropdownItem divider />
<DropdownItem>Foo Action</DropdownItem>
<DropdownItem>Bar Action</DropdownItem>
<DropdownItem>Quo Action</DropdownItem>
</DropdownMenu>
</Dropdown>
</div>
);
}
Example.propTypes = {
direction: PropTypes.string,
};
export default Example;
You can create a state to store the last selected item:
const [selectedItem, setSelectedItem] = useState("Dropdown");
Then you add an onClick
to every <DropdownItem/>
so you can update your selectedItem
state once an option is selected:
//...
<DropdownItem onClick={() => {setSelectedItem('Foo Action')}}>Foo Action</DropdownItem>
<DropdownItem onClick={() => {setSelectedItem('Bar Action')}}>Bar Action</DropdownItem>
//...
Finally you can display selectedItem
as dropdown title.
<DropdownToggle caret>{selectedItem}</DropdownToggle>