React.JS: Passing button id as parameter onClick function

React.JS: Passing button id as parameter onClick function
0.0 0

#1

Hi FreeCodeCampers!

I’ve started with learning React JS and I am trying to solve the Twitch challenge. So far I’m just working with some dummy data to get some basic functionality working.

I’m stuck at passing on parameters (such as a button id) to the button onClick event. I’ve been getting results back ranging from ‘undefined’ to 'Codepen '(when passing attribute name as parameter).

Codepen result using: onClick={()=>this.refreshStatus(name)}

I’ve searched the net and saw multiple people asking this question. None of the given answers worked for me. Is there something wrong with the way my code is set up?

The project: https://codepen.io/tomfledderus/pen/RoMKaP

Any help or feedback on the code is really appreciated!


#2

If I understood your question right, so you are asking how to get the value of “id” in the handler passed to onClick event,right?
Like for e.g,

<button onClick={this.showOffline} id='offline'>Offline</button>
showOffline(){  
   this.props.offline()    
  }

You want to access the value of id in showOffline function.
What you can do is this,

showOffline(e){  
    console.log(e.target.id)
   this.props.offline()    
  }

Hope it helps!


#3

I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.


#4

Thanks😊…I just thought it’s a short code!But now obviously it looks more clear


#5

That was exactly what I wanted Faizahmadfaiz, thanks a lot!


#6

Thank you for the solution !!