Created
April 4, 2019 16:09
LinkContainer from React Router Bootstrap
This file contains 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
import React, { Component } from 'react' | |
import { Route, withRouter } from 'react-router-dom' | |
const isModifiedEvent = event => !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey) | |
type LinkContainerProps = { | |
history: { | |
push: (...args: any[]) => any, | |
replace: (...args: any[]) => any, | |
createHref: (...args: any[]) => any | |
}, | |
location?: object, | |
match?: object, | |
staticContext?: object, | |
onClick?: (...args: any[]) => any, | |
replace?: boolean, | |
to: string | object, | |
exact?: boolean, | |
strict?: boolean, | |
className?: string, | |
activeClassName?: string, | |
style?: object, | |
activeStyle?: object, | |
isActive?: (...args: any[]) => any | |
} | |
export class LinkContainer extends Component<LinkContainerProps, {}> { | |
handleClick = event => { | |
const { children, onClick } = this.props | |
if (children.props.onClick) { | |
children.props.onClick(event) | |
} | |
if (onClick) { | |
onClick(event) | |
} | |
if ( | |
!event.defaultPrevented && // onClick prevented default | |
event.button === 0 && // ignore right clicks | |
!isModifiedEvent(event) // ignore clicks with modifier keys | |
) { | |
event.preventDefault() | |
const { replace, to, history } = this.props | |
if (replace) { | |
history.replace(to) | |
} else { | |
history.push(to) | |
} | |
} | |
} | |
render() { | |
const { | |
history, | |
location: _location, // eslint-disable-line no-unused-vars | |
match: _match, // eslint-disable-line no-unused-vars | |
staticContext: _staticContext, // eslint-disable-line no-unused-vars | |
children, | |
replace, // eslint-disable-line no-unused-vars | |
to, | |
exact, | |
strict, | |
activeClassName, | |
className, | |
activeStyle, | |
style, | |
isActive: getIsActive, | |
...props | |
} = this.props | |
const href = history.createHref(typeof to === 'string' ? { pathname: to } : to) | |
const child = React.Children.only(children) | |
return ( | |
<Route | |
path={typeof to === 'object' ? to.pathname : to} | |
exact={exact} | |
strict={strict} | |
children={({ location, match }) => { | |
const isActive = !!(getIsActive ? getIsActive(match, location) : match) | |
return React.cloneElement(child, { | |
...props, | |
className: [className, child.props.className, isActive ? activeClassName : null].join(' ').trim(), | |
style: isActive ? { ...style, ...activeStyle } : style, | |
href, | |
onClick: this.handleClick | |
}) | |
}} | |
/> | |
) | |
} | |
} | |
export default withRouter(LinkContainer) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment