I am trying to access the window object inside of a React.js component as I want to create a state which holds the dynamic innerWidth value of the window object. I was able to make it work when the page gets refreshed but not when I resize the page with the dev tools dynamically.
Here is the code that works for me on refresh:
const About = () => {
const [bioType, setBioType] = useState("");
const truncateText = () =>
window.innerWidth > 1024 ? setBioType("desktop") : setBioType("mobile");
useEffect(() => {
truncateText();
});
return ({
bioType === 'desktop' ? ... : ....
})
}
However, when I resize the web page with Dev Tools, it doesn't work. Could someone give me a hint? Thanks.`
CodePudding user response:
Changing the windows width doesn't cause React to react to the change, and re-render. You need to use an event handler to listen to the resize event, use a ResizeObserver
or use MatchMedia
, and listen to the changes.
Example with MatchMedia
:
const { useState, useEffect } = React;
const MIN_WIDTH = 600;
const getBioType = matches => matches ? 'desktop' : 'mobile';
const About = () => {
const [bioType, setBioType] = useState(() => getBioType(window.innerWidth > MIN_WIDTH));
useEffect(() => {
const mql = window.matchMedia(`(min-width: ${MIN_WIDTH}px)`);
const handler = e => setBioType(getBioType(e.matches));
mql.addEventListener('change', handler);
return () => {
mql.removeEventListener('change', handler);
};
}, []);
return bioType;
}
ReactDOM
.createRoot(root)
.render(<About />);
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div id="root"></div>