Home > Software engineering >  What's wrong with this implementation? I'm unable to override the style
What's wrong with this implementation? I'm unable to override the style

Time:10-07

I want to override the fontSize of my subheading text. I'm getting the style prop in my component. I've checked it by using console.log and it's fine. But my styles are not implementing. What's wrong with my code. Please help.

Here's the component called Subheading,

function SubHeadingText({children, style}) {
  return (
    <Text style={[{fontSize: style.fontSize}, styles.textSubHeading]}>
      {children}
    </Text>
  );
}

const styles = StyleSheet.create({
  textSubHeading: {
    fontSize: 19,
    color: colors.black,
  },
});

and here's I'm passing the style

<SubHeadingText style={{fontSize: 14}}>
    All fields are required to register with App.
</SubHeadingText>

CodePudding user response:

Flip the order of the styles, they are applied in order and you override it with the constant stylesheet:

See React Native Style Docs:

You can also pass an array of styles - the last style in the array has precedence, so you can use this to inherit styles

function SubHeadingText({children, style}) {
  return (
    <Text style={[
      styles.textSubHeading, // Needs to be applied first so next line overrides
      {fontSize: style.fontSize}, // Will override styles.textSubHeading fontSize
    ]}>
      {children}
    </Text>
  );
}
  • Related