2

I'm trying to add dynamic event key to button.

interface ButtonProps{
    actionType: string,
    actionCb: any
}

const Button = (props: ButtonProps)=>{
  return (
    <button {props.actionType}={props.actionCB}>
      Click me
    </button>
  )
}

is it possible to do something like this? or is there any other workaround for this? thanks!

4 Answers 4

1

To avoid passing invalid actionType, you need to use correct type instead of using string. and use spread operator to use dynamic attributes

interface ButtonProps {
  actionType: keyof React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>
  actionCb: any
}

const Button = (props: ButtonProps) => {
  return (
    <button {...{ [props.actionType]: props.actionCb }}>Click Me</button>
  )
}
Sign up to request clarification or add additional context in comments.

Comments

1

Pass props as key-value object and use the spread operator to dynamically apply attributes to the element

interface ButtonAttributes{
    actionType: string, 
}

interface ButtonProps{
    [ButtonAttributes.actionType]: actionCb, // like "title": "value"
}

 <button {...props}>
      Click me
    </button>

Comments

1

You could instead create an object with the dynamic key value pair and then spread that onto the props.

const Button = (props)=>{
  const dynamicProps = {
   [props.actionType]:props.actionCB,
  }
  return (
    <button {...dynamicProps}>
      Click me
    </button>
  )
}

Comments

1
<button {...{ [props.actionType]: props.actionCB }}>

spread operator can be used here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.