Bukenya KizzaRoland
Bukenya KizzaRoland

Reputation: 821

How to truncate a string in Reactjs and Tailwind CSS

import React from 'react';

function SampleArticle({ color, title }) {
  return (
    <div>
      <div className='shadow-md p-4 m-2'>
        <div style={{ backgroundColor: color }} className='h-12 w-20 '>
          <h2 className='text-gray-100 bg-textsecondary text-center justify-center'>
            {title}
          </h2>
        </div>
      </div>
    </div>
  );
}

export default SampleArticle;

Can someone help with a code to truncate that title to 2 lines I want the title to cover only one line .The title is in the card

Upvotes: 1

Views: 6539

Answers (2)

AntonioGarc&#237;a
AntonioGarc&#237;a

Reputation: 1150

I suggest you use the text overflow classes from Tailwind. You have precisely the class truncate that includes overflow and also ellipsis for your text.

<h2 className="truncate ...">...</h2>

You can read more about it in the Tailwind docs.

Upvotes: 2

kup
kup

Reputation: 819

You can create a truncate function and use it on title:

const truncate = (str, max, len) => {
    return str.length > max ? str.substring(0, len) + "..." : str;
}

and use it like this:

truncate("My Title", 5, 4)

first argument is your string title, second argument is the max length you should check for, third argument is the length of string you want to show.

And with Tailwind CSS you can use:

<div class="overflow-hidden truncate w-5">{title}</div>

w-5 is the width.

To use truncate you basically need 4 css properties.

text-overflow, width, overflow, white-space

for eg. :

text-overflow: ellipsis;

width: 18rem;

overflow: hidden;

white-space:nowrap;

Upvotes: 2

Related Questions