Skip to main content

Render Props in Component Composition (Live Playground)

Render props is a powerful technique in React for sharing reusable behavior between components. In this pattern, a component accepts a function as a prop, called the render prop, and invokes it to render the child components. This approach allows for more flexibility when composing components and can help keep your codebase clean and modular. In this tutorial, we'll demonstrate how to use render props in a React application.

Render Props Example

Let's consider a simple example where we have a MouseTracker component that tracks the mouse position and we want to display the position using two different components, DisplayA and DisplayB.

First, let's create the MouseTracker component that uses a render prop to display the mouse position:

JavaScript
import React, { useState } from 'react';

function MouseTracker(props) {
const [position, setPosition] = useState({ x: 0, y: 0 });

function handleMouseMove(event) {
setPosition({ x: event.clientX, y: event.clientY });
}

return (
<div style={{ height: '100%' }} onMouseMove={handleMouseMove}>
{props.render(position)}
</div>
);
}

Now, let's create the DisplayA and DisplayB components to display the mouse position in different ways:

JavaScript
function DisplayA(props) {
return (
<div>
<h1>Display A</h1>
<p>
The mouse position is ({props.position.x}, {props.position.y})
</p>
</div>
);
}

function DisplayB(props) {
return (
<div>
<h1>Display B</h1>
<p>
X: {props.position.x}, Y: {props.position.y}
</p>
</div>
);
}

Now we can use the MouseTracker component with both DisplayA and DisplayB:

JavaScript
import React from 'react';
import MouseTracker from './MouseTracker';
import { DisplayA, DisplayB } from './DisplayComponents';

function App() {
return (
<div>
<MouseTracker render={position => <DisplayA position={position} />} />
<MouseTracker render={position => <DisplayB position={position} />} />
</div>
);
}

export default App;

In this example, the MouseTracker component accepts a render prop, which is a function that takes the position object as an argument and returns the component to be rendered. By using render props, we can easily share the mouse tracking behavior between different components, keeping our code clean and modular.

Live Playground, Try it Yourself

Conclusion

Render props is a powerful technique for sharing reusable behavior between components in React applications. In this tutorial, we demonstrated how to use render props to share mouse tracking behavior between two different display components. As your application grows in complexity, this technique will become even more valuable in keeping your codebase organized and maintainable.