1

I'm trying to create a "higher-order" function in React that performs some permissions-based checks on the wrapped component and returns it accordingly.

MyComponent.js

...

export default Permissions(MyComponent)

Permissions.js

export default function Permissions(Component) {

  class NewComponent extends React.Component {

     // ... perform checks here

    render() {

      return {validPermissions && <Component />}

    }
  }
}

However, I'd like to be able to use this Permissions as a React Component (as opposed to a function that wraps the component export).

It would looks similar to this:

<Permissions>
    <MyComponent />
</Permissions>

When I run React.Component.isPrototypeOf(Component.children) I get false in these instances. My inclination is to think that the solution is to use some React or ReactDOM method to transform the React Element into a React Component, and then perform the same checks.

How can I transform a React Element into a React Component?


Update:

I gave the bit about permissions as context, but not looking for help with regard to implementing permissions.

I am basically looking for the opposite of React.createElement(MyComponent).

1 Answer 1

1

You can use a functional component, which combines the best of both worlds: it's simple (just a function!) and at the same time it's a proper stateless React component.

const Permissions = ({ granted, children }) =>
    granted ? React.Children.only(children) : null;

Usage:

<Permissions granted={true}>
    <MyComponent />
</Permissions>
Sign up to request clarification or add additional context in comments.

2 Comments

This is helpful, but doesn't allow me to transform the React Element to a React Component class...
I'm not sure if I understand this part of the question. Would you be able to show some example code, what do you need the "transformed" component for? What is the use case?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.