x89
x89

Reputation: 3460

Button Navigation with React Router

Header: I am trying to navigate to a new page from my Material UI button using the onClick method. I am confused about what to write in my handleClickSignIn function.

Code snippet from my Header.tsx file:

const HatsPage = () => (
  <div>
    <h1>
      HATS PAGEHH
    </h1>
  </div>
)

function handleClickSignIn() {
  <Route component= {HatsPage}></Route>
}

const Header = () => (
  <div className = 'header'>‚
    <h1 className = 'title'>
      Instaride
    </h1>
    <div className="header-right">
      <Button onClick= {handleClickSignIn}> Sign In</Button>
      <Button> Contact</Button>
    </div>
  </div>
);

This doesn't work and I get errors like:

expected assignment or function but got expression instead

Upvotes: 0

Views: 1270

Answers (1)

Sam Gomena
Sam Gomena

Reputation: 1479

The problem you're having it that you're generating a Route component every time the Sign In button is clicked.

Instead, you should use a Link component like so:

const Header = () => (
  <div className = 'header'>‚
  <h1 className = 'title'>
    Instaride</h1>
  <div className="header-right">
    <Link to={"/login"}> Sign In</Link>
    <Button> Contact</Button>
  </div>
</div>

This will create a link component that, when clicked, will direct to the /login URL. To then render components at that URL you'll also need to define a Route. You've already done this with but need to define the path like so:

<Route path={"/login"} component={HatsPage} />

And then note that this Route, your Header component and any Link's need to be nested within an instance of a BrowserRouter.

Upvotes: 1

Related Questions