I have some default props that depends on other prop. As this.props
doesn't exists inside getDefaultProps()
I wonder if using getInitialState()
and states is the better way of doing it.
https://facebook.github.io/react/tips/props-in-getInitialState-as-anti-pattern.html
Is there a better approach?
Button = React.createFactory React.createClass
getInitialState: ->
className = undefined
iconClass = undefined
label = undefined
switch @props.type
when 'save'
className = 'btn-primary'
iconClass = 'glyphicon glyphicon-floppy-disk'
label = I18n.t('crud.save')
when 'save_next'
className = 'btn-success'
iconClass = 'glyphicon glyphicon-floppy-saved'
label = I18n.t('crud.save_new')
when 'cancel'
className = 'btn-danger'
iconClass = 'fa fa-stop'
label = I18n.t('crud.cancel')
else
className = 'btn-default'
className: className
iconClass: iconClass || ''
label: label || ''
propTypes:
onClick: React.PropTypes.func.isRequired
type: React.PropTypes.oneOf(['button', 'save', 'save_next', 'cancel'])
className: React.PropTypes.string
title: React.PropTypes.string
name: React.PropTypes.string
iconClass: React.PropTypes.string
label: React.PropTypes.string
size: React.PropTypes.oneOf(['xs', 'sm', 'md', 'lg'])
disabled: React.PropTypes.bool
submit: React.PropTypes.bool
getDefaultProps: ->
disabled: false
className: ''
label: ''
size: 'sm'
submit: false
render: ->
React.DOM.button
className: "btn btn-#{@props.size} #{@props.className} #{@state.className}",
onClick: @props.onClick(),
type: @state.domType
title: @props.title,
name: @props.name,
disabled: @props.disabled,
React.DOM.span className: "#{@props.iconClass} #{@state.iconClass}"
' '
@props.label || @state.label
What are default props in React? Default props can be used to define any props that you want to be set for a component, whether or not a value is actually passed in from the parent component.
Default Prop Values Since ES2022 you can also declare defaultProps as static property within a React component class. For more information, see the class public static fields. This modern syntax will require a compilation step to work within older browsers.
For example, let's create a CustomButton class in React that takes color as a prop. To set a default value for the color prop, use the defaultProps property of CustomButton to set the default value of color to blue .
You May Not Need defaultProps As per this tweet, defaultProps will eventually be deprecated. You can check the discussions here: Original tweet.
I'm afraid no.
getDefaultProps
function is called before component instance is created.
It's meant that you can't have access to this
reference from this place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With