Website Links

Friday 12 April 2019

React/React Native - Higher Order Components

Higher order components is probably one of my favourite patterns that I have come across for React/React Native. It is when you pass a component to a function and it returns the component with additional functionality. This is very useful for code reuse. You may have seen this used before with the connect function provided by redux. I typically use this for auto login if a user were to navigate to a login/register page e.g.

  import React, { Component } from 'react'
  import { connect } from 'react-redux'
  import { setCurrentUser } from '../actions/index'
  import { bindActionCreators } from 'redux'

  export const withAutoLogin = (Scene) => {
    // New component that wraps our existing component and adds
    // additional functionality
    class WithAutoLogin extends Component {

      constructor(props) {
        super(props);

        // If there is a current user, navigate to home page
        if (this.props.currentUser) {
          ...  
        }
      }

      render() {
        return (
          // apply props to component
          <Scene {...this.props} />
        );
      }
    }

    // Connecting to redux
    function mapStateToProps(state) {
      return {
        currentUser: state.currentUser
      }
    }

    function mapDispatchToProps(dispatch) {
      return bindActionCreators({
        setCurrentUser: setCurrentUser
      }, dispatch);
    }

    return connect(mapStateToProps, 
                   mapDispatchToProps)(WithAutoLogin);
  }

No comments:

Post a Comment