React Native: Adding emphasis to Text elements without the pain.
Tags: reactnative, performance, javascript
Published: 2023-02-16 23:38:08


## Making words stand out

We've all been there, we have a phrase, a sentence or greeting in a <Text> component, but we want one or more words to be emphasised using bold lettering.

The problem with React Native it can be difficult to write this cleanly within code. We end up with multiple <Text/> elements , which can make our parent components cluttered and hard to read.

### Example 

Let's take the example of a hotel booking confirmation notification.

![Output screenshot showing 2 clips of emphasised text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/inikfgnbsj8ysiit9e0o.png)



_You can see that they are both the same, in terms of output - yet the code is very different._

#### The unclean way

![Card code with multiple text components](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0n4zviqnt18l2oescoe9.png)

You can see we've had to implement multiple text components in order to get the effect we'd want to. Achieved by alternating text components with varying font weights.

## I've developed a cleaner way

I've written a component that will keep your code cleaner and easier to use. Everywhere you wish to have bold emphasised text.



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ancqyfepm0x13vbs05xn.png)

Code: (for sharing)
```ts
export const BoldText: React.FC<BoldTextProps> = (props) => {
  const { fullText, boldTextParts, boldWeight, fontSize } = props;
  const regEx = new RegExp(`\\b(${boldTextParts.join("|")})\\b`, "gi");
  const splitText = fullText.split(regEx);

  return (
    <Text>
      {splitText.map((textPart, i) =>
        boldTextParts.includes(textPart) ? (
          <Text key={i} style={{ fontWeight: boldWeight, fontSize: fontSize }}>
            {textPart}
          </Text>
        ) : (
          <Text style={{ fontSize: fontSize }} key={i}>
            {textPart}
          </Text>
        )
      )}
    </Text>
  );
};
```

### Usage:

![Example of usage of clean component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0yuj8d0o4cjf0cxj1woc.png)

Here you can see our usage is so much cleaner, making the parent component much easier to read. 

## Pro's of doing it this way:

- Why splitting using an "|" operator regex we can split on full phrases, and split on multiple items.

- The usage of this component makes code much cleaner, and easier to read.

- Makes refactoring easier, as don't need to update multiple `<Text/>` elements, can be done by updating the `<BoldText/>` component only.

## Explanation:

The component takes in a fullText string, as well as the parts [`boldTextParts`] that are needed to be emphasised.

Additional props as `fontWeight` and `fontSize`, allowing you to control the weighting of the emphasised text, should you wish to perhaps have a semi-bold look.

The key part to this code is:

```ts
const splitText = fullText.split(
    new RegExp(`\\b(${boldTextParts.join('|')\\b})`, 'gi'),
  );
```

In simplest terms, this creates a [RegEx patten](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) is joining the array of `boldTextParts` with `|` operator, and creating a "OR" RegEx pattern.

Using this RegEx _OR_ pattern informs the `string.split()` method to split on "Grant" OR "28th May 2023", which therefore outputs:

```ts
['Hi ', 'Grant', ', Your booking on the ', '28th May 2023', ' has been confirmed.']
```

We can then map over the `splitText` array (above). As as we loop through each portion of text, we check this against the boldTextParts, which helps us decide if the text portion needs to be in bold, or not.


### Conclusion
I hope you find this article useful, should you wish to discuss, don't forget to leave a comment, or follow me on [twitter](http://twitter.com/gweaths).