0

I recently started to play around with React and am facing an issue in the code below. Here is my component, the question will follow:

class CustomButton extends Component {
    render() { 
        const {number,parent} = this.props;
        return (
            <button className="button"
            onClick={() => parent.onEvent123()}>Option{number}
            </button>
        )
    }
}

export default CustomButton;

This component is already working. I can use it like that:

<CustomButton number={123} parent={this.props} />

And the onClick line maps to:

onClick={() => this.props.onEvent123()}>Option123

But here is what I really want:

<CustomButton number={789} parent={this.props} />

mapping to:

onClick={() => this.props.onEvent789()}>Option789

for any number (here 789) I pass.

I have tried something like:

return (
    <button className="button"
    onClick={() => parent.onEvent{number}()}>Option{number}
    </button>
)

in order to parameterize the function name, but it doesn't work. What is the way to get what I want? Of course I would not want to pass the hard coded function name. I have the feeling there has to be a solution. But I am still too beginner in React.

Michel
  • 10,303
  • 17
  • 82
  • 179

1 Answers1

1

try:

return (
    <button className="button"
    onClick={() => parent[`onEvent${number}`]()}>Option{number}
    </button>
)
lam
  • 545
  • 1
  • 3
  • 10