Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to change dropdown title on selected option with reactstrap on react

Im 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 :-

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading