# render-hoc

> Convert a component with a render prop into a higher order component

Latest version **0.0.7** (published 2018-04-08) · MIT license · 0 weekly downloads

## Install

```sh
npm install render-hoc
pnpm add render-hoc
yarn add render-hoc
bun add render-hoc
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support; pre 1.0.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 0.0.7 |
| Published | 2018-04-08 |
| First published | 2018-04-06 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 1 |
| Unpacked size | 17.2 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | jrwebdev |
| Maintainers | jrwebdev |

## Links

- npm: https://www.npmjs.com/package/render-hoc
- Repository: https://github.com/jrwebdev/render-hoc
- Homepage: https://github.com/jrwebdev/render-hoc#readme
- Issues: https://github.com/jrwebdev/render-hoc/issues
- npm.io page: https://npm.io/package/render-hoc

## Dependencies (1)

- [utility-types](https://npm.io/package/utility-types.md) ^1.1.0

## Recent versions

- 0.0.7 (latest) — 2018-04-08
- 0.0.6 — 2018-04-07
- 0.0.5 — 2018-04-07
- 0.0.4 — 2018-04-07
- 0.0.3 — 2018-04-07
- 0.0.1 — 2018-04-06

## README

# render-hoc

Higher-order components with render prop flexibility.

[![npm version](https://badge.fury.io/js/render-hoc.svg)](https://badge.fury.io/js/render-hoc)
[![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)
[![CircleCI](https://circleci.com/gh/jrwebdev/render-hoc.svg?style=svg)](https://circleci.com/gh/jrwebdev/render-hoc)

## Introduction

[Higher-order components](https://reactjs.org/docs/higher-order-components.html) (HOCs) are a powerful pattern of reuse in React, but they come with a number of well known issues and pitfalls, such as prop name collisions. The [render prop](https://reactjs.org/docs/render-props.html) pattern fixes a lot of these issues, but comes with its own set of issues, such as not being able to hook prop changes into component lifecycle methods.

This library allows you to support both patterns by converting your render prop component into a higher-order component, giving the consumer the power to choose between the two. It also aims to fix some of the issues associated with higher-order components, aiming to bring them in line with the flexibility offered by render prop components.

render-hoc is built with static types in mind from the outset, allowing higher-order components to be generated without all the complexity of typing them. It currently has first-class support for TypeScript and Flow support may be added in the future.

## Installation

```
npm install render-hoc
```

## How it works

Taking a contrived example of a render prop component that loads comments for a blog post from a server and calls the render prop with the resulting data:

```jsx
class WithComments extends React.Component {
  state = {
    loading: true,
    hasError: false,
    comments: undefined,
  };

  componentDidMount() {
    const { postId, numberOfCommentsToDisplay } = this.props;
    fetch(
      `https://api.myblog.com/${postId}/comments?display=${numberOfCommentsToDisplay}`
    )
      .then(res => res.json())
      .then(
        comments =>
          this.setState({
            comments,
            loading: false,
          }),
        () =>
          this.setState({
            hasError: true,
            loading: false,
          })
      );
  }

  render() {
    this.props.render(this.state);
  }
}
```

A higher-order component can then be easily generated using render-hoc:

```jsx
import { makeHoc } from 'render-hoc';

const withComments = makeHoc(WithComments);
```

Which can then be used with a `BlogPost` component:

```jsx
import withComments from './withComments';
import BlogPost from './components/BlogPost';

