React add dynamic element key and value
Problem Description:
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!
Solution – 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>
Solution – 2
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>
)
}
Solution – 3
<button {...{ [props.actionType]: props.actionCB }}>
spread operator can be used here
Solution – 4
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>
)
}