React-Create a show more/less button

Chay Auker
2 min readJun 17, 2021

--

When I read something on websites and saw a show more/less button, I thought it was a good feature because it makes everything on the website look more clean. So I would like to share an easy way to insert a show more/less button by using React- State Hook.

  1. Create React App component and add React, {useState}
  2. Create const showMore and setShowMore as follow:
const [showMore, setShowMore] = useState(false);

3. Create condition and the button where you want to show text as follow:

In this case, it means if showMore is true, it will show the text. If showMore is false, only 250 characters will be shown. Here is how to use substring function: substring(indexStart, indexEnd) . You can check more information on how to use the function in this link MDN.

<h6>
{showMore ? text : `${text.substring(0, 250)}`}
<button className="btn">Show more</button>
</h6>

4. Set onClick function to setShowMore(!showMore). When the user clicks it will alternate between hiding and showing the text.

<button className="btn" onClick={() => setShowMore(!showMore)}>Show more</button>

5. Now the button works and will expand and contract. The next step is to change the button’s wording to Show more/Show less. By adding a condition in the button as follow:

{showMore ? "Show less" : "Show more"}

Here is the final code. It’s easy, isn’t it?

Finally when we click show more, the text will be shown and the button will be changed to Show less.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Chay Auker
Chay Auker

Written by Chay Auker

Software Engineering at Flatiron

Responses (4)

Write a response