How to create a read more/less button in React
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 Less
button to collapse it.
The complete example below shows you how to do this.
App Preview
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.
-
In src/App.js , we created a
ExpandableText
reusable 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 (
<p className='text'>
{isExpanded ? fullText : `${fullText.slice(0, descriptionLength)}...`}
<span onClick={toggleText} className='toggle-button'>
{isExpanded ? 'Show less' : 'Show more'}
</span>
</p>
);
};
// Main App
function App() {
return (
<>
<div className='container'>
<div className='card'>
<h1 className='title'>Welcome To jiyik.com</h1>
<p>
{/* Only show 120 characters in the beginning */}
<ExpandableText descriptionLength={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>
<div className='card'>
<h1 className='title'>Just A Dummy Title</h1>
<p>
{/* Show 200 characters in the beginning */}
<ExpandableText descriptionLength={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>
</>
);
}
export default App;
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.
Related Articles
React Tutorial - Transferring Props
Publish Date:2025/03/16 Views:185 Category:React
-
React transfers Props. Props are generated when components are encapsulated. Components expose some properties (Props) to the outside world to complete some functions.
React Tutorial: Props Anti-Pattern
Publish Date:2025/03/16 Views:183 Category:React
-
React's Props anti-pattern, using Props to generate state in getInitialState is an anti-pattern - Anti-Pattern.
React Tutorial - Props Validation
Publish Date:2025/03/16 Views:99 Category:React
-
Props validation is a very useful way to use components correctly. It can avoid many bugs and problems as your application becomes more and more complex. In addition, it can make your program more readable.
React tutorial: Types of Props for child components
Publish Date:2025/03/16 Views:170 Category:React
-
Usually, the child components of a React component are a group, that is, the child components are an array. Introduction to Type of the Children Props.
How to solve the error Uncaught TypeError: Cannot read properties of undefined in
Publish Date:2025/03/16 Views:150 Category:React
-
In the process of React development, we often encounter some errors. Here we look at an error reported in App.js. The error is as follows: App.js:69 Uncaught TypeError: Cannot read properties of undefined (reading 'setState') at onInput
Why do you need to bind event handlers in React Class Components?
Publish Date:2025/03/16 Views:58 Category:React
-
When using React, we must have come across control components and event handlers. We need to use `.bind()` in the constructor of the custom component to bind these methods to the component instance. As shown in the following code:
Solution to the error "does not contain a default export" in React
Publish Date:2025/03/16 Views:187 Category:React
-
When we try to use `default import` to import from a module that does not have a `default export`, we get a "does not contain a default export" error. To fix the error, make sure the module has named exports and wrap the import in curly braces, e.g.
Error in React: Attempted import error 'X' is not exported from Solution
Publish Date:2025/03/16 Views:76 Category:React
-
In React, the error “Attempted import error 'X' is not exported from” in React.js occurs when we try to import a named import that does not exist in the specified file. To fix the error, make sure the module has named exports and you have not obfu
Solve the Module not found: Can't resolve 'react-bootstrap' error
Publish Date:2025/03/16 Views:85 Category:React
-
To resolve the error "Module not found: Error: Can't resolve 'react-bootstrap'", make sure to install the react-bootstrap package by opening a terminal in the root directory of the project and running the command `npm install react-bootstrap bootstrap