Özenç B.
Özenç B.

Reputation: 1038

Render prop as a component to prevent change in the order of hooks

I am wrapping every routed page in a top level component but the passed in page is a function (for reasons I cannot export components as is) so, in order to render them, I have to call their functions directly like so:

const RoutePageContainer = ({ title, page }) => {
  return (
    <div className={styles.container}>
      {title && <h3 className={styles.title}>{title}</h3>}
      <div className={styles.page}>{page()}</div>
    </div>
  );
};

This worked up until some point but now I am getting Warning: React has detected a change in the order of Hooks errors, which I believe is caused by this function call here, so I am trying to fix it.

Kent C. Dodds's blog post describes the problem and how to fix it but I am not sure how I can render this page prop as a JSX element because it is dynamic. Passing it as a children prop also won't work. Is there any way to handle this?

Upvotes: 0

Views: 39

Answers (1)

&#214;zen&#231; B.
&#214;zen&#231; B.

Reputation: 1038

Creating an element with React.createElement seems to be doing the trick.

const RoutePageContainer = ({ title, page }) => {
  const Page = React.createElement(page, null, null);

  return (
    <div className={styles.container}>
      {title && <h3 className={styles.title}>{title}</h3>}
      <div className={styles.page}>{Page}</div>
    </div>
  );
};

Upvotes: 0

Related Questions