Home > front end >  Changing color of a single word in a button - React Native
Changing color of a single word in a button - React Native

Time:10-13

So looking over some answered questions on the same topic but they all have a totally different layout, I was wondering how to style a different color for the word "Register" in "Don't have an account? Register" which is itself a button.

Component:

const CustomButton = ({onPress, text, type = "PRIMARY", bgColor, fgColor, fontColor}) => {
  return (
    <Pressable 
      onPress={onPress} 
      style={[
        styles.container, 
        styles[`container_${type}`],
        bgColor ? {backgroundColor: bgColor} : {},
      ]}>
      
      <Text 
        style={[
          styles.text, 
          styles[`text_${type}`],
          fgColor ? {color: fgColor} : {},
          fontColor ? {color: fontColor} : {},
        ]}>
          {text}
      </Text>
    </Pressable>
  );
};

Login screen:

<CustomButton 
  text="Don't have an account? Register" 
  onPress={onSignUpPressed} 
  type="TERTIARY" 
  fontColor="#000000"
/>

CodePudding user response:

You can try something like this:

Login Screen:

<CustomButton 
  text="Don't have an account?"
  childText="Register"
  onPress={onSignUpPressed} 
  type="TERTIARY" 
  fontColor="#000000"
  childColor="#DDFFDD"
/>

Component:

const CustomButton = ({onPress, text, type = "PRIMARY", bgColor, fgColor, fontColor, childText, childColor}) => {
  return (
    <Pressable 
      onPress={onPress} 
      style={[
        styles.container, 
        styles[`container_${type}`],
        bgColor ? {backgroundColor: bgColor} : {},
      ]}>
      
      <Text 
        style={[
          styles.text, 
          styles[`text_${type}`],
          fgColor ? {color: fgColor} : {},
          fontColor ? {color: fontColor} : {},
        ]}>
          {text}
          <Text style={[styles.text,{color:childColor|| fontColor}> 
            {childText}
          </Text>
      </Text>
    </Pressable>
  );
};

But the question you should ask yourself is this: Will I use this dual color button feature in more than one place in my app or will this feature only be on this "register" button in my app? If this is the only place you are going to use it, then may be you don't need to use your CustomButton component for this and code a simple button just for this reason. If you are going to use this dual color feature more than once so you can use my simple example above. Even you can improve it to check if childText prop coming or not then decide to show the second text component.

  • Related