The following example covers how to create a Read More component in React JS using useState() hook.
- Basic knowledge of npm & create-react-app command.
- Basic Knowledge of useState() React hooks.
Basic Setup: You will start a new project using create-react-app using the following command:
npx create-react-app react-read-more
Now go to your react-read-more folder by typing the given command in the terminal.
Now create the components folder in src then go to the components folder and create one file ReadMore.js.
Project Structure: The file structure in the project will look like this.
Example: In this example, we will design a Read more component, for that we will need to manipulate the App.js file and other created components file.
Show & Hide text, that’s where the role of useState() hook comes into play. We create a functional component Read More() in which we create a state with first element isReadMore as an initial state having a value of the true and the second element as function setIsReadMore() for updating state. Then a function is created by the name toggleReadMore which sets the value of the state isReadMore to the opposite of its present value whenever it is called.
The value of state isReadMore decides how much text has to be shown with help of a conditional operator. When our state’s value is true, it only shows the first 150 characters of our text with the help of string.slice(). You can choose any number of characters as per your choice. And a ‘read more’ link is also shown at the end. Otherwise, it shows the entire text and a ‘show less’ link at the end.
When we click on the ‘read more’ link, toggleReadMore sets the state value to false with the help of onClick function due to which we see the entire text with a ‘show less’ link at its end. And when we click on ‘show less’ link, it sets the state value to true which only shows a slice of our text with a ‘read more’ link at its end.
We write our text in a different functional component Content() and enclose it with a <ReadMore> tag due to which it becomes a child for ReadMore() function. That’s why we first destructure the children’s property in ReadMore() function so that we can access its value in our text string and implement the logic discussed above.
Step to Run Application: Run the application using the following command from the root directory of the project:
Output: Now open your browser and go to http://localhost:3000/, you will see the following output: