Table of contents
1.
Introduction
2.
What are Render props?
3.
Implementation of Render Props
4.
Naive Implementation
4.1.
App.js
4.2.
Counter1.js
4.3.
Counter2.js
4.4.
Output
5.
Better implementation using the render props
5.1.
App.js
5.2.
Wrapper.js
5.3.
Counter1.js
5.4.
Counter2.js
5.5.
Output
6.
Frequently Asked Questions (FAQS)
7.
Key Takeaways
Last Updated: Mar 27, 2024

Render Props in React

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Do you know why React is the most popular language for front-end developers?

React is a component-based language, meaning we can have different components coming together to display a webpage. 

This component-based architecture allows us to reuse our code in different components with the help of render props in react.

That is the reason why lazy developers love React. In this article we will be discussing how to render props in react in detail.

Now let us get into the concept of rendering props in react.

 

Shocked GIF by The Tonight Show Starring Jimmy Fallon


Click on the following link to read further: Hooks in React JS

What are Render props?

Render props in react is a technique that allows us to share code between react components.  

A component with a render prop takes a function as an argument which returns a react component. This function is called to render the component instead of implementing its render logic.

Consider two components, namely component1 and component2. These two components need to use the same functionalities/state. 

Right now, These components have duplicate code.

How to reduce code duplicity?

We can use render props in react having a wrapper component which calls the implementation of Component1 and Component2 using a function in the prop.

As shown in the figure above, The wrapper class has the state/functionality needed by Component1 and Component2, and these are taken from Wrapper using render props.

Further, we will discuss the implementation of render props.

Implementation of Render Props

Okay, Let’s go slowly,

There are mainly two parts in the definition of render props:

  1. Prop whose value is a function
  2. Sharing code

To demonstrate the above two steps, we will implement a react app with two counter buttons. When we click on the button, it will display the number of times it has been clicked. 

The implementation will have to maintain a state variable for storing the count of how many times a button is clicked, and also, we will create a function to increment the count variable.

 

Firstly, we will see the naive implementation, and then we will see the improvements and optimizations done with render props in react.

Naive Implementation

App.js

In App.js, we separately use the Counter1 and Counter2 components to get the functionality of buttons as shown above.

 

import React from 'react';

import './App.css';

import Counter1 from './components/Counter1';

import Counter2 from './components/Counter2';

function App() {

  return (

    <div style={{textAlign:"center"}}>

      <h1>Render Props in React</h1>

 

      <Counter1/>

      <Counter2/>

 

    </div>

  );

}

 

export default App;

 

Counter1.js

 

We define a separate state of the Counter1 button, and it includes the state variable count and the increment count function in it. 

 

import React, { Componentfrom 'react'

export class Counter1 extends Component {

   state = {count:0}

 incrementCount = () => {

        this.setState({

            countthis.state.count + 1

        })

    }

  render() {

        return (

            <div>

                <button style={{color"red"fontSize:"40px"}} onClick={this.incrementCount}>

                    Clicked {this.state.count} times

                </button>

            </div>

        )

    }

}

export default Counter1

 

Counter2.js

 

Similar to the implementation done in the Counter1.js, The component, Counter2 also has its state variable count and the function incrementCount in it.

 

import React, { Componentfrom 'react'

export class Counter2 extends Component {

 state = {count:0}

 incrementCount = () => {

        this.setState({

            countthis.state.count + 1

        })

    }

  render() {

        return (

            <div>

                <button style={{color"blue"fontSize:"40px"}} onClick={this.incrementCount}>

                    Clicked {this.state.count} times

                </button>

            </div>

        )

    }

}

export default Counter2

 

Output

 

[video-to-gif output image]

 

In the naive implementation, we can observe that the code is getting repeated in Counter1.js and Counter2.js. This is not desirable and leads to a large amount of code in our codebase. This also leads to complications.

 

Now, we will look at the better version of implementation that uses render props in react.

Better implementation using the render props

App.js

 

Firstly, we use the wrapper class component from having a render prop that has a function with two parameters, namely the current state “count” and the incrementCount part. This technique is known as the render props in react.

 

import React from 'react';

import './App.css';

import Wrapper from './components/Wrapper';

import Counter1 from './components/Counter1';

import Counter2 from './components/Counter2';

function App() {

  return (

    <div style={{textAlign:"center"}}>

      <h1>Render Props in React</h1>

      <Wrapper render={(countincrementCount)=>{

        return <Counter1 count={count} incrementCount={incrementCount}/>

      }}/>

       <br />

       <Wrapper render={(countincrementCount)=>{

        return <Counter2 count={count} incrementCount={incrementCount}/>

      }}/>

   </div>

  );

}

export default App;

 

Wrapper.js

The parameters count and the function incrementCount are implemented in the Wrapper component. This component basically includes the duplicate code that is to be supplied to both counter1 and counter2 components.

 

We initialize the state of the count variable in this component to zero. And the incrementCount function takes the current state count variable and increments it precisely that by 1.

 

After that, these two are passed as the parameter into the render parameter present in the props of Wrapper defined in App.js. Since there is a function in the render props, we call that function to pass on these variables into App.js, and from there it is further passed onto counter1 and counter2 components. 

 

import React, { Componentfrom 'react'

export class wrapper extends Component {

  state = {count:0}

    incrementCount = () => {

        this.setState({

            countthis.state.count + 1

        })

    }

render() {

        return (

            <div style={{textAlign"center"}}>

                {this.props.render(this.state.count,this.incrementCount)}

            </div>

        )

    }

}

export default wrapper

 

Counter1.js

The state variable count and the function incrementCount those received in the props of Counter1 from the render props used in the App.js. 

We simply embed these props received in the button to display it.

 

import React from 'react';

const Counter1 = (props=> (

    <button style={{color"red"fontSize:"40px"}} onClick={props.incrementCount}>

        Clicked {props.count} times

    </button>

);

export default Counter1;

 

Counter2.js

Similar to Counter1.js, we also simply embed these variables into the button to display them.

 

import React from 'react';

const Counter2 = (props=> (

    <button style={{color"blue"fontSize:"40px"}} onClick={props.incrementCount}>

        Clicked {props.count} times

    </button>

);

export default Counter2;

 

Output

 

[video-to-gif output image]

Frequently Asked Questions (FAQS)

  1. What are render props?

Render props are the components with a prop that takes a function as an argument that returns a react component.

2. Why do we need Render props in react?

“Render props” is a technique used to allow code sharing among components; this helps in code reusability in react.

3 .What is a wrapper component?

The wrapper component is used to include the render logic of duplicate code in different components. Then this component contains all the state/functionality required by various components with similar code. 

Key Takeaways

We learned how the technique of render props in react helps us avoid DRY (Don’t Repeat Yourself) code. You will always find this technique handy in your next big project. Some of the points that you could keep in mind are about render props in react:

  • Render prop is a function prop.
  • It is used for sharing code among components.
  • A component uses it to know what is to be rendered and displayed.
  • It makes it possible to promote code reusability among the components.

Apart from this, you can also expand your knowledge by referring to these articles on Javascript and React.

Check out this problem - Duplicate Subtree In Binary Tree

For more information about the react framework for frontend development get into the exclusive Frontend web development course.

Live masterclass