Truncate From Middle React Hook
Tags: react, reacthook, npm
Published: 2022-05-23 09:12:19

I've published my very first npm package [`use-truncate-from-middle`](https://www.npmjs.com/package/use-truncate-from-middle). 
 It is a react hook, dynamically truncates text from the middle with given ellipsis string (i.e. `'...'`). 
It considers the width of the _container*_ and its font style. 
In this blog, I am going to talk about the most common methods for truncating text and when you should use the `useTruncateFromMiddle` hook.
 If you want to know the details about how the truncate from middle hook works, you can check my blog post 
 [Calculate Number of Characters Fit into an HTML Element](https://devmuscle.com/blog/number-of-characters-fit-with-hooks).
## The Problem
In web development, if there is not enough space for a text, meaning the width of the container is a fixed value, we truncate it with ellipsis from the end. And it is very easy and safe to make this with pure CSS. 
However, sometimes the **width** value of the container of the text **is not set** by the frontend team, meaning its value comes from an API call or an SDK or from a configuration file etc.
For such a case we have to include JavaScript along with CSS to truncate a long text dynamically. 
 In the next section, there are three most common methods to truncate long text with ellipsis from the end.
## Traditional Ways To Truncate Text
### Case 1: Single Line
I am pretty sure, especially if you are specialized in frontend development, you know by your heart the following css rules for truncating long text:
```css
.truncate {
  width: 240px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
```
### Case 2: Multiple Line
If you need to truncate a text not at the first line, but in other lines, for example you have a container element which can hold maximum two lines of string, we use the following css rules:
```css
.line-clamp {
  display: -webkit-box;
  -webkit-line-clamp: 2; // truncates at the second line
  -webkit-box-orient: vertical;  
  overflow: hidden;
}
```
### Case 3: Container Width Is Dynamic
 In this case, we have to include Javascript along with CSS. 
Especially thanks to [CSS-IN-JS](https://reactjs.org/docs/faq-styling.html#what-is-css-in-js) pattern it is very easy to make it. See below:
```jsx
  const truncateStyle = {
    width: `${widthValue}`,
    whiteSpace: 'nowrap',
    overflow: 'hidden',
    textOverflow: 'ellipsis',
  };
```
In the code block above, it just dynamically creates a style object with JavaScript.
## Truncate Text From Middle
### Static Method: Width of The Container Is Known
Function below truncates the text from the middle:
```js
export const truncateFromMiddle = (
  fullStr= '',
  strLen,
  middleStr= '...',
) => {
  if (fullStr.length <= strLen) return fullStr;
  const midLen = middleStr.length;
  const charsToShow = strLen - midLen;
  const frontChars = Math.ceil(charsToShow / 2);
  const backChars = Math.floor(charsToShow / 2);
  return (
    fullStr.substr(0, frontChars) +
    middleStr+
    fullStr.substr(fullStr.length - backChars)
  );
};

```
The function takes the original text that is `fullStr` and the parameter `strLen` that is the desired length should be shown in the UI.
As you see this method works, only if you know the width value of the container or say the frontend developer is the one who sets the width value in the .css file. The frontend developer decides when to truncate and how much to truncate. Therefore, if you know the width value and you need to truncate the text from the middle this kind of solution would be enough for you.
### Width of The Container Is Not Set, It Depends On External Data
In this case we cannot set a static maximum `strLen` value, and truncate the text from middle using the previous `truncateFromMiddle` function. Because we cannot be sure about when to truncate, and when to show all text. And it is not just about the width actually, it varies **depending on the font style** as well. If font style value also comes externally, still we cannot be 100% sure when to truncate; for example a text with bold font and with large font size occupies more space than the small font size.
For these cases, you can use the `useTruncateFromMiddle` hook. It takes `ref` of the container element and its original text value as parameter.
Below you can see an example result of the hook:
![example-for-the-hook-outcome](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/31tfeci3nxd9ceyelzf8.PNG)
## Conclusion
In this blog I tried to show the case where you need the `useTruncateFromMiddle` hook. 
 You can download and try the package if you have the opportunity or when you really need it. I plan to update the package in line with your feedback. Thank you for reading... Best.

-----
*Container: i.e., `div`, `span`, `button`, read only `textarea` or any other non editable DOM elements.