How to pass style props for a specific component in react-native

Amirth picture Amirth · Jan 6, 2018 · Viewed 13.7k times · Source

I tried creating a button with specific styles for its . I had more than 3 properties like justifyContent, alignItems, backgroundColor and height. I wanted to pass a style from another component to this, so that the backgroundColor property of the button changes.

My Code:

import React from 'react';
import { Text, TouchableOpacity } from 'react-native';

const Button = ({ buttonName, csCode }) => {
  const { buttonStyle, textStyle } = styles;

  return (
    <TouchableOpacity style={{ buttonStyle, backgroundColor: [csCode] }}>
      <Text style={textStyle}>
      {buttonName}
      </Text>
    </TouchableOpacity>
  );
};

const styles = {
  textStyle: {
    alignSelf: 'center',
    color: '#ffffff',
    fontSize: 35,
    fontWeight: '600',

  },
  buttonStyle: {
    justifyContent: 'center',
    alignSelf: 'stretch',
    height: '20%',
  }
};

export { Button };

Here, the buttonStyle is not applied to the buttons, instead only the backgroundColor prop is only being applied. Any help ?

Thanks.

Answer

moritzw picture moritzw · Jan 6, 2018

If you want to use styles from the styles object and inline styles together, please put them in an array like this:

<TouchableOpacity style={[buttonStyle, {backgroundColor: csCode }]}>
  ...
</TouchableOpacity>