Arbnor
Arbnor

Reputation: 2352

Style is not passed down to Custom Component React Native

I have a Custom Button Component with this code

import React from 'react';
import { TouchableOpacity, View, Text } from 'react-native';
import PropTypes from 'prop-types';

import styles from './styles';

const CustomBtn = ({props, text, onPress }) => (
    <TouchableOpacity {...props} onPress={onPress}>
        <View style={styles.button}>
             <Text style={styles.text}>{text}</Text>
        </View>
    </TouchableOpacity>
);

CustomBtn = {
  text: PropTypes.string,
  onPress: PropTypes.func,
};

export default CustomBtn;

I want to override the styles (Margins, Paddings) of the Component in my view where I write

<CustomBtn style={styles.BtnMargin} onPress={this.handlePressLogin} text="Login" />

But my custom Button don't get the style. How to change the code for the custom btn to solve this?

Upvotes: 4

Views: 510

Answers (1)

Teivaz
Teivaz

Reputation: 5665

You are using the stateless component wrong. If you look at the signature you can notice that it accepts props as an argument:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

In the line {...props} varibale props is undefined because it is the same as this.props.props in a normal component. What you really want to do is:

const CustomBtn = (props) => (
    <TouchableOpacity {...props} onPress={props.onPress}>
        <View style={styles.button}>
             <Text style={styles.text}>{props.text}</Text>
        </View>
    </TouchableOpacity>
);

Upvotes: 1

Related Questions