3

I need to put multiple CompoundButtons on my SPFX webpart, I need them to trigger the same onClick event handler.

How do I know in my event which button has fired? I tried to use an id, but it seems React (sometimes) changes this ID with it's own internal one.

public render(): React.ReactElement<IReportingProps> {
    return (
     <div>
              <CompoundButton id='button1' ariaLabel='Button1' description='First button description' onClick={ this._RequestButton}>Button 1</CompoundButton> 
              <CompoundButton id='Button2' ariaLabel='Button2' description='Second button description' onClick={ this._RequestButton}>Button 2</CompoundButton> 
          </div>
          <div> Result: {this.state.result}</div>
 );
  }



@autobind
  private _RequestButton(e:any):void{
      this.setState({
        result: e.target.id
      });
  }

The above code, some clicks the etarget.id is button1 or button2 other times it can be ID__101 Is there another property I should use to determine which button fired? I don't want to use the Title of the button.

1 Answer 1

3

I don't know what you are trying to achieve but you can call your method like this:

public render(): React.ReactElement<IReportingProps> {
  return (
    <div>
        <CompoundButton id='button1' ariaLabel='Button1' description='First button description' onClick={ () => this._RequestButton('Button 1')}>Button 1</CompoundButton> 
        <CompoundButton id='Button2' ariaLabel='Button2' description='Second button description' onClick={ () => this._RequestButton('Button 2')}>Button 2</CompoundButton> 
    </div>
    <div> Result: {this.state.result}</div>
  );
}

@autobind
private _RequestButton(value: string):void{
  this.setState({
    result: value
  });
}
1
  • Of course. That makes sense to do it this way. Commented Feb 26, 2018 at 14:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.