I made a tooltip component with React.cloneElement. It works fine until I use it with a functional component. Then the events I want to add are ignored (because they are not in the props of the child?). Can I force them onto the outermost/first child of my functional child component?
class Tooltip extends Component {
render() {
return React.Children.map(this.props.children, (child) => {
return React.cloneElement(child, {
onMouseEnter: () => { console.log('onMouseEnter'); }
})
});
}
}
<Tooltip right text="Logout">
<button>
This works fine.
</button>
</Tooltip>
<Tooltip right text="Logout">
<MyButton>
This does not work (resp. it works only if the child passes the {...props} manually)
</MyButton>
</Tooltip>
This does not work because React.cloneElement only sees the "top-level" element and not the contents of it.
Assuming <MyButton /> looks like:
const MyButton = ({ children }) => <button>{children}</button>;
Then, when you do:
<Tooltip>
<MyButton>
This does not work (resp. it works only if the child passes the
manually)
</MyButton>
</Tooltip>
React.cloneElement attaches the onMouseEnter prop to the MyButton functional component instead of the <button> element inside the MyButton and since MyButton is not a valid element the event does not work on it.
You can log the values for children in Tooltip class and verify the same.
{
type: "button"
key: ".0"
ref: null
props: Object
children: "This works fine."
onClick: ƒ onClick() {}
_owner: FiberNode
_store: Object
}
This is the representation when using:
<Tooltip right text="Logout">
<button>
This works fine.
</button>
</Tooltip>`:
vs
{
type: ƒ MyButton() {}
key: ".0"
ref: null
props: Object
children: "Thss does not work (resp. it works only if the child passes the
manually)"
onClick: ƒ onClick() {}
_owner: FiberNode
_store: Object
}
for
<Tooltip>
<MyButton>
This does not work (resp. it works only if the child passes the
manually)
</MyButton>
</Tooltip>:
Ideally, what you are trying to do should be done using Context, but for an easier workaround, you can pass through the props you receive on MyButton to its children.