DEV Community

Discussion on: Sharing Context with React Portals

Collapse
 
ghost profile image
Ghost

Hi Michael, thanks for share, I'm doing an idea and your tutorial helped me a lot.

But implementing I had one problem, I don't know if it was because of the version of react or react-dom, to fix, I needed to change one piece of the code in file main.jsx

From:

/* main.jsx */

const Main = () => {
  const ComponentA = ReactDOM.createPortal(
    <CoolComponent />,
    document.getElementById('banner'),
  );

  const ComponentB = ReactDOM.createPortal(
    <SuperCoolComponent />,
    document.getElementById('footer'),
  );

  return (
    <ImportantValueProvider>
      <ComponentA />
      <ComponentB />
    </ImportantValueProvider>
  );
};
Enter fullscreen mode Exit fullscreen mode

For:

/* main.jsx */

function Main() {
  function ComponentA() {
    return ReactDOM.createPortal(
      <CoolComponent />,
      document.getElementById('banner'),
    );
  }

  function ComponentB() {
    return ReactDOM.createPortal(
      <SuperCoolComponent />,
      document.getElementById('footer'),
    );
  }

  return (
    <ImportantValueProvider>
      <ComponentA />
      <ComponentB />
    </ImportantValueProvider>
  );
}
Enter fullscreen mode Exit fullscreen mode

For some reason, when I use constants instead of functions in my setup (react and react-dom: 16.8.6) , react throw this error:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

Check the render method of `Main`.
Enter fullscreen mode Exit fullscreen mode

If someone else get the same error/problem, the solution above may will work =]

Cheers o/

Collapse
 
mickmister profile image
Michael Kochell • Edited

You're right, never trust the internet!

Thanks for the kind words!

Edit: Added the functions so it works now