Home > OS >  useRef between components
useRef between components

Time:11-21

I have two components: <Header/> with hamburger button on it, and <Sidebar/>.

The idea is: if I click hamburger button the sidebar should be removed, or it should be appeared if I click back.

I have no issues to do so in one component where I use useRef:

  const sideBarRef = useRef()
  
  function toogleSideBar() {
    sideBarRef.current.classList.toggle('-translate-x-full')
  }

but I am not sure how to do it between components, where I have a layout with <Header/> and <Sidebar/> in it, and I need to initiate toogleSidebar() in <Header/> and some how pass ref={sideBarRef} in <Sidebar/>.

CodePudding user response:

As in most cases with React, there is no need to use a ref. A better approach is to lift the state up to the parent component and render the sidebar conditionally. The parent component is the one which renders both Header and Sidebar, let's call it App.

In your App component:

const App = () => {
  const [showSidebar, setShowSidebar] = useState(true);

  const toggleSidebar = () => setShowSidebar(prev => !prev);
  
  return (
    <main>
      <Header onClickMenu={toggleSidebar} />
      {showSidebar && <Sidebar />}
    </main>
  );
};

And then in your Header:

const Header = ({ onClickMenu }) => {  
  return (
    <nav>
      <Hamburger onClick={onClickMenu} />
      ...
    </nav>
  );
};

CodePudding user response:

You can pass the state thru code like a variable

In App.js declare the

    //App.js
    let sideBarRef = useRef(false); 

    let content = (
        {sideBarRef? (<SideBar sideBarRef ={sideBarRef} />
                      ): null} 
        <Header sideBarRef ={sideBarRef} />
          


export default function SideBar({sideBarRef,}) {   
<use sideBarRef in code as if declare here>
}

export default function Header({sideBarRef,}) {   
<use sideBarRef as if declare here >
}
  • Related