Graduate Program KB

React Render Props

  • Design pattern used to share code between components. Passing a function as a prop from a parent to a child Then the child can call to render the components
  • Example
    //Child
    const Counter = ({render}) => {
        const [count,setCount] = useState(0);
        const increment = () => {
            setCount(count +1)
        };

        return (
            <div>
                {render({count,increment})}
            </div>
        );
    }

    //Parent
    function App() => {
        return (
            <div>
            <Counter render={({count,increment})=>(
                <body>Count: {count}</body>
                <button onClick={increment}>+</button>
            </div>
        )}/>
        );
    }