1

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 command. 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.

3
  • The function can accept parameters 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> 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 Commented Mar 19, 2018 at 19:59

3 Answers 3

4

A 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 component)

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>
Sign up to request clarification or add additional context in comments.

Comments

1

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)
}

Comments

1

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.
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.