skip to Main Content

I guess the question is not clear enough. I want to create two buttons, Home and Log In, that when Log In is clicked, it redirects and loads the content in another JavaScript file. The problem is the web does shows it is redirected, but the content is not loaded.
Here is my App() function in App.js.

function App() {
  let LoggedIn = false;
  const setLogInState = (state) =>{
    LoggedIn = state;
    if(state){
      window.location = "Home.js";
    }else{
      window.location = "App.js";
    }
  }

  const displayMain = () => {
    window.location = "App.js";
  }

  return (
    <div className="App">
      <Navbar logIn = {LoggedIn} setLogInState = {setLogInState} displayMain = {displayMain}/>
    </div>
)};

And here is my Navbar.js.

const Navbar = ({logIn, setLogInState, displayMain}) => {

    return ( 
        <nav className="navbar">
            <h1>Main Page</h1>
            <div className="links">
                <button onClick={displayMain}>Home</button>
                <button onClick={() => setLogInState(true)}>Log In</button>
            </div>
        </nav>
     );
}

What should I write so that the function does load?

2

Answers


  1. This isn’t how you handle routing in React. Assuming the redirect does load the file, the application will no longer run because App.js is the root of the application.

    Use the React Router instead.

    Login or Signup to reply.
  2. you must use some routing library for React since theres dymanic routing in react instead of opening an external file.
    then use Link or useNavigate hook to navigate between pages.

    <Link to="home">
      <button>Home</button>
    </Link>
    

    as for props part use some global state manager like redux etc. to access state across different pages or simply create a state in parent component which i guess is app.js where you define your routes.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search