2
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.

TIMEX
  • 259,804
  • 351
  • 777
  • 1,080

3 Answers3

2

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>
        );
    }
}
jas7457
  • 1,712
  • 13
  • 21
1

You can use Auxiliary component. It is a higher order component. Auxiliary element is something that does not have semantic purpose but exist for the purpose of grouping elements, styling, etc. Just create a component named Aux.js and put this on it:

const aux = ( props ) => props.children;

export default aux;

Then wrap withAuth with Aux.

const withAuth = (component) => {
     return ( 
           <Aux> 
               <AuthRequired>{ component }</AuthRequired>
           </Aux> 
      );
}
Ömürcan Cengiz
  • 2,085
  • 3
  • 22
  • 28
0

As I know, you cannot return a function as children in React. How about you trying this?

const LoggedInView = <div>You are logged in!</div>;

This code works when I tried on my laptop.

Please, take a look at this link: Functions are not valid as a React child. This may happen if you return a Component instead of from render

Misol Goh
  • 813
  • 6
  • 9