Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

defaultProps in React Native?

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' }
like image 501
Brien Crean Avatar asked Mar 26 '17 22:03

Brien Crean


People also ask

What is defaultProps in React?

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.

Is defaultProps deprecated?

You May Not Need defaultProps ​ As per this tweet, defaultProps will eventually be deprecated.

Should I use defaultProps React?

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.

Why do we need PropTypes?

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.


1 Answers

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;
like image 144
flaky Avatar answered Oct 22 '22 13:10

flaky