Home > database >  Use text that is passed through props, to know which constant is called for button onClick
Use text that is passed through props, to know which constant is called for button onClick

Time:05-20

does anyone know how I can pass the name of the const I want to use for the button onClick here?

So I have two const's defined in my component, what I want to achieve is that each button in a column calls a different const, so I pass the name of the const I want to use through props, but that doesn't work. For example if I pass clickHandler="handleFirstOption"

The column button onClick has to become:

<Button role="group" mt={10} onClick={handleFirstOption}>

Does anyone know how I can accomplish this?

FooterRow.jsx

<FooterColumn
   clickHandler="handleFirstOption"
/>
<FooterColumn
   clickHandler="handleSecondOption"
/>

FooterColumn.jsx

const handleFirstOption = event => {
   updateStep(firstOption);
};

const handleSecondOption = event => {
   updateStep(secondOption);
   event.preventDefault();
};
<Button role="group" mt={10} onClick={clickHandler}>

CodePudding user response:

Define this inside your FooterColumn:

let handlers = {

    handleFirstOption: event => {
        updateStep(firstOption);
    }
    handleSecondOption: event => {
        updateStep(secondOption);
        event.preventDefault();
    }
}

Then you can specify which handler you want using string name from props:

<Button role="group" mt={10} onClick={handlers[clickHandler]}>
  • Related