Window Width Listener
ReactJS
Medium
6 views
Problem Description
Show window width and update it on resize using an effect.
Output Format
Render a React component.
Constraints
Add resize listener and remove it on cleanup.
Official Solution
import React, { useEffect, useState } from 'react';
export default function App() {
const [w, setW] = useState(() => window.innerWidth);
useEffect(() => {
function onResize() {
setW(window.innerWidth);
}
window.addEventListener('resize', onResize);
return () => window.removeEventListener('resize', onResize);
}, []);
return (
<div style={{ padding: 16 }}>
<strong>meetcode responsive</strong>
<div style={{ marginTop: 8, fontSize: 24, fontWeight: 800 }}>{w}px</div>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!