reactjs / reactjs/react.dev

Better implementation of render props

Open
#1,241 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
JavaScript
Stars
11.8k
Forks
7.9k
Avg merge
1d 11h
Merged PRs (30d)
11

Description

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?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the render-props page linked in the issue and the accompanying CodeSandbox demo. Compare the documented Mouse implementation with the proposed variant; done means a maintainer decision about whether the documentation should change, plus an agreed scope for any update.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, react
Domain
documentation
Issue type
Documentation
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
20/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.