Home > Software engineering >  useRef inside multiple shared components is not returning the ref object
useRef inside multiple shared components is not returning the ref object

Time:03-30

I have an issue that I need to access the refs in a shared BaseTable component. For example on a parent route component:

function Route() {
  <div>
    <BaseTable />
    <BaseTable />
  </div>
}

function BaseTable() {
  const ref = useRef();

  console.log(ref && ref.current);
  
  return <table ref={ref}>...</table>
}

I would expect that upon the render of each BaseTable I would see the ref node, however I am only seeing it on one of the children BaseTable and the other is only returning null.

Strangely enough (and possibly important), when I make changes to the file and save, the hot reloading then picks up both nodes when re-rendering. When I only have a single BaseTable rendering, the ref is set correctly, however this issue only happens when I render multiple BaseTable components.

CodePudding user response:

Your code is correct.

I think you are confused because your are writing to the console in the render function.

The first time the function is rendered, the ref will be undefined. Instead, use the useEffect hook to write to the console after the component has mounted and the ref has been initialized. You will then see that ref.current is the table element.

function BaseTable() {
  const ref = useRef();

  useEffect(() => {
    console.log(ref && ref.current);
  }, []);

  return <table ref={ref}>...</table>;
}
  • Related