1

I'm rendering my only component from App.js like so:

export default class App extends React.Component {

constructor(props) {
super(props);
this.state = {gameState: "Menu"};
}

render() {
  return (
    <div>
      {<MenuCanvas/> && this.state === {gameState: "Menu"}}
    </div>
  )
 }
}

and the Menu component looks like this

export default class MenuCanvas extends React.Component {

constructor(props) {
  super(props);
}

render() {

  return (
    <div>
      <canvas id="menu-canvas" width="800" height="800"></canvas>
    </div>
  )
}

componentDidUpdate() {
  startMenuLogic();
}
}

startMenuLogic() function, that is called in componentDidMount is a javascript function that currently only finds the canvas that's being rendered

canvas = document.getElementById('menu-canvas');

the problem is that the canvas is null, even though the function is called in componentDidMount, and the weird part is that the canvas was not null, until I added conditional rendering with state in the App.js. Before that my App.js simple returned always, and everything was fine. What could be the problem and how could I fix this?

3
  • 3
    this.state === {gameState: "Menu"} is going to return false, as when you compare objects in JS they compare memory allocation space, not equality the way you are thinking about it. What you want is this.state.gameState === "Menu" Commented Jan 22, 2020 at 20:32
  • 2
    Exactly, it will never be true since you are creating a new object in the condition which means the references will not match. Commented Jan 22, 2020 at 20:32
  • I just noticed that and fixed it. Two of the answers bellow helped with the question problem. Commented Jan 22, 2020 at 20:41

2 Answers 2

2

Your conditional rendering logic is wrong. The condition should be before the component:

      {this.state === {gameState: "Menu"} && <MenuCanvas/>}

So that if the condition is false, then <MenuCanvas/> isn't evaluated. That's the way short circuit evaluation works:

true && expression returns expression, false && expression returns false.

Even then, as some comments have suggested already, the way you're comparing objects is not recommended since only references are compared. So your condition should be this.state.gameState === "Menu".

Sign up to request clarification or add additional context in comments.

Comments

1

I think you mistaken the sides:

{this.state.gameState === "Menu" && <MenuCanvas/>}

Comments

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.