How to create a Read More component in ReactJS?
Creating a Read More component in React JS refers to hiding and displaying the text content on the page. It can be achieved by setting the state variable and display the content accordingly.
Prerequisites
Approach
To create a Read More component in React JS we will use useState to set the display for text content on the web page. At the initial or hidden state only the first hundred letters will be visible will be managed using the string slice method and when read more is clicked the state will be updated and the content will be visible on the page.
Creating react Application
Step 1: You will start a new project using create-react-app using the following command:
npx create-react-app react-read-more
Step 2: Now go to your react-read-more folder by typing the given command in the terminal.
cd react-read-more
Project Structure:
The file structure in the project will look like this.
Example: Implementing read more component with the help of useState in react.
Javascript
// Filename - App.js import Content from "./components/ReadMore" ; import "../App.css" ; function App() { return ( <div className= "App" > <h1 className= "geeks" >GeeksforGeeks</h1> <h3> React example to Create Read More Component </h3> <Content /> </div> ); } export default App; |
Javascript
// Filename - components/ReadMore.js import React, { useState } from "react" ; const ReadMore = ({ children }) => { const text = children; const [isReadMore, setIsReadMore] = useState( true ); const toggleReadMore = () => { setIsReadMore(!isReadMore); }; return ( <p className= "text" > {isReadMore ? text.slice(0, 100) : text} <span onClick={toggleReadMore} className= "read-or-hide" style={{ color: "green" }} > {isReadMore ? "...read more" : " show less" } </span> </p> ); }; const Content = () => { return ( <div className= "container" > { /* <h2> */ } <ReadMore> GeeksforGeeks: A Computer Science portal for geeks. It contains well written, well thought and well explained computer science, programming articles and quizzes. It provides a variety of services for you to learn, so thrive and also have fun! Free Tutorials, Millions of Articles, Live, Online and Classroom Courses ,Frequent Coding Competitions, Webinars by Industry Experts, Internship opportunities, and Job Opportunities. Knowledge is power! </ReadMore> { /* </h2> */ } </div> ); }; export default Content; |
CSS
/* Filename - App.css */ .App { text-align : center ; margin : auto ; } .container { text-align : center ; margin : auto ; /* justify-content: space-evenly; */ max-width : 30 rem; } .geeks { color : green ; } .text { display : inline ; width : 90% ; } .read-or- hide { color : rgb ( 192 , 192 , 192 ); cursor : pointer ; } |
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output: