
Render Props in React
In React we have Parent and Child components. The Render prop is a technique in React JS which is used for sharing code between react components using props whose value is a function. React Child components takes render props(properties) as a function and calls it instead of implementing its own render logic. We are passing a function from the parent components to the child components as a render props, and the child components calls that function instead of implementing its own logic.
Example for Render props :
import React from "react"; class App extends React.Component { render() { return ( <div> <h1>Render Props Example</h1> <SampleRenderProps /> </div> ); } } // Child component getting render props class RenderPropsComponent extends React.Component { render() { return ( <div> <h2>I am Child Component</h2> {this.props.render()} </div> ); } } // Parent component sending render props to the child class SampleRenderProps extends React.Component { render() { return ( <RenderPropsComponent // Passing render props to the child component render={() => { return ( <div> <h3>I am coming from render props</h3> </div> ); }} /> ); } } export default App;
In the above example we are creating two components that is parent and child component inside the App component. Here in the app component we are calling <SampleRenderProps/> which is the parent component,This parent component is returning the child component in its render method and passing {this.props.render()] Through which we are able to use child properties in parent component and both the parent & child properties in App component. Render props in react is used in class components for communicating data between components.
Output