Skip to content

Instantly share code, notes, and snippets.

@seveibar
Last active March 23, 2022 04:25
Show Gist options
  • Save seveibar/707601b935ddaa2214bf5c98d9601d55 to your computer and use it in GitHub Desktop.
Save seveibar/707601b935ddaa2214bf5c98d9601d55 to your computer and use it in GitHub Desktop.
React Override Link onClick for all Hyperlink Elements
// @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