DEV Community

Sivantha Paranavithana
Sivantha Paranavithana

Posted on • Updated on

Render props in React

In the previous articles, we discussed what is stateful logic sharing, why do we need it and one of the popular solution for that, HOCs.

In this articles let's take a look at another popular solution for the stateful logic sharing.

For the explanation I will use the same example that I have used in the previous articles.

In that examples we had three separate components before applying HOCs, with some duplicated stateful logic inside them. I will mention them here as well for the ease of reference.

If we take a closer look at these components, we can see that the only thing that are different from each other is the render method (And the name of the component obviously 😅).

So what if we just created a single component and pass what to render to that component as a prop?

That's exactly what we are going to do.

We can create a component called Counter and put the sharable stateful logic inside of it. And instead of rendering specific content we are going to render the content dynamically.

For that, we can use the render prop.

The render prop is, is an ordinary prop like any other whose value is a function. This function is responsible of rendering the dynamic content. And we can pass whatever information we need to share to that function as arguments.

Let's see that in code.

In below Counter component you can see that we just execute the render prop inside the render method. Also, we are passing the count and the increment handler as arguments to the this.props.render() function.

Then we can create a Button counter using the Counter component as below

const newButtonCounter = <Counter render={(count, increment) => <ButtonCounter count={count} increment={increment} />} />;
Enter fullscreen mode Exit fullscreen mode

If we extract out the function inside the render prop...

(count, increment) => <ButtonCounter count={count} increment={increment} />
Enter fullscreen mode Exit fullscreen mode

Here you can see that the argument which were passed to the function inside the render prop, are passed again to the ButtonCounter as props. Then we can use them inside the ButtonCounter as below.

import React, { Component } from "react";

export class ButtonCounter extends Component {
  render() {
    const { count, increment } = this.props;
    return <button onClick={increment}>Clicked {count} times!</button>;
  }
}

export default ButtonCounter;

Enter fullscreen mode Exit fullscreen mode

In this way we don't have to write the stateful logic inside the ButtonCounter.

Likewise, we can create InputCounter and HoverCounter or any other component we want by this technique and not duplicate the stateful logic.

Top comments (0)