reactjsreact-nativehigher-order-components

How do I wrap this child in an Higher Order Component?


const LoggedInView = (props) => <Text>You are logged in!</Text>
export default withAuth(LoggedInView)


const withAuth = (component) => <AuthRequired>{ component }</AuthRequired>


const AuthRequired = (props) => {
    const context = useContext(AuthContext)
    if(!context.auth){
        return (
            <View style={styles.container}>
               <Text>You need to login . Click here</Text>
            </View>
        )
    }
    return props.children 
}

My <AuthRequired> view works fine, but my withAuth does not.


Solution

  • HOCs take a component and return another component. You're taking a component and returning a React node, not a component. Docs reference

    In your case, you should be able to do something like:

    const withAuth = (Component) => (props) => <AuthRequired><Component ...props /></AuthRequired>
    

    It might be easier to understand as:

    function withAuth(Component) {
        return function WithAuthHOC(props) {
            return (
                <AuthRequired>
                    <Component ...props />
                </AuthRequired>
            );
        }
    }