Search code examples
reactjsreact-bootstrapreact-state

bootstrap split button dropdown item value undefined


I'm not used to playing with split button values in react bootstrap but i'm just trying to update my react state with the value of a splitbutton but the value always returns undefined... Not sure what I'm doing wrong? I have a value property for all my dropdown items in place already.

handleChange=(e)=>{
    this.setState({[e.name]: e.target.value})
    console.log(e.target.value)
}

<SplitButton className="dropdownItem" variant='Secondary' title='step pattern'>
      <Dropdown.Item onClick={this.handleChange} name='stepPattern'  eventKey="1" value='step' ><img className="patterns" alt="a stepped gradient" src={step}></img></Dropdown.Item>
      <Dropdown.Divider />
      <Dropdown.Item onClick={this.handleChange} name='stepPattern' eventKey="2" value='wave' ><img className="patterns" alt="a wavy gradient" src={wave}></img></Dropdown.Item>
       <Dropdown.Divider />
       <Dropdown.Item onClick={this.handleChange} name='stepPattern'  eventKey="3" value='curve' ><img className="patterns" alt="an upward sloped gradient" src={curve}></img></Dropdown.Item>     
       </SplitButton> 

Solution

  • If you are using handleChange (which I suggest), you could change it in the following way:

    handleChange = value => {
        this.setState({ stepPattern: value });
        console.log(value);
    }
    

    By doing this, now all you need is your Dropdown.Item to call the handleChange function. Try the following:

      render() {
        return (
          <SplitButton className="dropdownItem" variant='secondary' title='step pattern' >
            <Dropdown.Item onClick={() => { this.handleChange(1); }} eventKey="1" value='step' ><img className="patterns" alt="a stepped gradient" src={step}></img></Dropdown.Item>
            <Dropdown.Divider />
            <Dropdown.Item onClick={() => { this.handleChange(2); }} eventKey="2" value='wave' ><img className="patterns" alt="a wavy gradient" src={wave}></img></Dropdown.Item>
            <Dropdown.Divider />
            <Dropdown.Item onClick={() => { this.handleChange(3); }} eventKey="3" value='curve' ><img className="patterns" alt="an upward sloped gradient" src={curve}></img></Dropdown.Item>
          </SplitButton >
        );
      }
    

    Now each of the buttons is calling the function with predefined value, which can be taken out in constants.