Skip to content
Advertisement

React Native, in a text string, change color of words having # or @ in start just like twitter

I have a text string some of words are having # or @ as prefix (in start of words, just as #example or @example) i want to change such words into blue color . React Native

Advertisement

Answer

You can use a custom component like below.

const CustomText = (props) => {
    const text = props.text.split(' ');
    return <Text>{text.map(text => {
      if (text.startsWith('@') || text.startsWith('#')) {
        return <Text style={{ color: 'blue' }}>{text} </Text>;
      }
      return `${text} `;
    })}</Text>;
}

export default function App() {
  return (
    <View style={styles.container}>
       <CustomText text="this is a @sample #text"/>
    </View>
  );
}

You can check the working snack https://snack.expo.io/@guruparan/demo2

Advertisement