React
Render Props
Render props pattern.
By EZ4Code Team
reactrender-props
Code
import { useState, useEffect } from 'react';
// Mouse position tracking
function MouseTracker({ render }) {
const [pos, setPos] = useState({ x: 0, y: 0 });
const handleMove = (e) => {
setPos({ x: e.clientX, y: e.clientY });
};
return (
<div onMouseMove={handleMove} style={{ height: '100vh' }}>
{render(pos)}
</div>
);
}
// Usage
function App() {
return (
<MouseTracker
render={({ x, y }) => (
<h1>Mouse at ({x}, {y})</h1>
)}
/>
);
}
// children as render prop
function DataFetcher({ url, children }) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch(url)
.then(res => res.json())
.then(data => { setData(data); setLoading(false); });
}, [url]);
return children({ data, loading });
}
// Usage
function UserList() {
return (
<DataFetcher url="/api/users">
{({ data, loading }) => {
if (loading) return <div>Loading...</div>;
return data.map(u => <div key={u.id}>{u.name}</div>);
}}
</DataFetcher>
);
}
// Toggle component
function Toggle({ children }) {
const [on, setOn] = useState(false);
const toggle = () => setOn(!on);
return children({ on, toggle });
}
// Usage
<Toggle>
{({ on, toggle }) => (
<button onClick={toggle}>{on ? 'ON' : 'OFF'}</button>
)}
</Toggle>Explanation
Render Props shares rendering logic via function properties; children can also be used as a render prop.
More React Snippets
Controlled Form with Validation
Build a controlled React form with inline validation and error messages.
Event Handling and List Rendering
Handle events and render dynamic lists with keys in React.
useState
State management Hook.
useEffect
Side-effect Hook.
useContext
Shared state via context.
useReducer
Complex state management.