Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is ref always null?

I have a component below, at the first render I have the correct ref to input, but then I always get null, with the next render, please tell me why? ref is passed on through props to input:

const inputRef = useRef(null);
useEffect(() => {
  setTimeout(() => {
    if (inputRef.current) {
        inputRef.current.focus();
    }
  });
 }, [inputRef]);

render() {
  return(
    <div>
      <FirstComponent />
      {({ selectedItem, items }) => (
             <SecondCompontnt
                inputRef={inputRef}
                items={items}
                onSelect={onSelect}
                value={selectedItem}
              />
          )}
    </div>
  )
}
like image 235
Blackbonny Avatar asked Oct 19 '25 04:10

Blackbonny


1 Answers

Once you have the ref in the parent component for one of its children then you need to apply so called Forwarding Ref technique, as the documentation states:

Ref forwarding is a technique for automatically passing a ref through a component to one of its children. This is typically not necessary for most components in the application.

Let's say you have in the parent component as the following:

const childDivRef = useRef(null);

return <>
  <ChildComponent ref={childDivRef} />
</>

Then you need to have in the child component as below:

import React, { forwardRef } from 'react';

const ChildComponent = forwardRef((props, ref) => {
    return <div ref={ref} className="child-component">
        <h3>Child component</h3>
    </div>
})

If you need a working example, please find this GitHub repository what I made earlier: https://github.com/norbitrial/react-forwarding-ref-example

I hope this helps!

like image 85
norbitrial Avatar answered Oct 21 '25 17:10

norbitrial



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!