React: A like button

A toggle button needs one piece of state, and everything else it shows can be computed from it.

What to build

A like button that shows whether the post is liked and how many likes it has.

Requirements

  • A button with the class like toggles between not liked (text ♡ Like) and liked (text ♥ Liked), with aria-pressed set to match.
  • A p with the class likes shows N likes: 41 when not liked, 42 when liked.

Constraints

Keep only one state variable; compute the count from it.

Example

The first click shows "♥ Liked" and "42 likes"; the second goes back to "♡ Like" and "41 likes".

Why it works

The count is derived from liked during render, so the two can never disagree, which a second state variable for the count could.

Hints

Hint 1

One boolean state for liked; the count shown is the base count plus 1 when liked.

Hint 2

aria-pressed={liked} tells screen readers whether the button is on.

Solution

Show one correct solution (try it yourself first)
import { useState } from "react";

const BASE_LIKES = 41;

export default function App() {
  const [liked, setLiked] = useState(false);
  return (
    <div>
      <button className="like" aria-pressed={liked} onClick={() => setLiked(!liked)}>
        {liked ? "♥ Liked" : "♡ Like"}
      </button>
      <p className="likes">{BASE_LIKES + (liked ? 1 : 0)} likes</p>
    </div>
  );
}

Lesson: State: a component's memory →