const BlogPostWithComments = withComments(BlogPost);
```

### Prop Mappers

By default, the newly generated HOC will pass through all props passed to it to the inner component, which may cause prop collisions or performance issues in some scenarios. This is where prop mappers come in, which aim to give HOCs render prop-like flexibility.

The props injected by the higher order components can be renamed via a `mapInnerProps` function:

```jsx
const const BlogPostWithComments = withComments({
  mapInnerProps: props => ({
    comments: props.comments,
    commentsLoading: props.loading,
    commentsHasError: props.hasError,
  }),
})(BlogPost);
```

Or namespaced:

```jsx
const const BlogPostWithComments = withComments({
  mapInnerProps: ({comments, loading, hasError, ...props})) => ({
    ...props,
    comments: {
      list: comments,
      loading,
      hasError,
    },
  }),
})(BlogPost);
```

You can also strip out props which are not required by the component and pass all others through:

```jsx
const const BlogPostWithComments = withComments({
  mapInnerProps: ({ numberOfCommentsToDisplay, ...props }) => props,
})(BlogPost);
```

`mapOuterProps` can be used to rename the props that are passed to the HOC:

```jsx
const const BlogPostWithComments = withComments({
  mapOuterProps: ({ blogPostId, ...props }) => ({
    ...props,
    postId: blogPostId,
  }),
})(BlogPost);
```

It can also be used to set defaults:

```jsx
const const BlogPostWithComments = withComments({
  mapOuterProps: props => ({
    numberOfCommentsToDisplay: 5,
    ...props,
  }),
})(BlogPost);
```

Or explicitly set the value of a prop and disallow overrides:

```jsx
const const BlogPostWith5Comments = withComments({
  mapOuterProps: props => ({
    ...props,
    numberOfCommentsToDisplay: 5,
  }),
})(BlogPost);
```

## Usage with TypeScript

_Note: render-hoc ships with an `index.d.ts` file so it doesn't require installation of an associated `@types` package._

Render prop and HOC patterns are very similar in the sense that they inject props into a component (`InnerProps`), either via a function (render props), or by passing them to the component directly (HOCs). They also often add their own additional props (`OuterProps`) to the wrapped component. The examples below will build upon the WithComments example above with this idea.

WithComments can be set up by separating out the outer and inner prop types for the component. `RenderProps` is then used to add a render prop function to the component's outer props, setting it up to be called with `WithCommentsInnerProps`.

```ts
import { RenderProps } from 'render-hoc';

interface WithCommentsOuterProps extends RenderProps<WithCommentsInnerProps> {
  postId: string;
  numberOfCommentsToDisplay: number;
}

interface WithCommentsInnerProps {
  comments: string[];
  loading: boolean;
  hasError: boolean;
}

interface WithCommentsState extends WithCommentsInnerProps {}

class WithComments extends React.Component<
  WithCommentsOuterProps,
  WithCommentsState
> {
 ...

 render() {
   return this.props.render(this.state);
 }
}
```

The inner and outer props can then be used to convert the render prop component into a HOC using makeHoc:

```ts
import { makeHoc } from 'render-hoc';

import WithComments, {
  WithCommentsInnerProps,
  WithCommentsOuterProps
} from './WithComments';

const withComments = <
  WithCommentsInnerProps,
  WithCommentsOuterProps
>makeHoc(WithComments);
```

To use the newly created higher-order component without any prop mappers, you simply need to make sure that the component extends the inner props of the render prop component:

```ts
interface BlogPostProps extends WithCommentsInnerProps {
  heading: string;
  text: string;
}

const BlogPost = (props: BlogPostProps) => {
  ...
};

const BlogPostWithComments = withComments(BlogPost);

const blogPost = (
  <BlogPostWithComments
    postId="1"
    numberOfCommentsToDisplay={5}
    heading="heading"
    text="text"
  />
);
```

_Note that in the above example, the WithCommentsOuterProps will also be injected as per the default behaviour of render-hoc, though you will not be able to access them due to the typing. It may only be an issue if you spread the props within the component (e.g. `<input {...props} />`_

If you require more control, you can use `mapInnerProps` and/or `mapOuterProps` and split BlogPost's props into inner and outer props:

```ts
interface BlogPostOuterProps {
  postId: string;
  heading: string;
  text: string;
}

interface BlogPostInnerProps {
  text: string;
  heading: string;
  comments: string[];
  commentsLoading: boolean;
  commentsHasError: boolean;
}

const BlogPostWithComments = withComments<
  BlogPostInnerProps,
  BlogPostOuterProps
>({
  mapOuterProps: props => ({
    postId: props.postId,
    numberOfCommentsToDisplay: 5,
  }),
  mapInnerProps: props => ({
    text: props.text,
    heading: props.heading,
    commentsLoading: props.loading,
    commentsHasError: props.hasError,
    comments: props.comments,
  }),
})(BlogPost);
```

---
_Source: https://npm.io/package/render-hoc · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
