Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

84
Views
Getting ref to props.children by React.cloneElement returns always null

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!