I'm attempting to create a text toggle button for displaying more or less content

I am currently working on implementing a show more/show less button feature. However, the current version is not very effective as I only used slicing to hide content when the state is false and display it all when true. Now, my goal is to only show the first row in each card but I'm unsure how to achieve this.

  const classes = useStyles(props);
  const { name, text, firstButtonText, secondButtonText } = props;
  const [show, setShow] = useState(false);

  const handleReadMore = () => {
    setShow(prevShow => !prevShow);
  };

  return (
    <Card className={classes.card}>
      <CardMedia
        className={classes.media}
        image={require(`../../assets/photos/${name}.png`)}
        title={name}
      />
      <CardContent>
        <Typography
          gutterBottom
          variant="h5"
          component="h2"
          className={classes.textStyling}
        >
          {show ? text : text.slice(0, 45)}
        </Typography>
      </CardContent>

      <CardActions>
        <Button size="small" color="primary">
          {firstButtonText}
        </Button>
        <Button size="small" color="primary" onClick={handleReadMore}>
          {secondButtonText}
        </Button>
      </CardActions>
    </Card>
  );
};

Answer №1

To achieve conditional rendering of specific items, you can follow this approach:

<CardContent>
{display &&(<Typography
  gutterBottom
  variant="h5"
  component="h2"
  className={classes.textStyling}
  >
    {content}
  </Typography>)}
</CardContent>

Apply the same concept to other sections as well:

<CardContent>
  <Typography gutterBottom variant="h5" component="h2" className={classes.textStyling}>
    {content}
  </Typography>
  {display && (<div>...</div>)}
</CardContent>

Answer №2

To achieve this effect, you can utilize CSS by setting the line-height to your desired value and max-height to multiples of that value that you wish to display.

.singleLine{ // 1 line
    line-height:1.5em;
    max-height:1.5em;
    overflow: hidden;
}
.multiLine{ // 3 lines
    line-height:1.5em;
    max-height:4.5em;
    overflow: hidden;
}

<Typography
      gutterBottom
      variant="h5"
      component="h2"
      className={show ? classes.multiLine : classes.singleLine}
    >

