Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Router is refreshing page when I follow a route using <a> tag

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?

like image 551
Rick Avatar asked Nov 27 '15 20:11

Rick


People also ask

How do I stop my page from refreshing in react?

Use the preventDefault() method on the event object to prevent a page refresh on form submit in React, e.g. event. preventDefault() . The preventDefault method prevents the browser from issuing the default action which in the case of a form submission is to refresh the page.

Does react router reload the page?

react-router-dom allows us to navigate through different pages on our app with/without refreshing the entire component. By default, BrowserRouter in react-router-dom will not refresh the entire page.

What to set to true in BrowserRouter so that the router will use full page refreshes on page navigation?

forceRefresh: bool If true, the Router will use full-page refreshes on-page navigation.

How does my router detect route change react?

To detect route change with React Router, we can use the useLocation hook. import { useEffect } from "react"; import { useLocation } from "react-router-dom"; const SomeComponent = () => { const location = useLocation(); useEffect(() => { console.


4 Answers

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>
    )
  }
};
like image 168
Rick Avatar answered Oct 04 '22 16:10

Rick


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';
like image 32
Janne Harju Avatar answered Oct 04 '22 15:10

Janne Harju


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

like image 36
Edwin Avatar answered Oct 04 '22 17:10

Edwin


Hi semantic ui react example

             <Menu.Item name="NotFound" as={NavLink} to="/dadsadsa" />
like image 31
tayfun Kılıç Avatar answered Oct 04 '22 17:10

tayfun Kılıç