Open alexkirsz opened 9 years ago
Since styles
is a prop, default stylesheets can be provided via defaultProps
.
class Button extends React.Component {
static defaultProps = {
styles: {
btn: { color: 'red' },
},
};
render() {
return <div {...applyStyles(this.props.styles, 'button')} />;
}
}
Providing a styles
prop will thus override the default stylesheet. However, the format of the styles
prop makes it easy to extend the default stylesheet:
<Button styles={[Button.defaultProps.styles, { btn: { backgroundColor: 'blue' } }]} />
On the consumer side, styling a third-party component with a custom stylesheet is as simple as providing the two to a helper HoC, much like the one I built for react-classmap:
import ThirdPartyButton from 'react-component-lib';
export default provideStyles(ThirdPartyButton, { btn: { color: 'red' } });
provideStyles(Component, styles)
creates a new component that renders
<Component {...this.props} styles={[styles, this.props.styles]} />
Taking example from react-classmap, this proposal can be "polyfilled" in already existing third-party components that don't support it. The className
prop of DOM elements would serve as key(s), and style would be propagated through context.
// ThirdPartyButton::render
return <div className="btn" />;
polyfillProvideStyles(ThirdPartyButton, { btn: { color: 'red' } });
// renders
<div className="btn" style={{ color: 'red' }} />
Instead of having two different props
stylemap
andclassmap
, have a singlestyles
prop that covers both cases.The
styles
prop is designed for inter-compatibility with most existing React styling solutions (react-style, css-loader, etc.).Here's a (very) contrived example to illustrate its use on the component consumer side:
The component author can then consume the
styles
props via a standardapplyStyles(styles, keys[, overrides]) => { className, style }
helper:Here's an example implementation of
applyStyles
, wherekeys
order defines precedence:And here's a very similar implementation where
stylesValues
order defines precedence:TODO: determine which of the two is best.
The
styles
PropType is defined recursively as either astylesMap
or a list ofstyles
where falsy values are ignored.The
stylesMap
PropType is defined as an object that maps keys tostylesValue
.The
stylesValues
PropType is defined recursively as either aString
, an object that maps CSS properties to CSS property values, or a list ofstylesValues
where falsy values are ignored.