0.0.7 • Published 6 years ago

render-hoc v0.0.7

Weekly downloads
5
License
MIT
Repository
github
Last release
6 years ago

render-hoc

Higher-order components with render prop flexibility.

npm version code style: prettier CircleCI

Introduction

Higher-order components (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 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:

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:

import { makeHoc } from 'render-hoc';

const withComments = makeHoc(WithComments);

Which can then be used with a BlogPost component:

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:

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

Or namespaced:

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:

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

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

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

It can also be used to set defaults:

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

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

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.

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:

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:

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:

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);
0.0.7

6 years ago

0.0.6

6 years ago

0.0.5

6 years ago

0.0.4

6 years ago

0.0.3

6 years ago

0.0.2

6 years ago

0.0.1

6 years ago