xxxxxxxxxx
if (typeof window !== 'undefined') {
// You now have access to `window`
}
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;