Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render a HOC in react

I'm trying to render a HOC with react but I cannot figure it out how to make it works. So I have one HOC that is working perfect with react-navigation. My idea is to show a component that the render wraps a HOC. I am trying to do sth like this:

  render() {
    return (
      <View style={viewStyle}>
        {CheckLogin(Login)}
      </View>
    );
  }

this CheckLogin is the HOC and Login is the component itself. The result is that React is not complaining but is in blank. Any idea how to render a HOC invoking the Component itself??

like image 983
Ruffeng Avatar asked Jun 28 '17 20:06

Ruffeng


People also ask

How hoc works in React?

A higher-order component (HOC) is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React's compositional nature. Concretely, a higher-order component is a function that takes a component and returns a new component.

How do you write hoc in functional component in React?

We have created a new component called HOC which returns the <WrappedComponent/> from its render function. While this actually adds no functionality, it depicts the common pattern that every HOC function will follow. We can invoke the HOC as follows: const SimpleHOC = higherOrderComponent(MyComponent);

What is the difference between HOC and render props?

The React community is moving away from HOC (higher order components) in favor of render prop components (RPC). For the most part, HOC and render prop components solve the same problem. However, render prop components provide are gaining popularity because they are more declarative and flexible than an HOC.


1 Answers

You are just calling the HOC as a function inside the JSX, instead you need to use </> in order to render it.

// Apply your HOC
const EnhancedComponent = CheckLogin(Login);

class MyComponent extends Component {
  render() {      
    return (
      <View style={viewStyle}>
        <EnhancedComponent  />
      </View>
    );
  }
}
like image 153
Crysfel Avatar answered Sep 28 '22 03:09

Crysfel