Search code examples
react-bootstrap

bootstrap react JS global


I am new to react JS and stuck in a very basic issue. I am using Bootstrap 'Offcanvas' component but the problem is that the button to toggle it is header while the menu itself is in different file. I dont know how to define global const to manage it

CONST

 const [showSidebar, setShowSidebar] = useState(false);
 const handleSidebarClose = () => setShowSidebar(false);
 const handleSidebarShow = () => setShowSidebar(true);

HEADER.JS

<Button variant="primary" onClick={handleSidebarShow}>Show Meny</Button>

SIDEBAR.JS

<Offcanvas show={showSidebar} onHide={handleSidebarClose}>        
    <Offcanvas.Body>
      Some text as placeholder. In real life you can have the elements you
      have chosen. Like, text, images, lists, etc.
    </Offcanvas.Body>
  </Offcanvas>

Where should i place these consts and make them global?


Solution

  • You have to put the state, that is needed by several other components above them. This is called "lifting the state". Then hand over the state or/and your functions to the components below via props. For example:

    • Put state in App.js
    • Import Header and Sidebar in App.js
    • Give Header and Sidebar appropriate properties showSidebar, handleSidebarClose , handleSidebarShow

    Please look into following sandbox for a working example: https://codesandbox.io/s/vigilant-mopsa-5f6us9