Search code examples
javascriptreactjstypescriptreact-nativereact-hoc

How to wrap a class in a higher order component?


I was wondering if I can wrap a class component inside a hoc that has also a class.

import React, { Component } from "react";
import { View } from "react-native";
import { Toast } from "react-native-easy-toast";
const withToast = EnhancedComponent => {
    return class HOC extends Component {
        render() {
            return (
                <View>
                    <EnhancedComponent {...this.props} toast={(message, duration) => this.toast.show(message, duration)} />
                    <Toast
                        ref={toast => {
                            this.toast = toast;
                        }}
                    />
                </View>
            );
        }
    };
};
export default withToast;

This is the hoc I'm using,and now I'm passing a class component like this:

import React, { Component } from "react";
import withToast from "../../hoc/withToast";
import Btn from "react-native-micro-animated-button";
class Login extends Component<Props> {
render() {
            return <Btn title="Login" onPress={() => this.props.toast("logged in")} />;
        }
    }
export default withToast(Login);

When I run it I get this error:

Invariant Violation: Invariant Violation: Invariant Violation: Element type is invalid: expected a string 
(for built-in components) or a class/function (for composite components) but got: undefined. 
You likely forgot to export your component from the file it's defined in, or you might have 
mixed up default and named imports.
Check the render method of `HOC`

Is it possible somehow?

Thanks!


Solution

  • Figured it out. I was importing import { Toast } from "react-native-easy-toast"; instead of import Toast from "react-native-easy-toast";