Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a show more/less button with ReactJS to adjust the size of a div?

Tags:

reactjs

I have a div with many <p> and <span> inside, is there any example of how to create a show more/less button with ReactJS to adjust the size of a div?

I have tried to install npm read more and npm truncate, but it seems not to solve my problem. Because I have to adjust the size of a div and the text in the button on click in React.

Thanks!

like image 773
Carson Yau Avatar asked Sep 07 '17 09:09

Carson Yau


2 Answers

With React you can easily adapt the rendering of your component depending on the state. You can have a boolean in the state (isOpen for example) and toggle the value when you click on the more/less button.

After that, you have just to render X items and change the button text depending on the boolean value.

I made an exemple with datas stored inside an array, but you could easily adapt to your case.

const MAX_ITEMS = 3;

class MoreLessExample extends React.Component{
  componentWillMount() {
    this.state = {
      isOpen: false,
    };
    this.items = [
     'Item 1',
     'Item 2',
     'Item 3',
     'Item 4',
     'Item 5',
     'Item 6',
    ];
  }
  
  toggle = () => {
    this.setState({ isOpen: !this.state.isOpen });
  }
  
  getRenderedItems() {
    if (this.state.isOpen) {
      return this.items;
    }
    return this.items.slice(0, MAX_ITEMS);
  }

  render() {
    return(
      <div>
        {this.getRenderedItems().map((item, id) => (
          <div key={id}>{item}</div>
        ))}
        <button onClick={this.toggle}>
          {this.state.isOpen ? 'less' : 'more'}
        </button>
      </div>
    );
  }
}
    
ReactDOM.render(<MoreLessExample />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
like image 121
Thomas Arbona Avatar answered Sep 28 '22 22:09

Thomas Arbona


Here's a Material UI answer:

import { Button, makeStyles } from "@material-ui/core";
import React, { useState } from "react";

const useStyles = makeStyles((theme) => ({
  hidden: {
    display: "-webkit-box",
    WebkitLineClamp: 4,
    overflow: "hidden",
    WebkitBoxOrient: "vertical"
  }
}));
function ReadMore({ children }) {
  const classes = useStyles();
  const [isHidden, setIsHidden] = useState(true);
  return (
    <>
      <div className={isHidden ? classes.hidden : null}>{children}</div>
      <Button size="small" onClick={() => setIsHidden(!isHidden)}>
        {isHidden ? "⬇ More" : "⬆ Less"}
      </Button>
    </>
  );
}

export default ReadMore;

And Implement it like this:

       <ReadMore>
           <Typography>
              Hey World, what's up
           </Typography>
       </ReadMore>
like image 45
Nathan Tarasiuk Avatar answered Sep 28 '22 22:09

Nathan Tarasiuk