Skip to content

Higher Order Component Tips #19

@pwmckenna

Description

@pwmckenna

Here's an example Higher Order Component that just returns a component that renders the original component with some additional styling.

HoCs/style.js

import { Component } from 'react';
import hoistNonReactStatic from 'hoist-non-react-statics';

export default style => DumbComponent => {
    class Container extends Component {
        render() {
            return <DumbComponent style={style}/>;
        }
    }
    Container.displayName = 'Styled' + (DumbComponent.displayName || DumbComponent.name);
    hoistNonReactStatic(Container, DumbComponent);
    return Container;
};

index.js

import style from './HoCs/style';

const makeBold = style({ fontWeight: 'bold' });
// by making the HoC "Component-last and curried by default"
// we can create these reusable functions that can be applied over and over
const BoldBlogPost = makeBold(BlogPost);
const BoldHeader = makeBold(Header);

// BoldBlogPost.displayName === 'StyledBlogPost'
// BolderHeader.displayName === 'StyledHeader'

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions