I'm using a component library, which renders an input
field nested within several div
elements
<ComponentLibrary />
This component library renders a tree similar to the one below:
<div className={outerDiv}>
<div>
<input type="text" /> // This the element I'm trying to access
</div>
</div>
I built a custom component which wraps the ComponentLibrary
similar to below:
<MyCustomComponent>
<ComponentLibrary />
</MyCustomComponent>
I don't have access to modify the component library, but I need to access it's input
field within my component.
const MyCustomComponent = (props) => {
const inputRef = useRef();
return (
{React.cloneElement(props.children, {
ref: inputRef // This ofcourse references the 'outerDiv'
}}
);
}
Some possible relevant notes, when I console.log(props.children)
. While the component is react element, the type is a forward ref.
> children:
$$typeof: Symbol(react.element)
ref: null
> type: {$$typeof: Symbol(react.forward_ref)}
Below are a few more attempts I made:
{React.Children.map(props.children, child => {
console.log(child) // Only logs the Component element. No reference of DOM nodes
}
The closest I've gotten is by using the inputRef
I created in the 4th code block above.
console.log(inputRef.current)
// Logs `outerDiv` element
console.log(inputRef.current.children[0]?.children[1]?.children[1])
// Returns the right element, but an absolute mess. Is this my best solution?