6

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' }
Brien Crean
  • 2,599
  • 5
  • 21
  • 46

4 Answers4

19

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;
flaky
  • 6,816
  • 4
  • 29
  • 46
0

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.

Ajay
  • 450
  • 3
  • 11
0

I uses in this way ,try this!

import React,{Component} from 'react'
import {View, Text} from 'react-native';
export default class Example extends Component {
  render() {
    return (
      <View>
        <Text>{this.props.name}</Text>
      </View>
    )
  }
}

Example.defaultProps = {
  name: 'John'
}
Kishan
  • 106
  • 6
-1

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>).

TheJizel
  • 1,864
  • 1
  • 15
  • 14