Cold_Class
Cold_Class

Reputation: 3484

What is the difference between the 'href' and 'to' property in the link tag?

While learning React I stumbled upon a property I haven't seen before: "to" on a Link tag.

<Link to="/login" className="btn btn-link">Cancel</Link>

Can't find the docs to this - I guess it's a React specific property because I couldn't find it in the regular docs.

There must be a difference compared to "href" otherwise it shouldn't exist ;)
Can anyone point me in the right direction?

Upvotes: 1

Views: 2408

Answers (4)

Borex
Borex

Reputation: 1

A to prop is typically used for linking to other documents, such as a CSS stylesheet.

Whereas the href prop is used to link to an external page, such as <Link href="https://www.youtube.com"></Link> would take the user to YouTube.

Upvotes: 0

Alex K
Alex K

Reputation: 15828

Since <Link /> is a component from a third-party library, it can have any props it wants and is not limited to the html element props in React's docs.

In this case to is the name of the prop used by React Router to specify where the Link component should "link to" when clicked.

Upvotes: 0

Will Jenkins
Will Jenkins

Reputation: 9787

That's a React Router <Link/>, so it's a bit special. It ties in to the <Router> and <Route> components and is used to navigate around in a Single-Page App. A standard anchor tag (even if it has an href that matches one of your <Route> paths) doesn't interact with React Router, so will cause a full-page reload.

Upvotes: 2

Junius L
Junius L

Reputation: 16122

It's a react router prop for navigation. It can be an object or a string.

to - A string representation of the location to link to, created by concatenating the location’s pathname, search, and hash properties.

to - An object that can have any of the following properties:

  • pathname: A string representing the path to link to.
  • search: A string representation of query parameters.
  • hash: A hash to put in the URL, e.g. #a-hash.
  • state: State to persist to the location.

react router docs

Upvotes: 1

Related Questions