I am building a react web app to help my learning. I am trying to create a table which displays some fictional items for purchase. At the end of each row I want a button which will buy that item for the user.
The number of items listed may change over time and so I want the layout to be dynamic. The main code is in solidity so I store the addresses for each item in an array in the state and then the button would prompt the user to send money to the item's address.
I want the button to carry the address for the row into a 'buyItem' function. The two problems I am encountering are that upon reload the button seems to be triggered automatically. And that, when clicked, it doesn't seem to be passing the address from that row but rather the whole array. ie i want address[i] to be passed for the button in each row.
<tbody>
{this.state.address.map((d) => (
<tr>
<td>
<button type="button" className='create-btn' onClick={this.buyItem(d)}>Buy!</button>
</td>
</tr>
))}
</tbody>
Are you allowed to pass a variable to a function through a button and how would you go about doing this in the above scenario?
When you say onClick = {this. buyItem(d)}, you are calling the function when you create the button element. Instead, you want to create a callback function within the onClick, something like:
onClick = {() => this.buyItem(d)}
Here, you are defining the function, not calling it, so it won't trigger automatically when it loads.