Moaaz Bhnas
Moaaz Bhnas

Reputation: 1189

How to access ref from a non-related component?

I have a fixed-positioned navigation bar that I want to make static when some menu down in the app expands.
The problem is that both components are far away from each other in the app hirarchy.

const Nav = () => {
  const navRef = useRef(null);
  return (
    <nav
      ref={navRef}
    ></nav>
  );
}

const Menu = () => {
  // I want to access the nav ref here to change its style when the menu expands
  return (
    <ul></ul>
  )
}

Upvotes: 0

Views: 309

Answers (1)

Yash Gadle
Yash Gadle

Reputation: 451

You can do something like this ...

const App = () => {
  const navRef = useRef();

  const setStyleForNav = (style) => {
    navRef.current.style = style;  
  };

  return (
    <Nav ref={navRef}/>
    <Menu setStyleForNav={setStyleForNav}/>
  )
};

const Nav = React.forwardRef((props, ref) => {
  return (
    <nav
      ref={ref}
    ></nav>
  );
});

const Menu = ({setStyleForNav}) => {
  // I want to access the nav ref here to change its style when the menu expands
  return (
    <ul></ul>
  )
}

Upvotes: 1

Related Questions