Gastby - ReactDOM: Target container is not a DOM element

Viewed 289

I'm trying to Use Conditional Rendering using the example from Reactjs.org in a Gastby project to render a reusable component based on a condition

my end goal here would be to render my component differently whether i'm in landscape or portrait but i'd like to understand why it's not working even for basic conditions

I'm stuck at the very first step of the React example with the error ReactDOM: Target container is not a DOM element, here is the code for the component i'm trying to create

import React from "react";
import ReactDOM from "react-dom";


function PortaitMode(props) {
  return <h1>It's in LandscapeMode</h1>;
}

function LandscapeMode(props) {
  return <h1>It's in PortraitMode</h1>;
}

export default function MyComponent(props) {
  const isInPortait = props.isInPortait;
  if (isInPortait) {
    return <PortaitMode />;
  }
  return <LandscapeMode />;
}

ReactDOM.render(
  // Try changing to isLoggedIn={true}:
  <MyComponent isInPortait={false} />,
  document.getElementById("root")
);

I've tried to put <div id="root"></div> in my index.html or even change document.getElementById("root") with document.getElementById("___gatsby") but it worked oddly showing the h1 tag on my page by just importing myComponent into the other .js file without even using it ...

If someone could help it would be great ! : )

1 Answers

Use it like this:

import React from "react";

function PortaitMode(props) {
  return <h1>It's in LandscapeMode</h1>;
}

function LandscapeMode(props) {
  return <h1>It's in PortraitMode</h1>;
}

export default function MyComponent(props) { 
  const isInPortait = props.isInPortait;

  if (isInPortait) {
    return <PortaitMode />;
  }
  return <LandscapeMode />;
}

Then, in another page/component, you can:

import MyComponent from 'your/component/path'

const IndexPage = () =>{

return <main><MyComponent isInPortait={false} /></main>

}

export default IndexPage

If your IndexPage is inside /pages/index.js you will see your component depending on the isInPortait prop.


P.S: you can save the following line:

const isInPortait = props.isInPortait;

By adding a destructuring props in the component declaration like:

function portaitMode() {
  return <h1>It's in LandscapeMode</h1>;
}

function landscapeMode() {
  return <h1>It's in PortraitMode</h1>;
}

export default function MyComponent({isInPortait}) {     
  if (isInPortait) {
    return portaitMode();
  }
  return landscapeMode();
}

Note: in addition, the components are not doing anything with the props so you can avoid passing it.

You can even make it shorter, but it's completely up to you:

export default function MyComponent({isInPortait}) {  
    return isInPortait ? portaitMode() : landscapeMode();
}
Related