Skip to content Skip to sidebar Skip to footer

React: Can I Add Attributes To Children's Resultant Html?

I have a component that wraps other components: class MyComp extends React.Component { render() { return
{this.props.children}
} } Let's say I add

Solution 1:

Not sure why you need this and I do recommend you to rethink your architecture before it is too late.

But you can do a little bit of a hackery using ReactDOM.findDOMNode.

First you need to set refs for every child component. By cloning element and assigning a ref.

Then attach hooks on componentDidMount and componentDidUpdate events, find dom element using findDOMNode and manually populate dataset. DEMO.

importReact, { Component, Children, cloneElement } from'react'import { render, findDOMNode } from'react-dom'classMyCompextendsComponent {
  componentDidMount() {
    this.setChildAttrs()
  }

  componentDidUpdate() {
    this.setChildAttr()
  }

  setChildAttrs() {
    const { childAttrs } = this.propsconstsetAttrs = el => Object.keys(childAttrs)
      .forEach(attr => el.dataset[attr] = childAttrs[attr])

    // for each child ref find DOM node and set attrsObject.keys(this.refs).forEach(ref =>setAttrs(findDOMNode(this.refs[ref])))
  }

  render() {
    const { children } = this.propsreturn (<div> {
        Children.map(children, (child, idx) => {
          const ref = `child${idx}`
          return cloneElement(child, { ref });
      })} </div>)
  }
}

Post a Comment for "React: Can I Add Attributes To Children's Resultant Html?"