React render props
Created By: chatGPT
In React, render props is a pattern for sharing code between components using a prop whose value is a function. It's a convenient technique for abstracting stateful logic and can lead to more reusable components. Here's how it works:
First, let's create a simple
In the MouseTracker
component that tracks the mouse's position. It will use the render props pattern to allow other components to access mouse position data.class MouseTracker extends React.Component {
constructor(props) {
super(props);
this.state = {
x: 0,
y: 0,
};
}
handleMouseMove = (event) => {
this.setState({
x: event.clientX,
y: event.clientY,
});
};
componentDidMount() {
window.addEventListener('mousemove', this.handleMouseMove);
}
componentWillUnmount() {
window.removeEventListener('mousemove', this.handleMouseMove);
}
render() {
return this.props.render(this.state);
}
}
MouseTracker
, we define a function handleMouseMove
that updates the state whenever the mouse moves. The render
method calls the render
prop, passing the mouse's current position as an argument. Now, let's use this component elsewhere.Next, we create another component,
In the MousePosition
, that uses MouseTracker
to render the mouse coordinates:const MousePosition = () => (
<MouseTracker render={({ x, y }) => (
<div>
<h1>Mouse Position:</h1>
<p>X: {x}</p>
<p>Y: {y}</p>
</div>
)} />
);
MousePosition
component, we are invoking MouseTracker
and passing in a function that receives the mouse coordinates as an argument. This function returns JSX that displays the coordinates on the screen.Finally, we need to render the
With this setup, as you move your mouse across the window, the MousePosition
component in our application:const App = () => (
<div style={{ height: '100vh', textAlign: 'center', paddingTop: '20%' }}>
<MousePosition />
</div>
);
ReactDOM.render(<App />, document.getElementById('root'));
MousePosition
component will update and display the current x and y coordinates, demonstrating the render props pattern effectively. This approach promotes code reusability and separates the concerns of rendering and state management.