How to change substring style in react native

Viewed 1534

I have some text to show the user and I want to change style for some indiviual part of string.If the text is between "**" must have bold style.For example

{
        title: 'Food inside a Bowl', url: 'https://www.myvarco.com/varco-images/screen-3.png',
        description: "Lorem Ipsum is **simply dummy** text of the printing and **typesetting industry**.",
        id: 2
},

How I can achieve this in react native

2 Answers

You can use a custom component like below I've added the check for start ** you can change the condition in anyway you want.

const CustomText = (props) => {
 const arr = props.text.split(' ');
  const reducer = (acc, cur, index) => {
    let previousVal = acc[acc.length - 1];
    if (
      previousVal &&
      previousVal.startsWith('**') &&
      !previousVal.endsWith('**')
    ) {
      acc[acc.length - 1] = previousVal + ' ' + cur;
    } else {
      acc.push(cur);
    }
    return acc;
  };

  const text = arr.reduce(reducer, []);

  return (
    <Text>
      {text.map((text) => {
        if (text.startsWith('**')) {
          return (
            <Text style={{ fontWeight: 'bold' }}>
              {text.replaceAll('**', '')}{' '}
            </Text>
          );
        }
        return `${text} `;
      })}
    </Text>
  );
};


export default function App() {
  return (
    <View style={styles.container}>
       <CustomText text="Lorem Ipsum is **simply dummy** text of the printing and **typesetting industry**."/>
    </View>
  );
}
Related