Yurkee
Yurkee

Reputation: 873

React: passing parameters to a function in map

I am building a component that shows array of users in React using MaterialDesign's Table.

Users Table Each row is generated by a map function:

let actions = this.props.rowButtons;
...
{this.props.tableData.map( (val, index) => (
                       <TableRow key={index}>
                         <TableRowColumn >{index}</TableRowColumn>
                         <TableRowColumn >{val.firstName}</TableRowColumn>
                         <TableRowColumn >{val.lastName}</TableRowColumn>
                         <TableRowColumn >{val.email}</TableRowColumn>
                         <TableRowColumn >
                            <ActionButtons actions={actions}/>
                         </TableRowColumn>
                       </TableRow>
))}

<ActionButtons> component creates one or many buttons, and as an argument takes array of objects like [{type: string, onClick: function}, {type: string, onClick: function}, ... ] (one button for each object in array); Parent component is sending such an array in this.props.rowButtons.

I want to pass val as an argument to each onClick function to have something like

actions = [{type: "personButton", onClick: onClick(val)}, {type: '', onclick: someOtherfunction(val)}]; 

Upvotes: 0

Views: 5049

Answers (1)

Prakash Sharma
Prakash Sharma

Reputation: 16482

You have to modify the actions a bit. Try doing it following way.

modifyActions = (actions, val) => {
  return actions.map((a) => {
      return Object.assign({}, a, {onClick: () => a.onClick(val)})
  })
}

<ActionButtons actions={this.modifyActions(actions, val)})}/>

Upvotes: 1

Related Questions