"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Render Props in react for functional components

Render Props in react for functional components

Published on 2024-11-07
Browse:874

Render Props in react for functional components

In React, Render Props is a technique used to share logic between components using a function prop. Instead of using children or composition, a function is passed as a prop to render content dynamically. This approach works well with functional components and hooks.

Here’s an example of how to implement Render Props with functional components:

Example

import React, { useState } from 'react';

// The component using render props
const MouseTracker = ({ render }) => {
  const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 });

  const handleMouseMove = (event) => {
    setMousePosition({
      x: event.clientX,
      y: event.clientY,
    });
  };

  return (
    
{render(mousePosition)}
); }; // Component that consumes the render props const App = () => { return (

Mouse Tracker

(

Mouse Position: {x}, {y}

)}/>
); }; export default App;

Explanation:

  • MouseTracker is a functional component that takes a render prop.
  • The render prop is a function that receives the mouse position and returns JSX.
  • The App component passes a function as the render prop, which displays the mouse's x and y coordinates.

This pattern allows for more flexibility in deciding how to render content based on logic inside the MouseTracker component.

Release Statement This article is reproduced at: https://dev.to/imyusufakhtar/render-props-in-react-for-functional-components-2a3k?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3