Kimako
Kimako

Reputation: 625

add a condition in a list item

I am posting a list of products. I would like that when this is displayed, I only keep the first 15 characters of the product name, and if the product has more than 15 characters, that it is automatically displayed '...' after the 15 characters on this line > {item.name.substring(0, 15)} for the moment I added them by hand, but I would have liked it to be done 'automatically' so to speak, via a condition;

Is it possible to add this condition? Thanks for any help!

<ListItem
    style={{width:'100%', justifyContent: 'space-between'}}
    bottomDivider
    onPress={() => this.props.navigation.navigate('ProductDetails', {productId:parseInt(item.id)})}>
    <Image source={{uri:URL+ item.photo}} 
           style={{ height: 25, resizeMode: 'contain'}}/>
    <ListItem.Title style={{width: '65%', fontSize: 16}}>{item.name.substring(0, 15)}...</ListItem.Title>
    <ListItem.Subtitle style={{ color: '#F78400'}}>{item.cost}€</ListItem.Subtitle>
  </ListItem>

Upvotes: 0

Views: 395

Answers (2)

Hend El-Sahli
Hend El-Sahli

Reputation: 6742

I guess you're using React Native Elements...

If so, I'd suggest instead of using ListItem.Title, you use ListItem.Content so you can take advantage of Text > numberOfLines prop... which will truncate the text and automatically generate ellipsis for you...

<ListItem.Content>
  <Text numberOfLines={1}>{item.name}</Text>
</ListItem.Content>

Upvotes: 2

Mayank Pandeyz
Mayank Pandeyz

Reputation: 26258

To implement such type of read more ( character count ) ... kind of functionality you have to do conditional rendering like:

{
  ( item.name.length > 15 )  // Check if length is greater than certain length
  ?
  item.name.substring(0, 15) + ' ...'  // length is greater, show substring and ...
  :
  item.name  // show complete string
}

Upvotes: 1

Related Questions