React Way To Open A Navbar Onclick On A Button
I trying to find a way to open the navbar of ReactJS app when i'm clicking on my 'MENU' button. At the beginning my nav component have a width of 0px (with overflow : hidden). When
Solution 1:
To achieve something like that you have to set this logic in the common parent of both component (here App for the example).
App will manage a state to determine if the Nav is open or not. The state is called isMenuOpen and can be changed using the setIsMenuOpen() function. We will give to the children Nav the state isMenuOpen and to the children TopBar a callback from the function setIsMenuOpen():
App.jsx
importReactfrom"react";
importTopBarfrom"./TopBar";
importNavfrom"./Nav";
exportdefaultfunctionApp() {
const [isMenuOpen, setIsMenuOpen] = React.useState(false);
return (
<divclassName="App"><TopBarsetMenuStatus={setIsMenuOpen} /><NavisOpen={isMenuOpen} /></div>
);
}
Then the TopBar have to set the value of isMenuOpen to true using the function setIsMenuOpen() from the props.
TopBar.jsx
importReactfrom"react";
exportdefaultfunctionTopbar({ setMenuStatus }) {
return (
<divclassName="topbar__container"><divclassName="topbar__menuButton"><buttontype="button"onClick={() => {
setMenuStatus(true);
}}
>
Menu
</button></div></div>
);
}
Then the component Nav will set a specific class (here .open) if isOpen coming from props is true.
Nav.jsx
importReactfrom"react";
import"./styles.css";
exportdefaultfunctionNav({ isOpen }) {
return (
<divid="nav"className={isOpen ? "open" : ""}>
Menu
</div>
);
}
styles.css
#nav {
display: none;
}
#nav.open {
height: 400px;
display: inline-block;
}
You can try this example in this codesandbox.
Solution 2:
importReact, {useState} from"react";
import"./styles.css";
exportdefaultfunctionApp() {
const [toggle, setToggle]= React.useState(false)
const [width, setWidth]= React.useState('')
constshowMenu = () => {
setToggle(!toggle)
if(toggle === true) {
setWidth('50px')
}else {
setWidth('500px')
}
}
return (
<divclassName="App"><buttononClick={showMenu}>Menu</button><divstyle={{width,border:'1pxsolidred'}}><li>text</li><li>text</li><li>text</li><li>text</li></div></div>
);
}
Post a Comment for "React Way To Open A Navbar Onclick On A Button"