I'm currently trying to add a side navbar slide in and out feature for my responsive site. I'm following the first animated example here.
I was able to get it working first with document.getElementById("mySidenav").style.width = "250px";
. However, I would prefer not manipulating the DOM using document
. I would like to be using local state and updating that. I am using JavaScript inline styling. Here is what some of the code looks like working:
openNavbar = () => {
document.getElementById("mySidenav").style.width = "0";
};
<div style={styles.navbarMobile} onClick={this.openNavbar}>
<NavSidebar/>
</div>
navbarMobile: {
height: '100vh',
width: '100%',
position: 'fixed',
zIndex: 11,
top: '0',
left: '-100%',
overflowX: 'hidden',
overflowY: 'hidden',
transition: '1s',
paddingRight: '15px',
display: 'none',
'@media (max-width: 992px)': {
display: 'block',
backgroundColor: 'white'
}
}
Now obviously I'm doing this a little different than the example. Rather than manipulating the width, I am manipulating the left position. It works and runs smoothly. However, I am now trying to implement some local state and changing the CSS according to the local state value. Here is what I have:
this.state = {
navOpen: false
}
openNavbar = () => {
this.setState({navOpen: true});
};
<div style={this.state.navOpen ? {left: 0} : {left: -100%}, styles.navbarMobile} onClick={this.openNavbar}>
<NavSidebar/>
</div>
navbarMobile: {
height: '100vh',
width: '100%',
position: 'fixed',
zIndex: 11,
top: '0',
left: '-100%',
overflowX: 'hidden',
overflowY: 'hidden',
transition: '1s',
paddingRight: '15px',
display: 'none',
'@media (max-width: 992px)': {
display: 'block',
backgroundColor: 'white'
}
}
The main focus is on how to pass the ternary while also adding the other inline styling. By doing what I have above, all the css in navbarMobile
gets applied. However, the ternary never runs. If I remove the styles.navbarMobile
then the ternary works. Is there a way that I can run these two together? Any examples or ideas on how I should handle this?