We already know, how to set a defaultProps.
TestComponent.defaultProps = {
isTest: true
};
But I often used props as object type.
In Parent,
render(){
let sample = {
isTest : true,
isLoggedIn : true
}
return (
<div>
<TestComponent sample = {sample} />
</div>
)
}
In child component, I want to set isLoggedIn
to false
as default. If not set (or not passed from Parent) isLoggedIn
, default value is true
But I don't know how to set defaultProps for object type
TestComponent.defaultProps = {
sample : {
isLoggedIn: false
}
};
How to do this ?
You can use props to send data to a component. Like default values for function arguments, props also have default values. defaultProps can be defined as a property on the component class itself to set the default props for the class. defaultProps is used for undefined props, not for null props.
You can define default props this way: export class Counter extends React. Component { constructor(props) { super(props); this. state = {count: props.
As per this tweet, defaultProps will eventually be deprecated.
React props can be accessed as an object or destructuredOr they can be destructured, since props will always be an object, into separate variables.
Your code
TestComponent.defaultProps = {
sample : {
isLoggedIn: false
}
};
should work.
And for type validation (propTypes), use React.PropTypes.shape
for nested object props like this:
React.PropTypes.shape({
isLoggedIn: React.PropTypes.bool
})
See the document: https://facebook.github.io/react/docs/typechecking-with-proptypes.html#react.proptypes
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