Home > OS >  React: Conditional rendering of functional components using state | is not a function error
React: Conditional rendering of functional components using state | is not a function error

Time:11-20

Hi so i am trying to conditionally render one of three aspects of a one page game and i am stuck at one of the first hurdles.

import React, { useState } from "react";

function App() {
  const [currentPage, setCurrentPage] = useState("Intro");


  if (currentPage === "Intro") {
    return (
      <div className="App">
        <Intro setCurrentPage={setCurrentPage} />
      </div>
    );
  }
  if (currentPage === "GameContainer") {
    return (
      <div>
        <GameContainer  setCurrentPage={setCurrentPage} />
      </div>
    );
  }
  if (currentPage === "EndGame") {
    return (
      <div>
        <EndGame  setCurrentPage={setCurrentPage} />
      </div>
    );
  }
}

export default App;
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

This renders the component fine but there is a button which i have hooked up to an on click function in the intro component which i am hoping would change the state and hence the render.

import React from "react";

function Intro(setCurrentPage) {
  function startGame() {
     setCurrentPage("GameContainer");
  }

  return (
    <div className="intro">

      <div class="hoverButton">
        <button class="startButton" onClick={startGame} alt="start game">
          Start Game!
        </button>
      </div>
      <p id="footNote">written using react.js</p>
    </div>
  );
}

export default Intro;
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

I get the error "setCurrentPage is not a function".

I know the resources are out there but i just can't figure out how to achieve what I am aiming for or understand where I am going wrong?

Any advice appreciated, thank you

CodePudding user response:

You are destructuring the prop setCurrentPage incorrectly in Intro. You should add curly braces when destructuring the prop directly, in your case, {setCurrentPage}.

Try updating it as :

import React from "react";

function Intro({setCurrentPage}) {
  function startGame() {
     setCurrentPage("GameContainer");
  }

  return (
    <div className="intro">

      <div class="hoverButton">
        <button class="startButton" onClick={startGame} alt="start game">
          Start Game!
        </button>
      </div>
      <p id="footNote">written using react.js</p>
    </div>
  );
}

export default Intro;
  • Related