xxxxxxxxxx
import { useEffect, useState } from 'react';
function MyComponent() {
const [windowWidth, setWindowWidth] = useState(null);
useEffect(() => {
// Check if window is defined (i.e., running in the browser)
if (typeof window !== 'undefined') {
// Access window properties here
setWindowWidth(window.innerWidth);
// Add event listener to update window width on resize
const handleResize = () => {
setWindowWidth(window.innerWidth);
};
window.addEventListener('resize', handleResize);
// Clean up the event listener on component unmount
return () => {
window.removeEventListener('resize', handleResize);
};
}
}, []); // Empty dependency array ensures the effect runs only once after initial render
return (
<div>
{windowWidth && <p>Window width: {windowWidth}px</p>}
</div>
);
}
export default MyComponent;
xxxxxxxxxx
if (typeof window !== 'undefined') {
// You now have access to `window`
}
xxxxxxxxxx
var currentUrl = '';
if (typeof window !== 'undefined') {
currentUrl = window.location.href;
}
if (typeof window !== 'undefined') {
window.onload = function afterWebPageLoad() {
setLoading(false);
}
}
setTimeout(function () {
setLoading(false);
}, 30000);
xxxxxxxxxx
global?.window && window.innerHeight
It's important to use the operator ?., otherwise the build command
might crash.