Last active
March 23, 2022 04:25
-
-
Save seveibar/707601b935ddaa2214bf5c98d9601d55 to your computer and use it in GitHub Desktop.
React Override Link onClick for all Hyperlink Elements
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @flow | |
/* | |
Overrides the behavior of <a /> tags for all children. | |
Use it in your App.js to make it easier for your single page web application to route without reloading, e.g. | |
// App.js | |
class App extends Component { | |
render() { | |
return <LinkOverride onClickLink={(url) => { dispatch({type: 'PUSH_ROUTE', url}) }}> | |
<SomeComponent /> | |
</LinkOverride> | |
} | |
} | |
// SomeComponent.js | |
class SomeComponent extends Component { | |
render() { | |
return <div> | |
this tag WILL NOT cause a page reload: | |
<a href="/about">About Page!</a> | |
<br/> | |
this tag WILL cause a page reload: | |
<a href="https://google.com">Google!</a> | |
</div> | |
} | |
} | |
*/ | |
import React, { PureComponent } from 'react' | |
export type Props = { | |
onClickLink: (href: string) => any | |
} | |
const searchUpwardForLink = target => { | |
if (target.tagName === 'A') return target | |
if (target.parentNode) return searchUpwardForLink(target.parentNode) | |
return null | |
} | |
class LinkOverride extends PureComponent<Props> { | |
onClick = (e: any) => { | |
const link = searchUpwardForLink(e.target) | |
if (!link) return | |
const { host, pathname, search } = link | |
if (host === window.location.host) { | |
e.preventDefault() | |
e.stopPropagation() | |
this.props.onClickLink(pathname + search) | |
} | |
} | |
render = () => { | |
const { children } = this.props | |
return <div onClick={this.onClick}>{children}</div> | |
} | |
} | |
export default LinkOverride |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment