Open In App

React.js Render Props

The Render Props is a  technique in ReactJS for sharing code between React components using a prop whose value is a function. Child component takes render props as a function and calls it instead of implementing its own render logic. In brief, we pass a function from the parent component to the child component as a render props, and the child component calls that function instead of implementing its own logic.

Creating React Application And Installing Module:



Step 1: Create a React application using the following command:

npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command:



cd foldername

Project Structure: It will look like the following.

Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.




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;

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:


Article Tags :