HOC for Styling

Sometimes there are isolated UI components that only require a minimal amount of state for interaction, and using them as standalone components is sufficient

eg. Interactions in a Carousel

The HOC will have a current slide index and have previous and next methods.

// Higher order component
import React from 'react'
// This could be named something more generic like Counter or Cycle
const CarouselContainer = (Comp) => {
  class Carousel extends React.Component {
    constructor() {
      super();
      this.state = {
        index: 0
      };
      this.previous = () => {
        const { index } = this.state;
        if (index > 0) {
          this.setState({index: index - 1})
        }
      };

      this.next = () => {
        const { index } = this.state;
        this.setState({index: index + 1})
      }
    }

    render() {
      return (
        <Comp
          {...this.props}
          {...this.state}
          previous={this.previous}
          next={this.next}/>
      )
    }
  }
  return Carousel
};
export default CarouselContainer;

Using the HOC

By keeping the styling separate from the interactive state, any number of carousel variations can be created from these reusable parts.

Usage

Last updated

Was this helpful?