In react I have a code like this:
var myButtons=[];
/*Products is an array of objects where each object identify a product*/
for (var p of Products) {
var button = <button
style={someStyle}
onClick={onClickFunction}>
p.name
</button>
myButtons.push(button)
}
I will use this react array of buttons on a render mand. The problem I have is that I do not know how to make one of these buttons to show its label p.name through the onClickFunction.
In react I have a code like this:
var myButtons=[];
/*Products is an array of objects where each object identify a product*/
for (var p of Products) {
var button = <button
style={someStyle}
onClick={onClickFunction}>
p.name
</button>
myButtons.push(button)
}
I will use this react array of buttons on a render mand. The problem I have is that I do not know how to make one of these buttons to show its label p.name through the onClickFunction.
Share Improve this question asked Mar 19, 2018 at 19:51 Jose Cabrera ZunigaJose Cabrera Zuniga 2,6376 gold badges39 silver badges67 bronze badges 3- The function can accept parameters – Sterling Archer Commented Mar 19, 2018 at 19:52
- so, should I use: var button = <button style={someStyle} onClick={p.name => onClickFunction(p.name)}> p.name </button> – Jose Cabrera Zuniga Commented Mar 19, 2018 at 19:55
-
You can definitely do it like that, however, I'd suggest reversing your logic. You're iterating the products, but call a function that returns a
<button>
so that you can do something like:<div>{Products.map(makeButton, this)}</div>
which will pass the data variable along into the callback. Much cleaner – Sterling Archer Commented Mar 19, 2018 at 19:59
3 Answers
Reset to default 4A simpler more user friendly way is to iterate the data with a function. (note that this does not take into account scope, so this
may be needed if it's inside a ponent)
function makeButton(data) {
return (
<button
style={someStyle}
onClick={() => onClickFunction(data.label)}> //pass parameter for callback here if binding isn't used
data.name
</button>
);
}
Now you can simply use a binding map inside your div!
<div>
{Products.map(makeButton, this)}
</div>
You can add your label as paremeter :
<button style={someStyle} onClick={p.name => onClickFunction(p.name)}>
p.name
</button>
And :
onClickFunction = (label) => () =>{
console.log(label)
}
The easiest way is to use ES6 syntax and array map
.
The name
property should be unique, and don't forget provide a key for each button:
const myButtons = Products.map(p => (
<button style={someStyle} onClick={e=>{ this.onClickFunction(e, p.name); }} key={p.name}/>
{p.name}
</button>
));
Using an arrow function, so it doesn't require .bind(this)
. Add e.preventDefault()
to prevent default behavior, if the buttons are in a form
.
onClickFunction = (e, name) => {
e.preventDefault();
// Your button behavior goes here.
}