DEV Community

Cover image for Truncate Text In React.js and JS
Abod Micheal (he/him)
Abod Micheal (he/him)

Posted on

Truncate Text In React.js and JS

Truncate is to shorten by cutting off a part , it has a lot of uses , you might have a post or description you wanna cut short if its longer or more than a certain amount of text.
Alt Text
ill explain how the bellow code works , you could copy and paste code to your project

class Cover extends Component {
    state = {
      banners: [informations or text we wanna truncate (let say i have 300 words)],
    };
  }
  render() {
    //reduce your information or text 
    const truncate = (input) =>
      input?.length > 300 ? `${input.substring(0, 254)}...` : input;

    return (
      <div>
            {truncate(this.state.banners.overview)}
      </div>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

this code is basically telling the code if your input is greater than 300 it should reduce to 254 and add 3 dots

const truncate = (input) =>
      input?.length > 300 ? `${input.substring(0, 254)}...` : input;
Enter fullscreen mode Exit fullscreen mode

we later called the function in our return and added what we wanna truncate or cut

{truncate(this.state.banners.overview)} 
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
thexdev profile image
M. Akbar Nugroho

Hi, it's a nice post. But, i think it can be more easier when you use css instead of js.

Collapse
 
abodmicheal profile image
Abod Micheal (he/him)

Thank you,
falls into preference , some people prefer using it on Js than css .

Collapse
 
kamo profile image
KAIDI

Hey,
The tag help is used if you have an issue and you need a help to resolve it.