Skip to content

Better implementation of render props #1241

@chochihim

Description

@chochihim

This page https://reactjs.org/docs/render-props.html introduces the "render props" pattern with a class Mouse. Its implementation is

render() {
  return (
    <div>
      <h1>Move the mouse around! 1</h1>
      <Mouse render={mouse => <Cat mouse={mouse} />} />
    </div>
  );
}

And its usage is

<Mouse render={mouse => <Cat mouse={mouse} />} />

I find that if we implement it as

render() {
  const { render: Render } = this.props;

  return (
    <div
      style={{ height: 100, border: "1px solid" }}
      onMouseMove={this.handleMouseMove}
    >
      <Render mouse={this.state} />
    </div>
  );
}

Then we can allow the following usage patterns:

<Mouse render={({ mouse }) => <Cat mouse={mouse} />} /> // the original Cat class, 1st pattern

<Mouse render={MediumCat} /> // MediumCat is a function component, 2nd pattern

<Mouse render={BigCat} /> // BigCat is a class component, 3rd pattern

With this implementation, we have a pattern (the first one) which is almost the same as the original render props. Also it allows another two usage patterns (actually the 1st and 2nd patterns are the same).

I have created a codesandbox demo. In the demo, MouseTracker1 is the same as documented while MouseTracker2 is different in implementation of Mouse as I suggested.

I wonder if this is a better implementation of "render props". Any thought?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions