React Tabs Example

Building tabs with React is simple, they are just a Button group in disguise. This guide will be similar to our button examples.

First we create a Tab, which is a styled Button with a prop callback to handle the active prop. We set the background: white, border: 0 and outline: 0 to remove the native button look. When it is active, it's back to the normal opacity and we add a border-bottom of 2px.

In order to add toggle functionality we need to keep track of the state of which tab is toggled. We're going to use react hooks for that. We loop through a types array which we use for the text for the Tab, but also as the string to keep track of which Tab is active. We initialize the useState hook with the first type from the array. Then, we loop over the types and render a <Tab>.

We check active, which is the current state, against the type that we loop over. When we click on the Tab, we run our arrow function which calls the setActive setter. This sets the next active Tab to be whatever type we click on.

Menu
Lesson 5/7
import React, { useState } from "react";
import styled from "styled-components";
const Tab = styled.button`
  font-size: 20px;
  padding: 10px 60px;
  cursor: pointer;
  opacity: 0.6;
  background: white;
  border: 0;
  outline: 0;
  ${({ active }) =>
    active &&
    `
    border-bottom: 2px solid black;
    opacity: 1;
  `}
`;
const ButtonGroup = styled.div`
  display: flex;
`;
const types = ["Cash", "Credit Card", "Bitcoin"];
function TabGroup() {
  const [active, setActive] = useState(types[0]);
  return (
    <>
      <ButtonGroup>
        {types.map((type) => (
          <Tab
            key={type}
            active={active === type}
            onClick={() => setActive(type)}
          >
            {type}
          </Tab>
        ))}
      </ButtonGroup>
      <p />
      <p> Your payment selection: {active} </p>
    </>
  );
}

export default function App() {
  return <TabGroup />;
}