React Render Prop
In React, a render prop is a function prop that a component uses to know what to render. It allows a component to share its internal state with a child component, without exposing its implementation details.
Here is an example of a component using a render prop:
import * as React from "react";
class MyComponent extends React.Component {
state = {
count: 0,
};
handleClick = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return this.props.render({
count: this.state.count,
handleClick: this.handleClick,
});
}
}
In the example above, the MyComponent
component has a state
and a handleClick
method. It also has a render
prop that receives an object with the component’s state
and handleClick
method. The render
prop is then used to render the component’s internal state.
To use the MyComponent
component, you would pass a function as the render
prop, like this:
<MyComponent
render={({ count, handleClick }) => (
<div>
<p>Count: {count}</p>
<button onClick={handleClick}>Increment</button>
</div>
)}
/>
In the example above, the MyComponent
component is rendered using the render
prop. The render
prop function receives the component’s state
and handleClick
method as arguments, and it returns a React element that displays the component’s count
and a button that can be clicked to increment the count.
Using render props can help you create more flexible and reusable components. It allows you to share state and behavior with a child component, without exposing its implementation details.