Jim Peeters
Jim Peeters

Reputation: 2863

How to use a element with href property in combination with react-router?

I want to use the navigation.push(url) functionality when clicking on an anchor tag element so that the app doesn't refresh by navigating to another page, and I can keep the application state.

The reason why I want to use this on an anchor tag element instead of a button is:

When trying to use the combination as seen in the code below it still navigates towards a new page causing the webapp to refresh:

import React from 'react';
import { useHistory } from 'react-router-dom';

const TestComp = () => {
  const navigation = useHistory();
  return (
    <a
      onClick={() => {
        navigation.push(`/test`);
      }}
      href={`/test`}>
      this is a link
    </a>
  );
};

export default TestComp;

Upvotes: 2

Views: 1853

Answers (2)

Hans Murangaza DRCongo
Hans Murangaza DRCongo

Reputation: 860

By using event.preventDefault() it prevents the browser to execute the norma function of a event (click)... On anchor tag, it prevents the browser from navigating to another page, so that you can do it manually

<a
      onClick={(e) => {
        e.preventDefault()
        navigation.push(`/test`);
      }}
      href={`/test`}>
      this is a link
    </a>

Upvotes: 0

Drew Reese
Drew Reese

Reputation: 203466

Use the Link component from react-router-dom. It renders an anchor tag to the DOM and does all the linking/navigation for you that you are trying to do manually, and it doesn't reload the page.

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

const TestComp = () => {
  return (
    <Link to="/test">
      this is a link
    </Link>
  );
};

export default TestComp;

Upvotes: 2

Related Questions