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
<
I do it in ReactNative
import React, {
Component
} from 'react';
import {
View,
Text
} from 'react-native';
import PropTypes from 'prop-types';
export default class foo extends Component {
static propTypes = {
name: PropTypes.array,
prop2: PropTypes.string
}
static defaultProps = {
array: [1, 2, 4],
name: 'abc'
}
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<View>
<Text>Default Prop array is: {this.props.array}</Text>
<Text>Default Prop name is: {this.props.name}</Text>
</View>
);
}
}
And then you can use these props like this.props.prop1
and this.props.prop2
.
You want this:
Foo.propTypes = {
someData: React.PropTypes.string
};
This says that someData
should be a string, but it is not required.
Then in your render()
, you can do this:
render() {
return (
<View>
{this.props.someData || Foo.defaultProps.someData}
</View>
);
}
This will use this.props.someData
if it's provided or Foo.defaultProps.someData
if not.
I also think you need to wrap {this.props.someData || Foo.defaultProps.someData}
in a Text
element (i.e., <Text>{this.props.someData || Foo.defaultProps.someData}</Text>
).
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;