HOC for Link aka withLink
See original GitHub issueWith the rise of styling libraries like glamorous and styled-components styling component become so much better. But those libraries share a weakness:
If I want to style a third-party component like Link I can do it conveniently but I have to trust that the third-party component knows how to handle className prop passed to it by a styling library.
Styling libraries have no way to know if a third-party component uses className properly, thus fail silently in the case of misuse giving no info whatsoever. That can lead to pretty nasty bugs.
Also Link breaks the container/persentational separation. It both provides some data and displays something on the page.
I’d like to propose adding HOC for Link that would solve this problem.
With withLink I could do this:
import A from '.styledElements/A'
import withLink from 'react-router-dom/withLink'
const MyLink = withLink((props) => <A {...props}/>) // A is a styled component
This gives me 100% certainty that the styles will be applied and also gives me freedom to choose how I want to present links in my app.
The implementation should be straightforward:
// withLink.js is just slightly changed Link.js
const withLink = (Comp) => class Link extends React.Component {
// ... nothing changes here
render() {
const { replace, to, ...props } = this.props // eslint-disable-line no-unused-vars
const onClick = this.handleClick
const href = this.context.router.history.createHref(
typeof to === 'string' ? { pathname: to } : to
)
const passProps = {...props, onClick, href}
return <Comp {...passProps} />
}
}
export default withLink
// Link.js
import React from 'react'
import withLink from './withLink'
export default withLink((props) => <a {...props}/>)
Issue Analytics
- State:
- Created 6 years ago
- Reactions:8
- Comments:21 (10 by maintainers)

Top Related StackOverflow Question
Not every React Router aware component has to live in the
react-router/react-router-dompackages. If you really want this, your best bet is to make your own package. The source is basically just wrapping the existingLink.jscode for thewithLinkfunction.or modifying the
<Link>to take a component prop if you prefer that approach.Maybe toss in a few tests, figure out what to call the package,
npm publishit and you’re good to go.Despites the fact that React is all about composition instead of inheritance, I’ve solved this problem in very few lines of code:
Buttonis a React component which renders a HTML looking like a button if the propshrefis provided. See https://ant.design/components/button/I guess it works with any other component like your styled-component.