Dancer
Dancer

Reputation: 17651

React Native - Conditional check whether prop has value for styling

I'm trying to apply a width to a component - only if a width prop is available - but don't understand where i'm going wrong - can anyone point me in the correct direction please?

class ButtonHomeNav extends React.Component {

render() {
getMinWidth = () => {

 if(this.props.minWidth.length > 0) {
   console.warn('nob jockey');
  return {

    minWidth:this.props.btMinWidth
  }
 }
}
return (
  <View style={[AppStyles.buttonRect, getMinWidth()] } >
    <View style={[AppStyles.buttonRectWrap, this.props.darkCol && AppStyles.darkCol]}>
      <Image style={AppStyles.buttonRectIcon} source={this.props.buttonIcon} />
      <Text style={[AppStyles.buttonRectText, this.props.darkCol && AppStyles.darkColText]}>{this.props.buttonTxt}</Text>
    </View >
  </View>
);

} }

Upvotes: 0

Views: 793

Answers (1)

SiSa
SiSa

Reputation: 2684

You should check if minWidth is null/undefined. also you used two different props minWidth and btMinWidth!

getMinWidth = () => {
    if(this.props.minWidth) {
        console.warn('nob jockey');
        return {
            minWidth: this.props.minWidth
        };
    } else
        return {};
}

You can also use it without function:

<View style={[
    AppStyles.buttonRect,
    this.props.minWidth && {minWidth: this.props.minWidth},
]}>

Upvotes: 1

Related Questions