How to pass multiple props to an element created by React.createElement?

Viewed 2345

React.createElement( type, [props], [...children] )

as the react documentation said. But somehow it's not working for me with multiple props. I tried to pass an array of key-value objects, pass a container object with key-values, but nothing isn't worked. Let me show how I tried it:

//input.js
const Input = ({name, elementProps}) => {
    const { element, props } = elementProps;
    return React.createElement(element, props)
}

export default Input;
//props from
{
    name: "msg",
    element: "textarea",
    props: [
        {placeholder: "Message"},
        {rows: "4"},
        {cols: "50"},
    ]
}
//rendered by method
const { name, ...elementProps } = objectAbove;
return <Input name={name} elementProps={elementProps} />

What's the required syntax to pass multiple props?

1 Answers

props should be a non-array object, not an array. The props array you're creating looks like it could easily be a single object rather than an array of objects. Instead of:

props: [
    {placeholder: "Message"},
    {rows: "4"},
    {cols: "50"},
]

perhaps

props: {
    placeholder: "Message",
    rows: "4",
    cols: "50"
}

As Tholle points out in a comment, the [] shown in the syntax in the documentation:

React.createElement( type, [props], [...children] )

...is meant to show that props is optional, not that it's an array.

Related