ReactJS Program to Render Props Mini with Explanation
ReactJS
Hard
Component Design
25 views
1 min read
89 words
This problem helps you practice core ReactJS fundamentals in a practical way. It builds intuition around render, prop, component. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Create a component that provides mouse position using a render function prop.
Input Format
No input.
Output Format
Render a React component.
Constraints
Use a function prop named render to output UI.
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
import React, { useState } from 'react';
export function MouseTracker({ render }) {
const [pos, setPos] = useState({ x: 0, y: 0 });
return (
<div
onMouseMove={(e) => setPos({ x: e.clientX, y: e.clientY })}
style={{ height: 160, border: '1px solid #eee', borderRadius: 14, padding: 12 }}
>
{render(pos)}
</div>
);
}
export default function App() {
return (
<MouseTracker
render={({ x, y }) => (
<div>
<strong>meetcode tracker</strong>
<div style={{ color: '#555' }}>x: {x}, y: {y}</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
Create a component that provides mouse position using a render function prop.
Input / Output
Output
Render a React component.
Constraints
Use a function prop named render to output UI.
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, { useState } from 'react';
export function MouseTracker({ render }) {
const [pos, setPos] = useState({ x: 0, y: 0 });
return (
<div
onMouseMove={(e) => setPos({ x: e.clientX, y: e.clientY })}
style={{ height: 160, border: '1px solid #eee', borderRadius: 14, padding: 12 }}
>
{render(pos)}
</div>
);
}
export default function App() {
return (
<MouseTracker
render={({ x, y }) => (
<div>
<strong>meetcode tracker</strong>
<div style={{ color: '#555' }}>x: {x}, y: {y}</div>
</div>
)}
/>
);
}
Solutions (0)
No solutions submitted yet. Be the first!