user1234
user1234

Reputation: 3159

How to add a listener to the array of objects in ReactJs

I have a prop called buttons, whose type is an array. I'm passing that to my component in a such a way that when present it should list all the buttons in that array, like this:

render() {
return (
<div>
      <MyComp title="Some titme" subtitle="subtitle" buttons={this.getButtonArray()}>
</div>
)
}
getButtonArray() {
    let buttonArray=[{
        type:"aaa",
        text: "Downlaod",
        onClick: {this.onCancel.bind(this)}//getting an eslint error saying Fatal: this is a reserved keyword
    }]
}

here is my MyComp defined:

export default class MyComp extends React.Component {

  static defaultProps = {
    buttons: [{
       text: "Confirm",
        type: "secondary",
       onClick : function() {console.log("Confirm clicked");}
     },
      {
       text: "cancel",
        type: "secondary",
       onClick : function() {console.log("cancel clicked");}
     }]

}
render() {
 return (
<div>
    {this.props.buttons && this.props.buttons.map(el => <Button key={el.type} text={el.text} type={el.type} onClick={el.onClick}/>)} //<Button> is another component imported.
</div>
)
}
}

Any ideas why "this" is not acceptable there and how can I possiblely have an onclick on an array of object?

Thanks

Upvotes: 0

Views: 78

Answers (1)

ladyk
ladyk

Reputation: 106

You are passing function not object so you should remove {}, onClick: this.onCancel.bind(this) is enough.

Upvotes: 1

Related Questions