Tips for condensing text within a card using react bootstrap

I am currently working with a card that looks like this:

https://i.sstatic.net/nFTLh.png

<Card className="m-5 border-0 shadow" style={styles.card}>
  <Row>
    <Col>
      <Card.Img src={require("../assets/images/findingsPage/EnglishesOfTheWorld.jpg")} style={styles.cardImage} />
    </Col>
    <Col>
      <Card.Body>
      <Card.Title as="h1">Englishes of the World</Card.Title>
      <Card.Text as="h4" style={styles.cardText}>
        How do your grammar intuitions depend on when and where you learned English? Participants took a short grammar quiz, which we are using to understand how grammar differs in different parts of the English-speaking world (USA, Ireland, Australia, etc.). We are also investigating how grammar is different for people who learn English later in life: Do they make different mistakes if their first language is German as opposed to Japanese?
      </Card.Text>
      </Card.Body>
    </Col>
  </Row>
</Card>

I am looking for a way to collapse part of the text if it exceeds the height of the card, similar to what is shown here:

https://i.sstatic.net/oM4CT.jpg

https://i.sstatic.net/8ogje.jpg

Any suggestions or help would be greatly appreciated. Thank you.

Answer №1

To get started, here's a demo link: https://codesandbox.io/s/cool-wright-u5old?file=/src/App.js

Here's how the logic works:

  • When the component mounts, a ref is used to check if the height of the text parent exceeds a defined limit
  • If the height surpasses the limit, the max-height property is set and a toggle button is displayed
  • Clicking on the button toggles the max-height between the specified limit and the maximum height allowed for the card

The use of max-height is crucial for achieving smooth transitions in CSS, as discussed in this Stack Overflow post.

To make things more convenient, this logic has been encapsulated into a separate Component, but it can also be integrated directly into the original component.

Now, let's dive into the code:

const MAX_POSSIBLE_HEIGHT = 500;

const ExpendableText = ({ maxHeight, children }) => {
  const ref = useRef();
  const [shouldShowExpand, setShouldShowExpand] = useState(false);
  const [expanded, setExpanded] = useState(true);

  useEffect(() => {
    if (ref.current.scrollHeight > maxHeight) {
      setShouldShowExpand(true);
      setExpanded(false);
    }
  }, [maxHeight]);

  return (
    <Card.Text as="h4" style={styles.cardText} ref={ref}>
      <div
        class="inner"
        style={{ maxHeight: expanded ? MAX_POSSIBLE_HEIGHT : maxHeight }}
      >
        {children}
      </div>
      {shouldShowExpand && (
        <button onClick={() => setExpanded(!expanded)}>Expand</button>
      )}
    </Card.Text>
  );
};

And here's the corresponding CSS:

.inner {
  overflow: hidden;
  transition: max-height 0.2s ease;
}

To use the component, simply include it like so:

<ExpendableText maxHeight={95}>
  How do your grammar intuitions depend on when and where you learned English? Participants took a short grammar quiz...
</ExpendableText>
  • A height transition has been added to the solution for extra flair. If not needed, the code will be shorter.
  • If content will always need to be truncated, the implementation becomes simpler.

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

Troubles with aligning a figure in Bootstrap 4

I am in the process of updating my website layout from an old version marked by Old HTML, which can be found at JFiddle: https://jsfiddle.net/LybeppL3/11/ The new version I am working on, known as Current Code: https://jsfiddle.net/5c2sm9s1/23/ OR at Pree ...

Uncovering the Reasons Behind Multiple Accesses to a ReactJS Page

The code snippet provided shows an issue with accessing the /profile page. Upon accessing the page, there are 6 POST requests sent to the backend. However, after implementing the useEffect hook, while the page is still accessed 6 times, now only 2 POST req ...

Slow TextField Updates in React

As a newcomer to the world of React, I'm struggling a bit with understanding how to pass props and states from a child component to a parent. While I've managed to make something that functions, it's unfortunately quite slow. Here's an ...

Use the useEffect hook to dynamically load an element within the current div

Recently, I embarked on a journey to develop a basic login page using React. I integrated two input sections - one for the username and another for the password. Additionally, I included an animated div that functions via the useEffect hook. My goal is for ...

Combining React Conetxt with useReducer and Typescript throws the error message: 'No overload matches this call'

