2

I'm struggling with what I'm sure is the basics of React Router. I have an overall App.js file, and a child react functional component, Navbar.js. I want my Switch to be in App.js, but Navbar.js to have Links to my different pages.

The questions I looked at previously dealing with nesting talked about nested routes, but I don't think that is my case here. Do I need to declare a new route in the Navbar component? I'm a little confused as to why I can't just have the link component on its own in Navbar, or just push the page I want to history.

2 Answers 2

1

Okay, So you just need to import what we call as a Link from react-router-dom.
And then you can use Link as an "anchor" tag

import {Link} from 'react-router-dom'
 <nav>
      <ul>
        <li>
          <Link to="/">Home</Link>
        </li>
        <li>
          <Link to="/about">About</Link>
        </li>
        <li>
          <Link to="/users">Users</Link>
        </li>
      </ul>
    </nav>
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! Is there a benefit to using <Li nk to=> tags instead of pushing it onto history, history.push('/some/path')?
@BigSteve history.push('/some/path') is meant to navigate pragmatically, like after completing an API request, link is meant to be used for a button just meant to navigate.
0

In App.js you can have the switch

<BrowserRouter>
    <Switch>
        <Route path="/" component={Home}/>
        <Route path="/contact-us" component={ContactUs}/>
        ....
    </Switch>
</BrowserRouter>

And in the Navbar.js you can have the navigation

<div>
    <Link to="/">Home</Link>
    <Link to="/contact-us">Contact us</Link>
    .....
</div>

6 Comments

Thank you! And the entirety of App.js should be wrapped in a BrowserRouter?
The routes need to be wrapped in a BrowserRouter (see my updated answer)
Does the <routes> tag need to encompass the child component holding the <link> tags?
@BigSteve No, both the <route> and <link> elements need to be inside the <BrowserRouter> element.
Do so the <route> and <link> could be inside the <BrowserRouter> through the composition of components? Like could the <route> and <link> components be in a component thats a child component of a component with the <BrowserRouter> tag?
|

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.