how to create a read more/less button in react-ag捕鱼王app官网

current location:home > learning > web front-end > react >

how to create a read more/less button in react

author:jiyik last updated:2025/03/10 views:

when building a web application, sometimes we need to display some long text. in this case, a smart design is to display only part of the text and add a show more button for the user to expand the text if needed. when the text is expanded and fully displayed, there is a show lessbutton to collapse it.

the complete example below shows you how to do this.

app preview

creating a read more or less button in react

code

1. create a new react project:

$ npx create-react-app kindacode-example

a bunch of files and folders will be automatically generated. anyway, we only care about 2 files: src/app.js and src/app.css.

  1. in src/app.js , we created a expandabletextreusable component called (we can put it in a separate file to keep things organized). this component can take 2 props: children (the text) and descriptionlength (the maximum number of characters to display initially). here is the full source code and explanation of src/app.js:
// jiyik.com
// src/app.js
import { usestate } from 'react';
import './app.css';

// createa reusable read more/less component
const expandabletext = ({ children, descriptionlength }) => {
  const fulltext = children;

  // set the initial state of the text to be collapsed
  const [isexpanded, setisexpanded] = usestate(false);

  // this function is called when the read more/less button is clicked
  const toggletext = () => {
    setisexpanded(!isexpanded);
  };

  return (
    <pclassname='text'>
      {isexpanded ? fulltext : `${fulltext.slice(0, descriptionlength)}...`}
      <spanonclick={toggletext}classname='toggle-button'>
        {isexpanded ? 'show less' : 'show more'}
      span>p>
  );
};

// main app
functionapp() {
  return (
    <><divclassname='container'><divclassname='card'><h1classname='title'>welcome to jiyik.comh1><p>
            {/* only show 120 characters in the beginning */}
            <expandabletextdescriptionlength={120}>
              lorem ipsum dolor sit amet, consectetur adipiscing elit. donec ut
              egestas mauris. maecenas leo mauris, accumsan vel velit ac,
              blandit lobortis est. vivamus in erat ac magna faucibus placerat
              eget non ligula. aliquam consequat rhoncus turpis a convallis.
              pellentesque ac sapien rhoncus, congue nibh eget, finibus turpis.
              aenean volutpat malesuada augue, at lacinia dolor volutpat congue.
              ut sit amet nunc ac arcu imperdiet iaculis. mauris sit amet quam
              ut nisi blandit blandit congue nec lorem. mauris viverra, quam non
              aliquet pellentesque, lorem risus fermentum mi, a mollis turpis
              velit vitae nulla. proin auctor, elit a rhoncus vulputate, est
              magna facilisis ipsum, non mattis sem odio in neque. cras at
              ultricies eros. ut risus turpis, consequat sed auctor nec, rutrum
              id mauris.
            expandabletext>p>div><divclassname='card'><h1classname='title'>just a dummy titleh1><p>
            {/* show 200 characters in the beginning */}
            <expandabletextdescriptionlength={200}>
              aliquam maximus, purus vel tempus luctus, libero ipsum consectetur
              purus, eu efficitur mi nunc sed purus. etiam tristique sit amet
              nisi vel rhoncus. vestibulum porta, metus sit amet tincidunt
              malesuada, dui sapien egestas magna, quis viverra turpis sapien a
              dolor. fusce ultrices eros eget tincidunt viverra. ut a dapibus
              erat, vel cursus odio. phasellus erat enim, volutpat vel lacus eu,
              aliquam sodales turpis. fusce ipsum ex, vehicula tempor accumsan
              nec, gravida at eros. in aliquam, metus id mollis interdum, nunc
              sem dignissim quam, non iaculis tortor erat nec eros. nunc
              sollicitudin ac dolor eget lobortis. aenean suscipit rutrum dolor
              in euismod. curabitur quis dapibus lectus. mauris enim leo,
              condimentum ac elit sit amet, iaculis vulputate sem.
            expandabletext>p>div>div>
  );
}
exportdefaultapp;

css is an important part of this demo. delete all the default code in src/app.css and add the following: /* src/app.css */

.container {
  width: 80%;
  margin: 50px auto;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.card {
  width: 43%;
  padding: 15px 20px;
  background: #fffde7;
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2);
  border-radius: 10px;
}

.text {
  width: 100%;
}

/* style the read more/less button */
.toggle-button {
  margin-left: 7px;
  color: blue;
  cursor: pointer;
}

.toggle-button:hover {
  color: red;
  text-decoration: underline;
}

done. now let's get our application up and running and move on http://localhost:3000 to testing it.

for reprinting, please send an email to 1244347461@qq.com for approval. after obtaining the author's consent, kindly include the source as a link.

article url:

related articles

insert style tags into react components

publish date:2025/03/10 views:66 category:react

要在 react 组件中插入样式标签,请将我们的 css 包装在样式标签中的模板字符串中。 花括号之间的表达式将被评估并添加样式。

how to listen to state changes in react

publish date:2025/03/10 views:179 category:react

使用 useeffect 钩子来监听 react 中的状态变化。 我们可以将要跟踪的状态变量添加到挂钩的依赖项数组中,并且每次状态变量更改时都会运行 useeffect 钩子中的逻辑。

get parent height and width in react

publish date:2025/03/10 views:158 category:react

在 react 中获取父级的高度和宽度: 在元素上设置 ref 属性。 在 useeffect 钩子中,更新高度和宽度的状态变量。 使用 offsetheight 和 offsetwidth 属性来获取元素的高度和宽度。

get the value of an input field in react

publish date:2025/03/10 views:179 category:react

要在 react 中获取输入字段的值: 声明一个跟踪输入字段值的状态变量。 将 onchange 属性添加到输入字段。 使用 event.target.value 获取输入字段的值并更新状态变量。

rendering nested arrays in react using map()

publish date:2025/03/10 views:71 category:react

使用 map() 渲染嵌套数组: 使用 map() 方法迭代外部数组。 在每次迭代中,调用嵌套数组的 map()方法。 渲染嵌套数组的元素。

publish date:2025/03/10 views:118 category:react

在 react 中获取表单提交的输入值: 将输入字段的值存储在状态变量中。在表单元素上设置 onsubmit 属性。 在我们的 handlesubmit 函数中访问输入字段的值。

publish date:2025/03/10 views:130 category:react

在 react 中为 body 元素添加一个类: 在 useeffect 或事件处理程序中以 document.body 的形式访问 body 元素。 使用 classlist.add() 方法将类添加到 body 标记。 例如,document.body.classlist.add('my-class'

clearing the value of an input field in react.js

publish date:2025/03/10 views:119 category:react

要在 react 中清除输入字段的值:将输入的值存储在状态变量中。 当某个事件发生时,将状态变量设置为空字符串。对于不受控制的组件,将 ref 的值设置为空字符串,例如 ref.current.va

deleting keys from state object in react

publish date:2025/03/10 views:62 category:react

要从 react 状态对象中删除键: 使用 usestate 挂钩来存储状态对象。 解构对象的键和其余属性。 将状态设置为其余属性。

scan to read all tech tutorials

social media
  • https://www.github.com/onmpw
  • qq:1244347461

recommended

tags

scan the code
easier access tutorial
网站地图