Measure Width With LayoutEffect
ReactJS
Hard
7 views
Problem Description
Measure an element width after layout and show it on the UI.
Output Format
Render a React component.
Constraints
Use useLayoutEffect to measure after DOM updates.
Official Solution
import React, { useLayoutEffect, useRef, useState } from 'react';
export default function App() {
const boxRef = useRef(null);
const [width, setWidth] = useState(0);
useLayoutEffect(() => {
function measure() {
const el = boxRef.current;
if (!el) return;
const rect = el.getBoundingClientRect();
setWidth(Math.round(rect.width));
}
measure();
window.addEventListener('resize', measure);
return () => window.removeEventListener('resize', measure);
}, []);
return (
<div style={{ padding: 16, width: 560 }}>
<h2 style={{ marginTop: 0 }}>meetcode measure</h2>
<div ref={boxRef} style={{ border: '1px solid #eee', borderRadius: 16, padding: 16, width: 'min(100%, 420px)' }}>
Resize the window
</div>
<div style={{ marginTop: 10, color: '#555' }}>Width: {width}px</div>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!