Limit character length of mapped value in React
Asked Answered
L

1

9

I have a functional react component with text that is displayed from a mapped array. How can I limit the character count of {item.description} to 250 characters?

 import React from "react";

 const Component = props => {
  const classes = props.classes;
  return (
    <div className={classes.container}>
      <ul className={classes.items}>
        {props.children.map((item, i) => (
          <li key={i} className={classes.item}>
            <p className={classes.category}>
              {item.genre} {item.date}
            </p>
            <p className={classes.header}>{item.header}</p>
            <p className={classes.details}>{item.description}</p>
          </li>
        ))}
      </ul>
    </div>
  );
};
Lonne answered 20/9, 2018 at 14:15 Comment(0)
E
19

Short and simple:

<p className={classes.details}>{item.description.substring(0, 250)}</p>

It will return a substring containing the first 250 characters of item.description (or the whole string if it's shorter than 250 chars).


Slightly longer:

If you want to conditionally add ... at the end of the truncated string, you can do:

<p className={classes.details}>
  {item.description.length > 250 ?
    `${item.description.substring(0, 250)}...` : item.description
  }
</p>
Eliathan answered 20/9, 2018 at 14:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.