How to add a like button (React-useState)

Chay Auker
2 min readJul 9, 2021

--

The general idea is set state to boolean and initial state to “false” and then when the user clicks an empty heart, state is updated to true. Next, we set condition to show the heart and make an empty heart the default(“false”). When the user clicks, state is updated to true and a pink heart will be shown. If the heart is clicked again, it will change to an empty heart. Here is the way you can add a like button.

  1. We have to add {useState} from react to call the useState Hook directly inside our component.
import React, { useState } from 'react';

2. Declare a new state variable called “like” and we use useState instead of “this.setState” in React class and set initial state equal to “false” as follows:

3. Add onClick function in text/button which we want the user to click on. In my case, I want to show an empty heart and a pink heart. So I use text(emoji). Now it’s time to update state by setLike to opposite of the prevState or you could write prevLike.

4. The final step is to set ternary state or the conditional operator to show a pink heart if like is true and an empty heart if like is false. This result in a functional like button as seen below:

Thanks for reading my blog and I hope it helpful.

--

--

Chay Auker
Chay Auker

Written by Chay Auker

Software Engineering at Flatiron

No responses yet