Is it possible to use defaultProps in React Native? I’ve tried the following 2 ways of defining defaultProps and I get null when trying to access the defaultProp
export default class Foo extends Component {
// 1. define defaultProps within Class
static defaultProps = {
someData: 'Hello',
}
constructor(props) {
super(props);
}
componentDidMount() {
console.log(this.props.someData);
}
render() {
return (
<View> {this.props.someData} </View>
)
}
}
// 2. define defaultProps outside Class
Foo.defaultProps = { someData: 'Hello' }
The defaultProps is a React component property that allows you to set default values for the props argument. If the prop property is passed, it will be changed. The defaultProps can be defined as a property on the component class itself, to set the default props for the class.
You May Not Need defaultProps As per this tweet, defaultProps will eventually be deprecated.
Simply put, React offers a defaultProps attribute, to deal with default props values. And it is actually better to use it when dealing with non-functional components, because it will be called by all methods that rely on this.
Props and PropTypes are important mechanisms for passing read-only attributes between React components. We can use React props, short for properties, to send data from one component to another. If a component receives the wrong type of props, it can cause bugs and unexpected errors in your app.
I always do it like this and it works just fine:
class Foo extends React.Component {};
Foo.propTypes = {
animateBackground: PropTypes.bool
};
Foo.defaultProps = {
animateBackground: false
};
export default Foo;
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