Home > Net >  React add dynamic element key and value
React add dynamic element key and value

Time:11-30

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!

CodePudding user response:

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>

CodePudding user response:

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

CodePudding user response:

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

spread operator can be used here

CodePudding user response:

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