React: How do i make a hidden page, that is only accessible from a login screen, when the username and password is correct?

Viewed 731

I am making a personal website, with a blog in react. I got a Compose.jsx, where i have a wysiwyg editor, for making a new blog post. I am the only one who needs access, and its just a small project, so i just want to make a simple if-statement to check the username and password.

My problem is: how do i make a "hidden route" that i can only access through my Login.jsx, using an if statement?

Right now i have all my routes arranged like this:

function App() {
  return (
    <Router>
      <Route exact path="/" component={Homepage}/>
      <Route exact path="/blog" component={Blog}/>
      <Route exact path="/Cv" component={Cv}/>
      <Route exact path="/portfolio" component={Portfolio}/>
      <Route exact path="/compose" component={Compose}/>
      <Route exact path="/posts/:title" component={ShowPost}/>
      <Route exact path="/login" component={Login}/>
    </Router>
  )
}

And i would like my login page to handle it like this:

  function handleClick(e) {
    e.preventDefault();

    if(login.username === "username" && login.password === "password") {
      props.history.push("/Compose");
    }
  }

What is the easiest way to "hide" the route to compose.jsx, so i can't just access it with www.website.com/compose?

1 Answers

You can render routes conditionally

function App() {
  return (
    <Router>
      <Route exact path="/" component={Homepage}/>
      <Route exact path="/blog" component={Blog}/>
      <Route exact path="/Cv" component={Cv}/>
      <Route exact path="/portfolio" component={Portfolio}/>
      {login.username === "username" && login.password === "password" && (
        <Route exact path="/compose" component={Compose}/>
      )}
      <Route exact path="/posts/:title" component={ShowPost}/>
      <Route exact path="/login" component={Login}/>
    </Router>
  )
}
Related