Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I properly change the title of react-bootstrap DropdownButton on click?

I am trying to change the displayed text/title in the DropdownButton upon clicking on a Dropdown.Item.

I've tried to pass various parameters into the changeValue method/function but to no solution as of yet. Using this approach, text the parameter in the function appears to be empty. Therefore the state property, dropDownValue is becoming empty, thus leaving me with no title in the drop down after click on an item.

import React from 'react';
import './App.css';
import DropdownButton from 'react-bootstrap/DropdownButton';
import Dropdown from 'react-bootstrap/Dropdown';

class App extends React.Component {
  constructor() {
    super();

    this.state = {
      dropDownValue: "Select an item"
    }
  }

  changeValue(text) {
    this.setState({dropDownValue: text})
  }

  render() {
    return (
      <div className="App">
        <header className="App-header">
        </header>
        <div>
        <DropdownButton id="dropdown-item-button" title={this.state.dropDownValue} className="format"> 
          <Dropdown.Item as="button"><div onClick={() => this.changeValue(this.textContent)}>Item #1</div></Dropdown.Item>
          <Dropdown.Item as="button"><div onClick={() => this.changeValue(this.textContent)}>Item #2</div></Dropdown.Item>
          <Dropdown.Item as="button"><div onClick={() => this.changeValue(this.textContent)}>Item #3</div></Dropdown.Item>
        </DropdownButton>
        </div>
      </div>
    );
  }
}

export default App;
like image 284
MisterTams Avatar asked Sep 12 '25 03:09

MisterTams


1 Answers

Just change this,

<Dropdown.Item as="button"><div onClick={() => this.changeValue(this.textContent)}>Item #1</div></Dropdown.Item>

with this,

<Dropdown.Item as="button"><div onClick={(e) => this.changeValue(e.target.textContent)}>Item #1</div></Dropdown.Item>
like image 74
ravibagul91 Avatar answered Sep 13 '25 18:09

ravibagul91