HOWTO · React

How to Implement Expand/Collapse Feature in React

Read this guide to learn how to allow users to expand/collapse content by clicking a button. It's a step by step breakdown of a practical example.

On this page

When a page contains long sections or a list of posts, let readers choose what to see. In React, a button can update state, and conditional rendering can use that state to show or hide a container or an individual item. The key is to model each independent visibility choice separately.

Implement an Expand/Collapse Feature in React

Use a boolean state value for one section, or an object keyed by item identifiers when items need independent controls. React renders the matching JSX again after a state update. For a single section, the essential pattern is const [isOpen, setIsOpen] = useState(true), a button with onClick={() => setIsOpen(open => !open)}, and conditional content such as {isOpen && <section>...</section>}. The functional updater reads the latest value, and the && expression renders nothing when the value is false.

The following plain JavaScript model shows how identifiers map to independent visibility values. It is self-contained and does not render a React interface:

Run this JavaScript model:

const postIds = ["post1", "post2", "post3"];
const visible = Object.fromEntries(postIds.map((id) => [id, true]));

visible.post2 = !visible.post2;
console.log(postIds.map((id) => `${id}: ${visible[id]}`).join(", "));
post1: true, post2: false, post3: true

Here is one connected React component that puts these controls together. In an application module, import * as React and useState from react. This uses createElement so the component is valid JavaScript source as well as React code. The supplied execution evidence covers the plain JavaScript model, not React rendering, so this component is illustrative; the runnable JavaScript model above is separate.

function PostList({ posts }) {
  const postIds = posts.map((post) => post.id);
  const [sectionOpen, setSectionOpen] = useState(true);
  const [visible, setVisible] = useState(() =>
    Object.fromEntries(postIds.map((id) => [id, true]))
  );

  function togglePost(id) {
    setVisible((current) => ({ ...current, [id]: !current[id] }));
  }

  function setAllVisible(value) {
    setVisible(Object.fromEntries(postIds.map((id) => [id, value])));
  }

  return React.createElement(
    "section",
    null,
    React.createElement(
      "button",
      { onClick: () => setSectionOpen((open) => !open) },
      sectionOpen ? "Hide posts" : "Show posts"
    ),
    React.createElement(
      "button",
      { onClick: () => setAllVisible(true) },
      "Show All"
    ),
    React.createElement(
      "button",
      { onClick: () => setAllVisible(false) },
      "Hide All"
    ),
    sectionOpen &&
      React.createElement(
        "div",
        null,
        posts.map((post) =>
          React.createElement(
            "article",
            { key: post.id },
            React.createElement(
              "button",
              { onClick: () => togglePost(post.id) },
              visible[post.id] ? "Collapse" : "Expand"
            ),
            visible[post.id] &&
              React.createElement("p", null, post.text)
          )
        )
      )
  );
}

The visible object maps each post identifier to its own boolean. Clicking a post button changes only that entry; spreading current preserves the values for every other post. sectionOpen controls the parent list separately. Closing it hides all rendered children without resetting their values, so reopening it restores whichever posts were visible. The bulk buttons replace every item value with the same boolean. If the parent is closed, Show All still updates those values, but the post content stays hidden until the parent is opened.

Expand/Collapse the Entire Container in React

A parent section has its own visibility state. Toggle that value with a button and conditionally render the whole list inside the parent, for example {sectionOpen && <div>{/* list */}</div>}. When the parent is hidden, none of its children are rendered, even if their parent-held visibility values remain true. Showing the parent again renders the items whose values are still visible.

This distinction applies to where state lives: hiding the parent preserves the per-item visibility values stored in the parent, but conditional rendering unmounts child components and discards any state local to those components. In the example above, the visibility values are held by PostList, so reopening the section restores the same items. If you want closing the parent to reset every item, update those visibility values in the same event handler. Otherwise, keep the parent and item controls independent. The CodeSandbox example is the source article’s interactive demonstration.

Expand/Collapse Specific Posts in React

For each item, use its identifier to look up and update only its own visibility value. A state update should create a new object rather than mutate the existing one. A functional update works well when the next value depends on the previous state: setVisible(current => ({ ...current, [id]: !current[id] })). The computed property [id] selects the entry for the item whose button was clicked, while the spread keeps the other entries unchanged.

Inside the list, a button can call setVisible for its item, and a condition such as {visible[id] && <Post post={post} />} controls that item’s content. If the list can change, derive the initial visibility object from the current identifiers and account for new or removed identifiers when the data changes; a fixed object with hand-written keys only covers the items it names.

Expand or Collapse All Posts in React

Bulk controls set every item value to the same boolean. Derive the object from the identifiers so the list and visibility state stay aligned:

const setAllVisible = (value) => setVisible(Object.fromEntries(postIds.map(id => [id, value])))

Use onClick={() => setAllVisible(false)} for Hide All and onClick={() => setAllVisible(true)} for Show All. These controls update the item values; if the parent container is hidden, Show All changes the child state but the content remains invisible until the parent is shown.

Conclusion

Use one boolean for a single section and an identifier-to-boolean mapping for independent items. Keep parent visibility, item visibility, and bulk actions clear in state so each button changes the intended part of the interface. Styling can change the buttons’ appearance, while the state and conditional rendering determine what readers can see.