0

I have a bunch of functional react UI components. I want to set defaultProps to those components. However, it seems that my components do not apply those default props. Here is an example code:

// @flow
import React from 'react'
import classNames from 'classnames/bind'

type LabelType = 'default' | 'narrow' | 'wide'

const Label = (
  props: {
    text: string,
    type: LabelType,
  }
) => {
  const { text, type } = props
  const labelClass = classNames(
    'c-label',
    `c-label--${type}`
  )

  return (
    <div className={labelClass}>
      {text}
    </div>
  )
}

Label.defaultProps = {
  type: 'narrow',
}

export default Label

The result that I get is CSS class c-label--undefined. If I pass default values during object destructuring, const { type = 'narrow' } it works fine. The above code works also when I convert functional component to a class-based component.

I have researched this issue a lot but I haven't been able to find a solution. Of course, I could pass the default values during destructuring but it is harder to read and my company would like to adopt the pattern that I have described. I've seen some articles describing that it is possible to pass defaultProps to functional components but perhaps that has changed? I would appreciate any suggestions.

2 Answers2

1

I'm pretty sure your code should work. Just checked it out on my own. type has the default value if not passed as a prop. Maybe the issue is from where you're using the component?

Daniel Andrei
  • 2,654
  • 15
  • 16
0

OK, so after some research it appears that defaultProps do not work in this setting because of react on rails. We use that for server side rendering. Hopefully this will be helpful to those who might be in a similar situation