简体   繁体   中英

How to render HTMLCollection in react(passed as props)

I have a component in react that receives a HTMLCollection(10) [div, div, div, div, div, div, div, div, div, div] as props, and placing the prop directly in the return throws an error. How does one render it such that is can be appended at the end of already existing children

Poor Example for context explanation

export default function Block {
    const {children, HTMLCollectionChild} = props;

    return (
        <div>
            {children}
            {/*HTMLCollectionChild*/}
        </div>
    )
}

EDIT

The solution I found that seemed to work best is as follows

return(
    <div>
        {children}
        {HTMLCollectionChild
           ? HTMLCollectionChild.map((child) => {
            return createElement(
               child.localName,
              { key: `${generate_key()} ${child.firstElementChild.currentSrc}` },
              createElement("img", { src: child.firstElementChild.currentSrc })
            );
          })
        : null}

The only downside was that, I needed to know the structure of the HTMLCollectionChild before attempting to render it

for those needing further reading check createElement docs

You could use html-react-parser package.

import parse from 'html-react-parser';

and then use it like

HTMLCOllectionChild.map(item => (parse(item)))

For more details regarding the package, go to https://www.npmjs.com/package/html-react-parser

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM