I'd like my code to update the variable "currentPage" across file functions (App.js and startMenu.js). Currently I can do so with states using only App.js, but would like to simplify my code such that I can use other *.js files in the directory. Right now startMenu.js is calling from App.js in the form of App.toMainMenu and App.toLevelBuilder, but it is not updating the state variable, "currentPage" onClick like I'd like it to.
App.js:
import React, {useState} from "react";
import startMenu from "./startMenu";
import levelBuilder from "./levelBuilder";
function App(){
const[currentPage, setPage] = useState("start")
function toMainMenu(){
setPage(prevPage => "main")
}
function toLevelBuilder(){
setPage(prevPage => "levels")
}
function renderSwitch(param) {
switch(param) {
case 'levels':
return levelBuilder();
default:
return startMenu();
}
}
return (
<div >
<span>{currentPage}</span>
{renderSwitch(currentPage)}
</div>
)
}
export default App;
startMenu.js
import React, {useState} from "react";
import levelBuilder from "./levelBuilder";
import App from "./App";
function startMenu() {
return(
<div className="container">
{/* start menu */}
<img id = "scan_logo"src={process.env.PUBLIC_URL + '/scanlogo.png'} />
<button id="menuStart" onClick={App.toMainMenu}> START </button>
<button id="menuLevel" onClick={App.toLevelBuilder}> LEVEL BUILDER </button>
</div>
)
}
export default startMenu;
I was thinking I need to use props but as a React.js beginner, this confuses me slightly. Any ideas would be greatly appreciated!
Thanks!
If I understood correctly, you have two pages, the Main Menu, and the Level Builder, and you want to switch which one is beeing rendered, right? The best way to do this is by using the library react-router-dom, to create routes in your app, you can find more about it here.
But, if you really want to use the plain react state to do this, you can pass the function setPage()
as props to the other two components, and call it from them. This should work too.