Home > Mobile >  Add to text option to reveal/hide
Add to text option to reveal/hide

Time:08-07

On one of the pages of my site, I display the responses received from the server. By clicking on a specific response, you can go to its page, where we will see the response body, response header, size, and so on.

But as you can imagine, the response body can be quite huge. And the scrolling of the page turns into torment :) I would like to make it so that the information from the response body would initially be hidden (for example, only the first couple of lines, and then the "more" button. By clicking on which you can open the entire text. And, accordingly, at the end text less button to hide the text back to its original state. https://www.quora.com/Is-there-a-site-where-you-can-type-in-a-long-text-then-the-site-will-try-to-shorten-the-text-for-you-by-reformatting-the-text-in-different-ways).

export default function PocketDataResponse({ firestore, urlParams }) {
    const recordRef = firestore
        .collection("devices").doc(urlParams.deviceId)
        .collection("records").doc(urlParams.recordId)

    const record = useRecord(recordRef)

    return (
        record ?
            <TableContainer sx={styles.TableContainer}>
                Body: {record.response.body} <br></br>  // Here I would like to do what would hide and reveal the text
                Headers: {record.response.headers.toString()} <br></br>
                
                
            </TableContainer>
            : <Typography> Record not found </Typography>
    );
}

This function is responsible for getting the data from the database (in my case, it is a firestore) and displaying it on the page (in fact, this component is passed to me in two more components, but this does not matter for solving this problem).

Tell me, how can I display the response body as hidden text?

CodePudding user response:

You could use a state variable showFullText to handle how the text is displayed.
If false it will display only a part of the response:

export default function PocketDataResponse({ firestore, urlParams }) {
  const recordRef = firestore
    .collection('devices')
    .doc(urlParams.deviceId)
    .collection('records')
    .doc(urlParams.recordId);

  const record = useRecord(recordRef);

  const [showFullText, setShowFullText] = useState(false);

  const truncateText = (str, len) => {
    if (str.length < len) return str;
    return str.substring(0, len)   '...';
  };

  return record ? (
    <TableContainer sx={styles.TableContainer}>
      Body: {showFullText ? record.response.body : truncateText(record.response.body, 100)} <br></br> 
      <button type='button' onClick={() => setShowFullText(prev => !prev)}>{showFullText ? 'Show less' : 'Show more'}</button>
      Headers: {record.response.headers.toString()} <br></br>
    </TableContainer>
  ) : (
    <Typography> Record not found </Typography>
  );
}
  • Related