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.

3
  • Did you read the answers here? stackoverflow.com/questions/23314806/… Commented Jul 25, 2017 at 8:23
  • I cannot see how it is a possible duplicate. They are not trying to set default values the way I do and it is TypeScript Commented Jul 25, 2017 at 10:21
  • Yea, sorry. Didn't see that //@flow comment. Commented Jul 25, 2017 at 11:26

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

2 Comments

Very interesting. The application I am working on is rendered from the server (RoR). As we are migrating from backbone to react, we initiate our components in erb templates. That could be a problem, I guess
Ok, apparently it has to do with react_on_rails that we use for server side rendering.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.