I have a functional component that only render props.children, but I'd like to inject some custom data attribute to the DOM element that it renders.
Let's look at an example:
const Decorator = props => {
return props.children;
}
const Child = props => {
return <div>I'm a child</div>
}
- - -
// Suppose we have this:
<Decorator><Child /></Decorator>
// Then, the DOM output will be:
<div>I'm a child</div>
Now, from the example above what I'd like to achieve is that any DOM element rendered via Decorator has a custom data attribute, so:
// Suppose we have this:
<Decorator><Child /></Decorator>
// Then, the DOM output will be:
<div data-decorator-attr="foo">I'm a child</div>
I've searched here and there, but I haven't found a way to do this. Here's the list of possibilities that I have thought about and the reasons why they cannot be used:
- Inside
<Decorator>I could useReact.cloneElementand inject areftoprops.children, but therefwould reference the component itself, and NOT the rendered DOM. I would need to exportChildelement usingReact.forwardRefbut this is not viable (that's because<Decorator>could wrap anything, and I cannot edit all other component to beReact.forwardRef; - Being a functional component, I can't even use
React.findDOMNodeusing the reference to the component itself; - Inside
<Decorator>, I cuold wrapprops.childrenwith a<Fragment>, but<Fragment>doesn't supportref;
So.. I have no idea how I could achieve this. The only way I found out is to renders a wrapper DOM element in the <Decorator>, like this:
const Decorator = props => {
return <div style={{display: 'contents'}}>{props.children}</div>;
}
But what I wanted was to NOT have any wrapper DOM element.