krozero
krozero

Reputation: 6423

React add dynamic element key and value

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!

Upvotes: 2

Views: 57

Answers (4)

ClusterH
ClusterH

Reputation: 925

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>
  )
}

Upvotes: 1

Abhishek-Saini
Abhishek-Saini

Reputation: 743

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

spread operator can be used here

Upvotes: 1

arvir
arvir

Reputation: 101

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>
  )
}

Upvotes: 1

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41387

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>

Upvotes: 1

Related Questions