0

I am trying to console.log the value of the dropdown item that I selected. I have tried e.target.value and data.value. e.target.value returns nothing and data.value returns undefined.

<DropdownItem
    onClick={(e, data) => {
        // this.setState({ choice: this.props.size });

        // value.addChoices(this.state.choice);
        console.log(data.value);
    }}
    className="bg-info"
>
    {this.props.size}
</DropdownItem>
khan
  • 1,466
  • 8
  • 19

2 Answers2

2

this will give you the text value inside of the DropdownItem button

<DropdownItem
  onClick={e => {
    // this.setState({ choice: this.props.size });

    // value.addChoices(this.state.choice);
    console.log(e.target.innerText);
  }}
  className="bg-info"
>
  {this.props.size}
</DropdownItem>
Kamran Nazir
  • 672
  • 4
  • 11
1

What you want to do normally is to pass a value prop (that's why e.target.value is undefined, because you did not pass any value).

i.e.:

        <DropdownMenu>
          <DropdownItem value='one' onClick={(e) => console.log(e.target.value)}>Foo Action One</DropdownItem>
        </DropdownMenu>

Full example code (changing the reactstrap sample component):

import React from 'react';
import { Dropdown, DropdownToggle, DropdownMenu, DropdownItem } from 'reactstrap';

export default class DropdownTest extends React.Component {
  constructor(props) {
    super(props);

    this.toggle = this.toggle.bind(this);
    this.state = {
      dropdownOpen: false
    };
  }

  toggle() {
    this.setState(prevState => ({
      dropdownOpen: !prevState.dropdownOpen
    }));
  }

  handleClick = (e) => {
    console.log(e.target.value);
  }

  render() {
    return (
      <Dropdown isOpen={this.state.dropdownOpen} toggle={this.toggle}>
        <DropdownToggle caret>
          Dropdown
        </DropdownToggle>
        <DropdownMenu>
          <DropdownItem value='one' onClick={this.handleClick}>Foo Action One</DropdownItem>
          <DropdownItem value='two' onClick={this.handleClick}>Bar Action Two</DropdownItem>
          <DropdownItem value='three' onClick={this.handleClick}>Quo Action Three</DropdownItem>
        </DropdownMenu>
      </Dropdown>
    );
  }
}

Sanda
  • 1,357
  • 19
  • 29