reactjsreact-markdown

How to add react reference to HTMLCollection items?


I'm trying to access attach references to each paragraph/heading in react-markdown. But I can't figure out how to add a ref to c below.

const children = Array.from(div.children)
children?.forEach((c, i) => {
  // c = <p>...</p> or <h1>...</h1>
  // add ref from useRef to c
})

Solution

  • You can clone an element with ReactcloneElement(element, propsObject, childrenAray). This preserves key and ref props from the cloned element. More info on that here: https://reactjs.org/docs/react-api.html#clonelement

    Alternatively you can do this:

    const children = Array.from(div.children)
    children?.forEach((c, i) => {
      return <c.type {...c.props} ref={yourRef} key={i}>{c.props.children}</c.type>
    })