Here is a sample of my reducer code: import { IState } from "./initialState"; import { TAction } from "./actions"; import * as types from './types'; const myReducer = (state: IState, action: TAction): IState => { const ...

When choosing an email address, the input field in Nextjs turns a bright shade of white

Having an issue with my login form in Nextjs using tailwind. When selecting an email that's saved in Google Chrome, the input field turns white. Any suggestions on how to fix this? view image I attempted adding a focus but unfortunately it didn' ...

How can we efficiently loop through all the icons in React Material-UI?

I am looking to iterate over all the icons from @material-ui/icons in a React application. If I want to import a single icon, I can do so like this import IconNameIcon from '@material-ui/icons/IconName' and then use it in my component like th ...

Exploring the dimensions of checkboxes in Fluent UI Northstar

Is there a specific method for controlling the size of checkboxes in Fluent UI Northstar? My attempts to modify the font size and height have only impacted the label, not the checkbox itself. Unfortunately, I couldn't find any guidance on this in the ...

Scrolling to the next wrap class in jQuery is not functioning properly with the chatbox and ScrollTop

I have created a chat box using jQuery. However, I am facing an issue where when I click the button multiple times, the scroll returns to the top. My objective is for the scroll to move to the next wrap class when the button is clicked. Here is a snippet ...

Step-by-step guide on leveraging PubNub for facilitating group chat creation by users

I am currently working on developing a chat application utilizing PubNub. A key feature I am seeking to implement is the ability for individual users to create group chats, where they can add or remove members and designate admins. While I have come across ...

Address the NPM alert regarding Bootstrap's 'unmet peer dependency' in Angular even if Bootstrap is not utilized

In my web project, I am using Angular 5.2.0 along with Bootstrap 4. To install Bootstrap 4, I used the command npm i bootstrap --save, which resulted in unmet peer dependencies warnings: npm WARN <a href="/cdn-cgi/l/email-protection" class="__cf_email_ ...

Customizing text documents within an iframe using CSS from the parent page

My HTML page consists of multiple iframes, each linking to a text file on the same domain. I have done some research on how iframes behave when they point to an HTML file, but I haven't found much information on what happens when they link to a text ...

How can I update my outdated manifest v2 code to manifest v3 for my Google Chrome Extension?

Currently, I am developing an extension and using a template from a previous YouTube video that is based on manifest v2. However, I am implementing manifest v3 in my extension. Can anyone guide me on how to update this specific piece of code? "backgro ...

How to target the first and last elements of sequences with a specific class using CSS

My webpage contains numerous div elements with the class line, each containing a strong.datum element. I want to designate the first and last element of each sequence with the class .active. If this can't be achieved using CSS, is there a way to accom ...

Div - containing images removed from slideshow

Currently, I am in the process of constructing a small website that includes a slideshow beneath my navigation bar. My aim is to utilize flexbox while making the slideshow "responsive." By this, I mean that when altering the dimensions of my browser window ...

Tips for utilizing FileReader in a synchronous manner within the context of react/redux

Struggling to design a solution that integrates with the FileReader API in a react/redux application due to its asynchronous nature. Despite researching, I haven't found a suitable approach just yet. In my react component, I utilize react-dropzone to ...

How come I am able to reference a component in styled-components while others cannot?

When using styled-components, you can reference another React component using the syntax ${Label}. However, I have noticed that it only works with certain components and not others. Despite reading the documentation at , I encountered an issue when trying ...

The Bootstrap website appears visually appealing on desktop browsers, but the div elements are failing to display correctly on mobile devices

After using Bootstrap to create a multi-row, multi-column site, I encountered an issue with resizing on mobile devices. The divs misalign, stack on top of each other, content disappears, and images flatten to the point of invisibility. How can I maintain t ...

How can I retrieve the ID value from the returned promise?

Can someone help me figure out how to retrieve the ID of a newly uploaded file in SharePoint Online? I need this ID so that I can add permissions to the file within a document library. Below is the code snippet and promise chain I have been working with: ...

Creating an animated full-width SVG with a background image

This has been quite a challenge for me. I have successfully implemented the main functionality that I wanted in this codepen. The SVG is divided into 3 sections, with the middle section sliding away from the others when you click the "Find Out More" button ...