.singleLine{ 
    width: 50px;
    line-height:1.5em;
    max-height:1.5em;
    overflow:hidden;
<div>
Single -------------------------
</div>
<div class="singleLine">
dasdasasdasdas dasdasdasdasd sadasd asdasd sadasd sadasd asdasd a
</div>
<div>
Multi -------------------------
</div>
<div class="multiLine">
dasdasasdasdas dasdasdasdasd sadasd asdasd sadasd sadasd asdasd a
</div>

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

Encountering an ENOENT error while attempting to incorporate a style guide into next.js (react)

Recently, I delved into learning next.js and decided to enhance my project with documentation using To kickstart my project, I utilized npx create-next-app After installation and configuration setup, I added the following code snippet: [styleguide.config ...

`asp:button displaying without any CSS applied`

asp:Button does not respond to CSS styling. CSS: .TabButton { border: none; background-size: cover; background-repeat: no-repeat; width: 100%; height: 100%; } HTML5: <asp:Button runat="server" Text="Events" CssClass ="TabButton" ...

Leveraging server.ts for Development with Angular 5 Universal

I decided to give the new Angular Universal Starter a try for my latest Angular 5 project. Instead of providing multiple options, they now only offer the Angular CLI version as a starting point. I've been able to successfully run my project in product ...

Bootstrap.js has the ability to utilize nested objects for organizing and

As I work on enhancing a Combobox class I developed to complement Bootstrap 4, I am aiming to align the Javascript with the existing Bootstrap code. During this process, I came across a snippet of code in bootstrap.js while studying the Modal component: ...

I'm new to learning JavaScript and I'm wondering how I can receive a single alert using only the if operator

Extracted from the book "Beginning JS 4th edition", this code snippet displays two alert messages when loaded in a browser due to two NaN entries in an array. To ensure that only one alert is shown every time, how can I achieve this using the if operator? ...

How can I submit multiple dropdown menus when they are changed?

I recently added Four dropdown menus on my index.php page. <select name="filter_month" class="filters"> <option>Select a Month</option> <option value="1">January</option> <option value="2">February</optio ...

Reactjs Screen is failing to refresh properly, consistently lagging by one loop when making updates

After updating a record that is displayed on the screen, I noticed that the changes were not reflected in the MySql database. Despite attempts to refresh the array and filter the results, the screen remained stagnant. Only after manually refreshing the bro ...

"Exploring the Power of Logarithmic Slider with Vue and Quasar

I'm currently working on a project utilizing Vue 2 and Quasar 1, where I am attempting to develop a logarithmic slider. Initially, I managed to create a basic example using a native input slider in this code pen: https://codepen.io/tonycarpenter/pen/Z ...

basic computation of whole and decimal values using jquery

I'm having trouble multiplying 2 values in my code where the quantity is an integer and credit price is a decimal number. However, when I run the script, nothing seems to happen. Can someone please help me identify and resolve this issue? Any insight ...

Having trouble sending an HTTPS request in NodeJS only to receive an HTTP response instead

As I develop my website using NodeJS and deploy it on Heroku, I encountered an issue upon opening the website. Here is the problem at hand: When looking at the main source file of my web application: app.get('/', (req, res) => { var data ...

The HTML page is displaying the Express.js GET request

As a beginner in express.js, I'm encountering an issue where data sent to the client is displayed directly in the browser instead of appearing as a preview. Can someone please review my code and help me identify what I'm doing wrong? app.use(cors ...

What is the best way to incorporate quotes within inline CSS code?

Can anyone help me with inserting the following CSS into HTML? Here is the CSS snippet that needs to be converted to HTML: .group .circular-progress::before { ... content: "10%"; ... } This is what I have attempted so far: <div class="group"&g ...

Maintaining the functionality of an AJAX web page even after extended periods of inactivity

When using my one-page web app, I sometimes leave the page open overnight and find that when I come back in the morning, things don't work as they should. It seems like Javascript is acting up - edit-in-place loads incorrect data, ajax calls fail to f ...

Centered at the bottom of the screen lies a Bootstrap button

As a beginner with bootstrap, I am currently exploring new concepts and experimenting with different features. One thing I am attempting is to center a bootstrap button at the bottom of the screen. Here is my current code: .bottom-center { position: a ...

Encountering an issue with eslint-loader in a new VueJS project: TypeError - eslint.CLIEngine is not recognized as

Embarking on a fresh VueJS venture with WebStorm. A brand new VueJS project has been established, NPM upgraded, Vuetify added, and upon server initiation, an error pops up: ERROR Failed to compile with 1 errors ...

The module was not found because the package path "./link" is not being exported from the package located in the node_modules

Just completed a merge of one branch with another in my Next.js app, which included major changes and conflict resolutions. Initially, everything appeared to be fine. However, after reinstalling the next-intl package, I encountered the following error: M ...

Eliminate redundant XML entries when using jQuery autocomplete

Does anyone know how to prevent duplicate records from appearing in a jQuery autocomplete dropdown? I am pulling data from an XML file and want to ensure that each record is unique and only displayed once. You can see the issue here ...

Elements powered by jQuery failing to load upon dynamic webpage(s) loading via ajax

Dynamic loading of jQuery elements, such as Ibuttons, seems to be causing issues when implemented with an ajax dynamic content loader. The entirety of my website is rendered through Ajax just like this: <html> <header> {jQuery} </header> ...

Deploying my node.js project on a live server

I recently started using node.js and built a project with create-react-app, incorporating react, react-redux, and react-router. Now that I am ready to upload my project to a live server, I'm unsure whether I need to include the node_modules folder i ...

Exploring the potential of jQuery and AJAX for dynamic content generation:

I have developed a jQuery plugin that pulls data from a JSON feed (specifically YouTube) and then presents the results in a DIV. Everything is working well until I need to display the results with different configurations, such as more videos or from anoth ...