Home > OS >  Pass in styles from stylesheet into custom component in React Native
Pass in styles from stylesheet into custom component in React Native

Time:07-23

I am trying to pass in styles into my custom Component. They seem to work fine if I manually pass them in like style={{width: 100}} but if I pass them in via stylesheet... they return random numbers into my custom component.

Home Component:

return (
    <View>
        <CustomButton style={styles(theme).button} />
    </View>
);

const styles = (theme: Theme) =>
  StyleSheet.create({
    button: {
      width: 100
    }
  });

CustomButton:

interface ButtonProps {
    style?: object;
}

export const CustomButton: React.FC<ButtonProps> = ({ ...props }: ButtonProps) => {
    console.log(props.style); // returns random numbers like 402, 411, etc

    return (
      <View>
        <Button
          style={{
            marginVertical: 5,
            ...props.style
          }}
        >Test</Button>
      </View>
    );
  };

What am I doing wrong here?

CodePudding user response:

What you are seeing is an optimisation done by StyleSheet. What you are seeing as a "random number" is the object id of the style object button.

You can see the actual object by using StyleSheet.flatten:

console.log(StyleSheet.flatten(styles(theme).button))

which prints the actual object with the width attribute. However, this is not needed and this is also not the reason why your style is not applied.

You are trying to use the spread operator to combine two styles into a single style object, but since StyleSheet just returns an id this does not work. We can test this by using flatten again.

<Button
   style={{
     marginVertical: 5,
     ...StyleSheet.flatten(props.style)
   }}
>Test</Button>

You will notice that the above will now correctly work.

However, this is not the optimal way of combining two styles. We can achieve the same by using combine of styles using the array notation as follows.

<Button
   style={[{marginVertical: 5}, props.style]}
>Test</Button>
  • Related