Topic: MDBSideNav isOpen "window is not defined" error with nextjs
Expected behavior Trying to implement MDBPro in nextjs
Actual behavior The first time you add MDBSideNav, it appears on the screen. However, if you clear the cache and load the screen again, an error will occur.
Resources (screenshots, code snippets etc.)
I referenced the "https://mdbootstrap.com/articles/react/materialize-your-next-js-project-with-mdbootstrap-for-react/" document provided by this site and was applying MDBPro.
Here is the layout.js I have made of the document.
import Link from 'next/link';
import { MDBInput, MDBNavbar, MDBNavbarNav, MDBNavItem, MDBNavLink, MDBDropdown, MDBDropdownToggle, MDBDropdownMenu, MDBDropdownItem, MDBIcon, MDBSideNavItem, MDBSideNavCat, MDBSideNavNav, MDBSideNav, MDBContainer, MDBNavbarBrand,MDBNavbarToggler,MDBCollapse,MDBFormInline, } from "mdbreact";
class Layout extends React.Component { constructor(props) { super(props); this.state = { isOpen: false, toggleStateA: false, breakWidth: 1300, windowWidth: 0 }; }
handleResize = () => {}
componentDidMount = () => { this.handleResize() window.addEventListener("resize", this.handleResize) }
componentWillUnmount = () => { window.removeEventListener("resize", this.handleResize) }
handleResize = () => { const windowWidth = window.innerWidth this.setState({windowWidth }) }
toggleCollapse = () => { const isOpen = !this.state.isOpen this.setState({ isOpen }); }
handleToggleClickA = () => { const toggleStateA = !this.state.toggleStateA this.setState({toggleStateA}) }
render = () => { const {windowWidth, breakWidth} = this.state
const navStyle = {
paddingLeft: windowWidth > breakWidth ? "210px" : "16px"
}
const mainStyle = {
margin: "0 6%",
paddingTop: "5.5rem",
paddingLeft: windowWidth > breakWidth ? "240px" : "0"
}
const specialCaseNavbarStyles = {
WebkitBoxOrient: "horizontal",
flexDirection: "row"
}
return (
<React.Fragment>
<div className="fixed-sn light-blue-skin">
<MDBSideNav
logo="https://mdbcdn.b-cdn.net/img/logo/mdb-transparent.png"
breakWidth={this.state.breakWidth}
bg="https://mdbcdn.b-cdn.net/img/Photos/Others/sidenav4.jpg"
mask="strong"
fixed
>
</MDBSideNav>
<main style={mainStyle}>
<MDBContainer fluid style={{ height: 2000 }} className="mt-5">
{this.props.children}
</MDBContainer>
</main>
</div>
</React.Fragment>
);
} }
export default Layout;
Aliaksandr Andrasiuk staff answered 6 years ago
Hi,
If you are using SSR you have no access to window
because all the actions are executed on the server where there is no object window
.
For more information you can read the next article: https://github.com/zeit/next.js/wiki/FAQ
Best regards.
FREE CONSULTATION
Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.
Answered
- User: Free
- Premium support: No
- Technology: MDB React
- MDB Version: 4.12.0
- Device: window
- Browser: chrome
- OS: window 10
- Provided sample code: No
- Provided link: Yes