1

I have a project in react/typescript. I have a react router that looks like this

const Root = () => (
    <>
      <NavBar/>
      <Router>
        <Route path="/" component={Home} />
          <Route path="/timer" component={TimerPage} />
      </Router>
    </>
);

And I have a material-ui appbar that looks like this

export default function NavBar() {
  return (
      <div>
        <AppBar position="static">
          <Tabs>
              <Tab label="Timer" to="/timer" component={TimerPage}  />
          </Tabs>
        </AppBar>
      </div>
  );
}

There are a few issues - first the 'to' in Tab doesn't compile. Secondly, how do I make these two components work together, given they do very similar things?

1

2 Answers 2

0

If you are trying to navigate to another page, wrap your tab component, let react-router handle with the navigation and navigate using react-router history,

 <Tabs value={value} onChange={handleChange} aria-label="simple tabs 
     example">
   <div onClick={() => history.push("/timer")}>
        <Tab   label="Timer" />
    </div>
  </Tabs>
Sign up to request clarification or add additional context in comments.

Comments

0
<Router>
        <Route path="/" component={Home} />
        <Route path="/timer" component={TimerPage} />
</Router>

Route should be inside Switch. Also, if you write path="/" this means that whatever page you will visit will still go to "home" page. This is because react-router does something like "least" checking of routes. So, if you had defined path "/images", before "/images/1", both will route you to "/images". Instead you could change the order of these paths, or add exact keyword before the first one.

Take a look at example below.

<Router>
    <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/timer" component={TimerPage} />
    </Switch>
</Router>

or

<Router>
    <Switch>
        <Route path="/timer" component={TimerPage} />
        <Route path="/" component={Home} />
    </Switch>
</Router>

As for your second issue, you should put your AppBar (or div or any container) inside Router and assign Link to component property of Tab:

<Router>
    <AppBar position="static">
          <Tabs>
              <Tab label="Timer" to="/timer" component={Link}  />
          </Tabs>
    </AppBar>
</Router>

Keep in mind that Link component is imported from react-router and not from @mui.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.