ReNinja
ReNinja

Reputation: 573

Get the drop down items in the console in React js

I need to fetch the clicked dropdown item and log it in the console using React js.

Code:

<div onClick={this.handleSearchBtn} className="dropdown-menu">
  <a className="search-item dropdown-item" href="#" >Authors</a>
  <a className="search-item dropdown-item" href="#">Article Title</a>
  <a className="search-item dropdown-item" href="#">PMID</a>
  <a className="search-item dropdown-item" href="#">Mesh Terms</a>
</div>

Upvotes: 0

Views: 156

Answers (1)

Arun AK
Arun AK

Reputation: 4370

From my understanding, you can do something like this

class Anchor extends React.Component {
  state = {
    selected: ''
  }

  handleSearchBtn = (event) => {
    if (event.target.className.indexOf("search-item") !== -1) {
      this.setState({ selected: event.target.text });
    }
  };
  
  render() {
    return (
      <div onClick={this.handleSearchBtn} className="dropdown-menu">
        selected: {this.state.selected}
        <a className="search-item dropdown-item" href="#">
          Authors
        </a>
        <a className="search-item dropdown-item" href="#">
          Article Title
        </a>
        <a className="search-item dropdown-item" href="#">
          PMID
        </a>
        <a className="search-item dropdown-item" href="#">
          Mesh Terms
        </a>
      </div>
    );
  }
}

ReactDOM.render(<Anchor />, document.getElementById("root"));

Here is the demo

Hope it helps :)

Upvotes: 1

Related Questions