Home > Enterprise >  In ReactJS, how can I assign multiple ref to a single DOM?
In ReactJS, how can I assign multiple ref to a single DOM?

Time:11-18

I have a dialogue component in which I have created a ref, but I also want to pass the ref from the parent to it. How can I do this?

import { forwardRef } from "react";

export const PopOver = ({
  show = false,
  ...
}, ref) => {

  const thisRef = useRef(null);

  // dealing with UI changes with 'thisRef'

  return (
    <div
      ref={thisRef}, // How can I add a `ref` here?
      ....
    >
      Hello world
    </div>
  );
};

export default forwardRef(PopOver);

CodePudding user response:

You can wrap it with another element and pass parent ref to it sth like this :

   <div ref={ref}>
    <div
      ref={thisRef}
      ....
    >
      Hello world
    </div>
  </div>

or if you want to replace ref you can do it in useEffect like this :

useEffect(()=>{
 if(ref.current){
  thisRef.current = ref.current
   }
},[ref])

CodePudding user response:

Can't assign multiple refs directly to the same element. But can use useEffect to assign value to another ref

const otherRef = useRef(null);
const thisRef = useRef(null);

useEffect(() => {
  otherRef.current = thisRef.current;
}, [thisRef.current]);

return <div ref={thisRef} />;
  • Related