-
-
Notifications
You must be signed in to change notification settings - Fork 10.8k
Description
With 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 componentThis 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}/>)