Using propTypes and defaultProps for a styled-component

5.8k views Asked by At

The following styled-component throws an error:

const StyledButton = styled.button`
  font-weight: 400;
  vertical-align: middle;
  text-align: center;
  text-decoration: none;
  white-space: nowrap;
  margin-right: 0.2rem;
  outline: 0;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  -webkit-appearance: none;
`

const { oneOf, bool } = PropTypes

// button has no md size
StyledButton.propTypes = {
  /** enable block styling on the button */
  block: bool,
  /** size variant for the button */
  size: oneOf(['lg', 'sm', 'md']),
  /** style variant for the button */
  style: oneOf(['primary', 'grey', 'darkgrey', 'link', 'danger'])
}

StyledButton.defaultProps = {
  size: 'md',
  style: 'primary'
}

ERROR

Error: The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX. This DOM node was rendered by `styled.button`.
    at invariant (invariant.js?7313:44)
    at assertValidProps (ReactDOMComponent.js?922a:152)
    at ReactDOMComponent.mountComponent (ReactDOMComponent.js?922a:452)
    at Object.mountComponent (ReactReconciler.js?c56c:45)
    at ReactCompositeComponentWrapper.performInitialMount (ReactCompositeComponent.js?063f:370)
    at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js?063f:257)
    at Object.mountComponent (ReactReconciler.js?c56c:45)
    at ReactCompositeComponentWrapper.performInitialMount (ReactCompositeComponent.js?063f:370)
    at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js?063f:257)
    at Object.mountComponent (ReactReconciler.js?c56c:45)

WORKING VERSION

It was able to render a button of some sort when I commented out the propTypes and defaultProps for the component.

https://www.webpackbin.com/bins/-KsrPX89Zi6MnRw9X11E

This requires that every styled component need an additional component to use take advantage of prop-types. Is there a mechanism or an alternative API that allows me to work with styled-components without wrapping it in an additional component.

1

There are 1 answers

1
RIYAJ KHAN On BEST ANSWER

Error: The style prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX. This DOM node was rendered by styled.button.

StyledButton.defaultProps = {
  size: 'md',
  style: 'primary' //is the wrong way.
}

Its should be

StyledButton.defaultProps = {
  size: 'md',
  style: { color : 'red'} //e.g.
}

style property always eexpect object with {key : value} where key is the css property and value is the any valid css values for those keys

e.g.

style : {
  border: '1px solid red',
  font-size: 12px,
}