I am trying to get child ref in Wrapper component but it always returns null. I use the common code:
export const SelectableItem = ({ children }: Props) => {
const ref = useRef<HTMLElement>(null);
useEffect(() => {
setTimeout(() => console.log(ref?.current), 1000); // returns null
}, []);
const child = React.Children.only(children);
return React.cloneElement(child, { ref: (r) => (ref.current = r) });
};
<SelectableItem>
<SomeChild />
</SelectableItem>
What is wrong?
I am not getting that issue. The only thing I really changed was the console.log since it was producing an error. Hopefully you are able to figure out what was happening from the working code below.
const SelectableItem = ({ children }: Props) => {
const ref = React.useRef(null);
React.useEffect(() => {
setTimeout(() => {
console.log(ref)
}, 1000);
}, []);
const child = React.Children.only(children);
return React.cloneElement(child, { ref: (r) => (ref.current = r) });
};
ReactDOM.render(
<React.StrictMode>
<SelectableItem>
<div />
</SelectableItem>
</React.StrictMode>,
document.querySelector('.react')
);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>