57

I'm building a React app that has links pointing to predefined routes.

<a href="/my/react/route/">Click Here</a>

The routes resolve fine, but it's refreshing the page, thereby slowing down app performance. How do I avoid re-rendering the entire page?

1

5 Answers 5

83

Fix the problem by using the <Link> tag included with react-router.

import React from "react";
import { Link } from 'react-router-dom';

export class ToolTip extends React.Component {
  render() {
    return (
      <Link to="/My/Route">Click Here</Link>
    )
  }
};
4
  • Does this hold true for static site generation as well?
    – Sam
    Sep 30, 2016 at 18:19
  • How about NavItem href in react-bootstrap? <Nav bsStyle="tabs"> <NavItem href="/plan"> </NavItem> </Nav>
    – Hamid
    Aug 23, 2017 at 4:46
  • NavItem acts like a <a href..> so it will reload the page Aug 30, 2017 at 10:50
  • 6
    Does this mean using a href is discouraged altogether for a React SPA, and always replace with link when making basic links? e.g. a href causes full reload in all cases?
    – blamb
    Mar 10, 2018 at 22:46
5

You need to:

import { Link } from "react-router-dom"

then import the component you wish to go to

import Example from "./component/Example"

Then use Link like this

<Link to="/Example">
   <h4>Example Page</h4>
</Link>

This will stop the refreshing.

Note that, if to="/Example" matches a route you've specified in your BrowserRouter and then it sends you there.

Learn more here Reat Training / React Router

4

First answer was correct but I didn't found Link from react-router-dom. It was in my case here:

import { Link } from 'react-router';
2
  • 9
    Different versions of react-router: version 4: import { Link } from react-router-dom version 3 or before: import { Link } from react-router
    – Nicolas
    Sep 6, 2017 at 22:58
  • it is not available in earlier version but with version 4 and above you can do this import { Link } from 'react-router-dom' Mar 25, 2019 at 18:55
1

Hi semantic ui react example

             <Menu.Item name="NotFound" as={NavLink} to="/dadsadsa" />
2
  • 1
    This is the correct answer if using React-Bootstrap Nav.Link. Import NavLink from react-router-dom. Change href to to and add the as property: <Nav.Link to={"/admin/account/" + business.id} as={NavLink}>Account</Nav.Link>
    – mcarson
    Oct 20, 2021 at 19:58
  • Hi @mcarson your answer is correct thank you Oct 20, 2021 at 20:20
0

In case the above methods don't work, check if you are importing the right component where you are defining the routes. (In my case, I imported a component with the same name but from a wrong path)

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.