skip to Main Content

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 ?

2

Answers


  1. Do a ternary, checking the length.

    <div className='desc'>{student.description.length <= 35 ? student.description : (student.description.substring(0,35)+"...") } </div>
    
    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search