Shorten Text - React Native

I currently have a React Native application with a FlatList component.

The logic I initially implemented was to display an Expand/Collapse arrow whenever the content at the 100th position in the list is not empty. However, I now realize that this approach is flawed. Changing the font size of my app or using different characters like Chinese text renders this logic ineffective. Therefore, it should not be solely based on character count.

{  alert.charAt(100) !== "" ?
                arrowClicked === true ? 
                <Icon type='materialicons' name='arrow-drop-up' onPress={()=>{this.setFullLength()}}  />
                : 
                <Icon type='materialicons' name='arrow-drop-down' onPress={()=>{this.setFullLength()}}  />
                : null
            } 

I need a solution to detect when the text is long and being truncated instead. How can I go about implementing this? Your assistance is greatly appreciated!

Answer №1

Utilize the onTextLayout function to determine line length as shown below.

function CustomText(props) {
  const [showMore, setShowMore] = React.useState(false);
  const [lines, setLines] = React.useState(props.numberOfLines);

  const onTextLayout = (e) => {
    setShowMore(
      e.nativeEvent.lines.length > props.numberOfLines && lines !== 0
    );
  };

  return (
    <View>
      <Text numberOfLines={lines} onTextLayout={onTextLayout}>
        {props.children}
      </Text>
      {showMore && (
        <Button title="Show More"
          onPress={() => {
            setLines(0);
            setShowMore(false);
          }}
        />
      )}
      {!showMore && (
        <Button title="Hide More"
          onPress={() => {
            setLines(props.numberOfLines);
          }}
        />
      )}
    </View>
  );
}

How to Use

  const text =
    'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industrys standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to mak';

 <CustomText numberOfLines={2}>{text}</CustomText>

You can also pass other properties like styles.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adding a class to the following DIV and smoothly transitioning the current one out can be achieved using a dynamic number of items in multiple instances

Is there a way to create a scalable CSS slideshow for text divs without using images? Here is the current HTML structure: <div class="mb-panel-container cf"> <div class="mb-panel-section mb-slider"> <div class="mb-panel active" ...

Exploring the process of uploading images to MongoDB buffers using React on the client side

I am currently utilizing multer for file uploads const upload = multer({ limits: { fileSize: 1000000 }, fileFilter(req, file, cb) { if (!file.originalname.match(/\.(jpg|jpeg|png)$/)) { return cb(new Error( ...

I am having trouble getting my getColor() method to correctly change colors based on the data provided

When using a datatable, there are two columns: status and priority. The STATUS LIST includes OPEN or CLOSED, while the PRIORITY LIST includes HIGH, MODERATE, and LOW. So, if the status is open, it should be displayed in red color; if closed, then in green. ...

Utilize context.isPointInPath(x, y) in HTML5 Canvas for intricate shapes that contain multiple paths

I am currently working on a project that involves drawing a complex shape composed of 6 thin lines and two thick lines. In my code, I have defined 8 paths to achieve this: context.save(); context.lineWidth=2; var TAB_ABSTAND=10; var T ...

How is it possible that I am able to retrieve an image from the public folder but unable to access a

I recently started learning Reactjs and came across this issue. In the images folder of my React project created with create-react-app, I have placed both a json file and a jpg image. However, I am able to use the jpg image but not the json file. let pho ...

Unable to locate the value property of a null object

I'm currently working on creating a Shopping Cart using HTML, CSS, JavaScript, and JQuery. The idea is that when you click "Add to Cart" for the orange item, most of the HTML elements will disappear, leaving only the table displaying the Shopping Cart ...

Issues have been reported regarding compatibility between iOS7, jquery.touchSwipe, on click and webkit-touch-callout

I'm in the process of developing a web application, but I've encountered an issue with iOS7 where there seems to be a conflict between jquery.touchSwipe and my "on click" events. Interestingly, the web app functions perfectly on older iOS versio ...

What is the process of integrating hegel.js with a React application created using create-react-app?

Have you heard of Hegel.js? It's a powerful type checker that I recently discovered. Surprisingly, there isn't much information online about using hegel.js with React. Check it out at ...

Issue with Flex display not being applied within Material UI Grid Item

I am attempting to position an element at the end of a Grid Item (horizontally). In order to achieve this, I am enclosing my component in the following div: Here is the complete code snippet: <Grid container spacing={8} alignItems={'stretch' ...

Customize the antd theme in a create-react-app project without the need to eject webpack

Struggling with customizing antd in my react app. I'm hesitant to mess with the webpack config.js file since I'm not well-versed in webpack. My goal is to avoid having a site that looks like a generic antd clone, but all my attempts at customizat ...

Exploring table iteration in Angular 7

I am looking to create a table with one property per cell, but I want each row to contain 4 cells before moving on to the next row... This is what I want: <table> <tr> <td> <mat-checkbox>1</mat-checkbox& ...

Having trouble with resolving 'react-transition-group' in MUI IconButton?

I can't seem to shake this persistent error: ./node_modules/@mui/material/ButtonBase/TouchRipple.js Module not found: Can't resolve 'react-transition-group' in '#/node_modules/@mui/material/ButtonBase' I've diligently fo ...

HTML/CSS - Enhances user experience by zooming in on select tag when tapped on mobile devices

I am experiencing an issue with a select menu on mobile devices. Whenever I tap on the menu, it seems to zoom in slightly. Is there a particular -webkit property causing this behavior? How can I prevent the screen from zooming when I tap on the select me ...

What is the best way to apply focus to a list element using Javascript?

I recently created code to display a list of elements on my webpage. Additionally, I implemented JavaScript functionality to slice the elements. Initially, my page displays 5 elements and each time a user clicks on the "show more" link, an additional 5 ele ...

Choosing one item from an array to showcase in a view [Angular]

I've previously inquired about this issue without success. My current challenge involves a store app created with AngularJS. I am trying to implement a feature where clicking on an item will open it in a separate "item" view, displaying only the info ...

What is the process of integrating data from the OpenWeatherMap API into the WindowInfo feature of Google Maps?

My current project involves retrieving weather information from the openweathermap API and displaying it in an infowindow on Google Maps. However, there seems to be an issue where I am getting data from the previous marker instead of the current one. var ...

Tips for incorporating animated features into a bar graph using jQuery

How can I create a dynamic animated bar graph using jQuery? I am looking to make the bar slide up from the bottom, incorporating images for both the bar and background. I have already set the positioning in CSS and now need to add animation to make the bar ...

Rendering based on conditions with a pair of values

I am trying to render my component only if the id is equal to either 15 or 12. My current approach is not working as expected, it only renders the component when I check for one id at a time, but I need to check for both. {query_estate_id === 15 || q ...

Looking to update the location of an element within a canvas using Vue and socket.io?

I am currently developing a 2D pong game using vue.js and socket.io. At the moment, I have a black rectangle displayed in a canvas. My goal is to make this rectangle move following the cursor of my mouse. The issue I am facing is that although my console l ...

Is it feasible to update just one key within an exported type using setState in TypeScript?

Recently, I decided to dive into Typescript within my React App and encountered an error that has left me stumped. I'm wondering if it's possible to access a specific key in an exported type and modify its value? Here is how I've exported ...