smmoosavi / jsx-xml

Generate xml string from jsx
MIT License
26 stars 5 forks source link

How to do something like React `cloneElement`? #7

Open remorses opened 4 years ago

remorses commented 4 years ago

I tried the following

<element.type {...element.props}>{children}</element.type>

But it does not work because JSXXML output is an object with shape

{
  'tag': [
    {
      ...props
    },
    children
  ]
}

How can i re instantiate the element?

remorses commented 4 years ago

I wrote this, i will test on my project and open a pull request if it behaves ok


function cloneElement(element, props = {}, children = []): JsxElement {
    const ks = Object.keys(element)
    if (!ks.length) {
        throw new Error(`element ${element} invalid, no keys`)
    }
    const tag = ks[0]
    const oldProps = element[tag][0] || {}
    return {
        [tag]: [
            { ...oldProps, ...props },
            ...element[tag]?.slice?.(1),
            ...children,
        ],
    }
}
smmoosavi commented 4 years ago

Note that jsx-xml render is not lazy. this means that your solution only works for tags and not components.