My first react HOC + Redux component in Typescript

The logic: Show a component only if the user logged in

import React from 'react';
import {connect} from "react-redux";

interface AuthenticatedUserOnlyProps {
    authenticated: boolean
}


function mapStateToProps(state: State) {    
    return {
        authenticated: state.authenticated
    };
}

export function authenticatedUserOnly<T>(WrappedComponent: React.ComponentType<T>) {
    class FinalComponent extends React.Component<AuthenticatedUserOnlyProps > {
        public render() {

            const {authenticated, ...otherProps} = this.props;
            if (authenticated) {
                return <WrappedComponent {...(otherProps as T)}/>
            } else {
                return null;
            }
        }
    };

    return connect(mapStateToProps, null)(FinalComponent);
}

To use it, just

render() {
    const someComponent = authenticatedUserOnly(SomeComponent); 

    return {
        <div>
           {someComponent }
        </div>
    }
}

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.