How to set selected item in reactstrap Dropdown?

user657009 picture user657009 · Jun 5, 2017 · Viewed 23.9k times · Source

How to set selected item in reactstrap Dropdown?

There is example of dropdown: https://reactstrap.github.io/components/dropdowns/

When I select item in dropdown, it is not displayed.

*******************Working solution*****************************

import React from "react";
import {ButtonDropdown, DropdownItem, DropdownMenu, DropdownToggle} from "reactstrap";
import superagent from "superagent";

class BootstrapSelect extends React.Component {

    constructor(props) {
        super(props);

        this.toggle = this.toggle.bind(this);
        this.changeValue = this.changeValue.bind(this);
        this.state = {
            actions: [],
            dropDownValue: 'Select action',
            dropdownOpen: false
        };
    }

    toggle(event) {

        this.setState({
            dropdownOpen: !this.state.dropdownOpen
        });
    }

    changeValue(e) {
        this.setState({dropDownValue: e.currentTarget.textContent});
        let id = e.currentTarget.getAttribute("id");
        console.log(id);
    }


    componentDidMount() {
        superagent
            .get('/getActions')
            .type('application/json; charset=utf-8')
            .end(function (err, res) {
                console.log(res.body);
                this.setState({actions: res.body});
            }.bind(this));

    }

    render() {
        return (
            <ButtonDropdown isOpen={this.state.dropdownOpen} toggle={this.toggle}>
                <DropdownToggle caret>
                    {this.state.dropDownValue}
                </DropdownToggle>
                <DropdownMenu>
                    {this.state.actions.map(e => {
                        return <DropdownItem id={e.id} key={e.id} onClick={this.changeValue}>{e.name}</DropdownItem>
                    })}
                </DropdownMenu>

            </ButtonDropdown>
        );
    }

}

export default BootstrapSelect;

Answer

Nevosis picture Nevosis · Jun 5, 2017

Add an onclick on your DropDownItem (inside a div ?) to change your state. Set a "dropDownValue" from your click event. In your dropDownToggle, get your state.dropDownValue.

Something like this :

changeValue(e) {
  this.setState({dropDownValue: e.currentTarget.textContent})
}

<DropdownToggle caret>
    {this.state.dropDownValue}
</DropdownToggle>
<DropdownItem>
    <div onClick={this.changeValue}>Another Action</div>
</DropdownItem>

Of course, don't forget to init it and bind the function for your this to work.