最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - React Native limit characters - Stack Overflow

matteradmin5PV0评论

I am working with the API.

renderGridItem = (itemData) => {
 return(
  <Text>
   {itemData.item.description}
  </Text>
 );
};

I want to show only the first 50 characters of the description. How can I do that?

I am working with the API.

renderGridItem = (itemData) => {
 return(
  <Text>
   {itemData.item.description}
  </Text>
 );
};

I want to show only the first 50 characters of the description. How can I do that?

Share Improve this question edited Jul 13, 2020 at 17:36 monamona 1,2462 gold badges21 silver badges46 bronze badges asked Jul 13, 2020 at 15:44 NaiNai 551 silver badge9 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

Wele @Nai to StackOverflow,

You may use the pure JavaScript functions. slice or maybe substring.

Use of Slice:-

renderGridItem = (itemData) => {
 return(
  <Text>
   {itemData.item.description.slice(0, 50)}
  </Text>
 );
};

You can just use regular javascript functions to do that. In this case substring

renderGridItem = (itemData) => {
 return(
  <Text>
   {itemData.item.description.substring(0, 50)}
  </Text>
 );
};

Not exactly 50 characters, but you could achieve this with a bination of:

  • Declare numberOfLines prop for text and set it to 1 / 2 (depending on your needs).
  • Declare ellipsizeMode with whatever you want it to be.
  • Set width of the container / text itself to the width you need and want to display.

Link to docs on Text in React Native.

This way you're making sure that your text is going to show correctly and no word is going to be cut in an ugly way.

Post a comment

comment list (0)

  1. No comments so far