-1

I am using .map function to display a description. I would like to show only 35 characters followed by ... only if it exceeds 35 chars

e.g. This is description of thirty five ...

I am trying to show as below

<div className='desc'>{student.description.substring(0,35)+"..." } </div>

How to add logic for "..." so that it only shows when student.descripton.length() > 35 ?

dave_bell
  • 121
  • 9
  • 1
    Just add a ternary `{student.description.length > 35 ? student.description.substring(0,35)+"..." : student.description}` – pilchard Apr 15 '23 at 00:28
  • 1
    Just in case you don't know the word and are looking for a search term, you looking for how to _elide_ text. Also, in case you don't know, CSS has a text-overflow mode called `text-overflow: ellipsis` that does this automatically based on the space available. – Wyck Apr 15 '23 at 00:50
  • Thanks...I had no clue about "elide". So which approach is preferred and light? CSS or JS Function? – dave_bell Apr 15 '23 at 02:08

2 Answers2

1

Do a ternary, checking the length.

<div className='desc'>{student.description.length <= 35 ? student.description : (student.description.substring(0,35)+"...") } </div>
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34
0

Create a function that determines the length of the string and returns the appropriate text based on that length, and then call it from the JSX.

function getFormattedText(text) {
  if (text.length <= 35) return text;
  return `${text.substring(0, 35)}...`;
}

function Example({ text }) {
  return (
    <div>
      {getFormattedText(text)}
    </div>
  );
}

const text = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.';

ReactDOM.render(
  <Example text={text} />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
Andy
  • 61,948
  • 13
  • 68
  • 95