Skip to content

Commit 03c8f0e

Browse files
committed
Document gatsby-link being only for internal links
Add an example of a component which could be used to automatically choose <a> or gatsby-link depending on the destination. Resolves #4662.
1 parent f2b4319 commit 03c8f0e

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

packages/gatsby-link/README.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,3 +93,42 @@ const IndexLayout = ({ children, location }) => {
9393
);
9494
};
9595
```
96+
97+
## For internal links only!
98+
99+
Note that this component is intended only for links to pages handled by Gatsby.
100+
101+
If the `to` prop is on a different domain (such as a full off-site URL) the
102+
behavior is undefined, and the user will likely not be taken to the expected
103+
location.
104+
Links will fail similarly if the `to` prop points somewhere on the same domain
105+
but handled by something other than Gatsby (which may be the case if your server
106+
proxies requests for certain paths to a different application).
107+
108+
Sometimes you won't know ahead of time whether a link will be internal or not,
109+
such as when the data is coming from a CMS.
110+
In these cases you may find it useful to make a component which inspects the
111+
link and renders either with `gatsby-link` or with a regular `<a>` tag
112+
accordingly.
113+
Since deciding whether a link is internal or not depends on the site in
114+
question, you may need to customize the heuristic to your environment, but the
115+
following may be a good starting point:
116+
117+
```jsx
118+
import GatsbyLink from "gatsby-link";
119+
120+
const Link = ({ children, to, ...other }) => {
121+
// Tailor the following test to your environment.
122+
// This example assumes that any internal link (intended for Gatsby)
123+
// will start with exactly one slash, and that anything else is external.
124+
const internal = /^\/(?!\/)/.test(to);
125+
126+
// Use gatsby-link for internal links, and <a> for others
127+
if (internal) {
128+
return <GatsbyLink to={to} {...other}>{children}</GatsbyLink>;
129+
}
130+
return <a href={to} {...other}>{children}</a>;
131+
};
132+
133+
export default Link;
134+
```

0 commit comments

Comments
 (0)