Reputation: 35
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;
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;
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
Upvotes: 1
Views: 247
Reputation: 2695
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;
Upvotes: 1