ReactJS Program to Measure Width With LayoutEffect with Explanation
ReactJS
Hard
Hooks & Effects
26 views
1 min read
88 words
This problem helps you practice core ReactJS fundamentals in a practical way. It builds intuition around measure, width, after. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Measure an element width after layout and show it on the UI.
Input Format
No input.
Output Format
Render a React component.
Constraints
Use useLayoutEffect to measure after DOM updates.
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
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>
);
}
Output Example
No sample I/O is provided for this question.
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Solution Guide
Problem
Measure an element width after layout and show it on the UI.
Input / Output
Output
Render a React component.
Constraints
Use useLayoutEffect to measure after DOM updates.
Details
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
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!