Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

External link component: Add a check for on page anchor links #42259

Merged
merged 4 commits into from
Aug 2, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions packages/components/src/external-link/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,22 @@ function UnforwardedExternalLink(
compact( [ ...rel.split( ' ' ), 'external', 'noreferrer', 'noopener' ] )
).join( ' ' );
const classes = classnames( 'components-external-link', className );
/* Anchor links are percieved as external links.
This constant helps check for on page anchor links,
to prevent them from being opened in the editor. */
const shouldPreventDefault = href.startsWith( '#' );
carolinan marked this conversation as resolved.
Show resolved Hide resolved
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we guarantee href is always a String? For example is it possible for it to be undefined? If it is then we should guard here and also coerce to Boolean.

Suggested change
const shouldPreventDefault = href.startsWith( '#' );
const shouldPreventDefault = !! href?.startsWith( '#' );

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not sure how to backtrace it to see if it can be undefined for some reason, so I believe it is easier to add the check :)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Though the type for href is set to string in types.ts. I think @walbo would be able to answer how to best handle the check.


return (
/* eslint-disable react/jsx-no-target-blank */
<a
{ ...additionalProps }
className={ classes }
href={ href }
onClick={
shouldPreventDefault
? ( event ) => event.preventDefault()
: undefined
}
target="_blank"
rel={ optimizedRel }
ref={ ref }
Expand Down