Simple React Accordian with State Hook

3 December 21

Here we'll create a simple accordion component in React v17. We will pass the header and content elements as props. Clicking on the header will toggle the components active state and show or hide the content elements. We will use the React State Hook, introduced in React v16.8, inside our "Function Component" instead of using a traditional class approach. Much more can be learned following the React documentation on State Hooks

Let's take a look at the full code first (.tsx):

import { useState, Fragment } from "react";

interface Props {
  header: any;
  content: any;
}

function Accordion({ header, content }: Props) {
  const [showHideClass, setShowHideClass] = useState("hidden");

  return (
    <Fragment>
      <div
        onClick={() =>
          setShowHideClass(showHideClass === "hidden" ? "" : "hidden")
        }
      >
        {header}
      </div>
      <div className={showHideClass}>{content}</div>
    </Fragment>
  );
}

export default Accordion;

We start by importing the useState Hook. As we want to toggle the visibility of our content elements, the useState Hook will manage the values for us between different interactions in the same view. This line calls useState with an initial value that is set on the showHideClass var and the setShowHideClass function that can be used to update that state

const [showHideClass, setShowHideClass] = useState("hidden");

We want to update the showHideClass value when the wrapper div for our header elements is clicked so we use the onClick event and our setShowHideClass function to update the showHideClass value

onClick={() =>
    setShowHideClass(showHideClass === "hidden" ? "" : "hidden")
}


© 2023 Tom Robson