Reputation: 1189
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
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