Search code examples
javascriptreact-nativestyling

Styling reusable components in React-Native


I made a reusable component Button.js and I'm importing it on two different screens. The button looks the same, but on the first screen I need it to be position: 'absolute' and on the second one position: 'relative' (the default).

How do I add the position to be absolute on the first screen? I tried to add the styling on FirstPage.js but it does not work. How do I overwrite the style that is defined in Button.js?

Button.js:

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

const Button = ({ position, onPress, children }) => {
  const { buttonStyle, textStyle } = styles;

    return (
        <TouchableOpacity onPress={onPress} style={buttonStyle, {'position': position}}>
            <Text style={textStyle}>{children}</Text>
        </TouchableOpacity>
    );
};

Button.defaultProps = {
  position: 'relative',
}

const styles = {
  textStyle: {
    alignSelf: 'center',
    color: '#F44336',
    fontSize: 16,
  },
  buttonStyle: {
    zIndex: 2,
    width: 100,
    backgroundColor: '#FFF',
  }
};

export { Button };

Solution

  • You can pass props, something like this (Button.js) (edited according to posted code):

    import React from 'react';
    import { Text, TouchableOpacity } from 'react-native';
    
    const Button = ({ position, onPress, children }) => {
      const { buttonStyle, textStyle } = styles;
      const style = {...buttonStyle, position };
      return (
        <TouchableOpacity onPress={onPress} style={style}>
            <Text style={textStyle}>{children}</Text>
        </TouchableOpacity>
      );
    };
    
    Button.defaultProps = {
      position: 'relative',
    }
    
    const styles = {
      textStyle: {
        alignSelf: 'center',
        color: '#F44336',
        fontSize: 16,
      },
      buttonStyle: {
        zIndex: 2,
        width: 100,
        backgroundColor: '#FFF',
      }
    };
    
    export { Button };
    

    Your button of course looks different, this is just an outline of what you could do (basically just using props).