Published on

How To Create A Bar Chart With TailwindCSS And AlpineJS With Tailwind CSS From Scratch

Bar Chart with TailwindCSS and AlpineJS

What is Tailwind CSS?

Tailwind CSS is a utility-first CSS framework that enables developers to create responsive and customizable designs quickly. It provides a set of pre-defined CSS classes that can be used to style HTML elements. Tailwind CSS is gaining popularity among developers due to its flexibility and ease of use.

The description of Bar Chart with TailwindCSS and AlpineJS ui component

A bar chart is a graphical representation of data in which bars of different heights or lengths are used to represent different values. In this tutorial, we will create a bar chart using Tailwind CSS and AlpineJS. AlpineJS is a lightweight JavaScript framework that allows you to create reactive and interactive user interfaces.

Why use Tailwind CSS to create a Bar Chart with TailwindCSS and AlpineJS ui component?

Tailwind CSS provides a set of pre-defined classes that can be used to style HTML elements. This makes it easier to create a bar chart without having to write custom CSS. Additionally, Tailwind CSS is highly customizable, which means that you can easily modify the styles to match your design requirements.

AlpineJS is a lightweight JavaScript framework that allows you to create reactive and interactive user interfaces. It provides a set of directives that can be used to add interactivity to HTML elements. This makes it easier to create a bar chart that responds to user input.

The preview of Bar Chart with TailwindCSS and AlpineJS ui component.

To create a bar chart with Tailwind CSS and AlpineJS, we will use a combination of HTML, CSS, and JavaScript. The bar chart will be responsive and will adjust its size based on the screen size.

Free download of the Bar Chart with TailwindCSS and AlpineJS's source code

The source code of Bar Chart with TailwindCSS and AlpineJS ui component.

To create a bar chart with Tailwind CSS and AlpineJS, we will use the following HTML, CSS, and JavaScript code:

<div class="sans-serif w-lg min-h-screen bg-gray-200 antialiased ">
  <link
    href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500;600;700&display=swap"
    rel="stylesheet"
  />
  <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet" />
  <script
    src="https://cdn.jsdelivr.net/gh/alpinejs/[email protected]/dist/alpine.min.js"
    defer
  ></script>
  <style>
    body {
      font-family: 'IBM Plex Mono', sans-serif;
    }
    [x-cloak] {
      display: none;
    }

    .line {
      background: repeating-linear-gradient(to bottom, #eee, #eee 1px, #fff 1px, #fff 8%);
    }
    .tick {
      background: repeating-linear-gradient(to right, #eee, #eee 1px, #fff 1px, #fff 5%);
    }
  </style>

  <div x-data="app()" x-cloak class="px-4">
    <div class="mx-auto max-w-lg py-10">
      <div class="rounded-lg bg-white p-6 shadow">
        <div class="md:flex md:items-center md:justify-between">
          <div>
            <h2 class="text-xl font-bold leading-tight text-gray-800">Product Sales</h2>
            <p class="mb-2 text-sm text-gray-600">Monthly Average</p>
          </div>

          <!-- Legends -->
          <div class="mb-4">
            <div class="flex items-center">
              <div class="mr-2 h-2 w-2 rounded-full bg-blue-600"></div>
              <div class="text-sm text-gray-700">Sales</div>
            </div>
          </div>
        </div>

        <div class="line relative my-8">
          <!-- Tooltip -->
          <template x-if="tooltipOpen == true">
            <div
              x-ref="tooltipContainer"
              class="absolute z-10 m-0 block h-auto rounded-lg p-0 shadow-lg"
              :style="`bottom: ${tooltipY}px; left: ${tooltipX}px`"
            >
              <div class="shadow-xs rounded-lg bg-white p-2">
                <div class="flex items-center justify-between text-sm">
                  <div>Sales:</div>
                  <div class="ml-2 font-bold">
                    <span x-html="tooltipContent"></span>
                  </div>
                </div>
              </div>
            </div>
          </template>

          <!-- Bar Chart -->
          <div class="-mx-2 mb-2 flex items-end">
            <template x-for="data in chartData">
              <div class="w-1/6 px-2">
                <div
                  :style="`height: ${data}px`"
                  class="relative bg-blue-600 transition duration-200 ease-in hover:bg-blue-400"
                  @mouseenter="showTooltip($event); tooltipOpen = true"
                  @mouseleave="hideTooltip($event)"
                >
                  <div
                    x-text="data"
                    class="absolute top-0 left-0 right-0 -mt-6 text-center text-sm text-gray-800"
                  ></div>
                </div>
              </div>
            </template>
          </div>

          <!-- Labels -->
          <div
            class="mx-auto border-t border-gray-400"
            :style="`height: 1px; width: ${ 100 - 1/chartData.length*100 + 3}%`"
          ></div>
          <div class="-mx-2 flex items-end">
            <template x-for="data in labels">
              <div class="w-1/6 px-2">
                <div class="relative bg-red-600">
                  <div
                    class="absolute top-0 left-0 right-0 mx-auto -mt-px h-2 bg-gray-400 text-center"
                    style="width: 1px"
                  ></div>
                  <div
                    x-text="data"
                    class="absolute top-0 left-0 right-0 mt-3 text-center text-sm text-gray-700"
                  ></div>
                </div>
              </div>
            </template>
          </div>
        </div>
      </div>
    </div>
  </div>

  <script>
    function app() {
      return {
        chartData: [112, 10, 225, 134, 101, 80, 50, 100, 200],
        labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep'],

        tooltipContent: '',
        tooltipOpen: false,
        tooltipX: 0,
        tooltipY: 0,
        showTooltip(e) {
          console.log(e)
          this.tooltipContent = e.target.textContent
          this.tooltipX = e.target.offsetLeft - e.target.clientWidth
          this.tooltipY = e.target.clientHeight + e.target.clientWidth
        },
        hideTooltip(e) {
          this.tooltipContent = ''
          this.tooltipOpen = false
          this.tooltipX = 0
          this.tooltipY = 0
        },
      }
    }
  </script>
</div>

How to create a Bar Chart with TailwindCSS and AlpineJS with Tailwind CSS?

To create a bar chart with Tailwind CSS and AlpineJS, follow these steps:

Step 1: Set up the HTML structure

The first step is to set up the HTML structure for the bar chart. We will use a div element with a class of "chart" to contain the chart.

<div class="chart"></div>

Step 2: Add the data

Next, we will add the data to the chart. We will use a data attribute to store the data for each bar. The data will be in the form of a comma-separated list of values.

<div class="chart" data-bars="10,20,30,40,50"></div>

Step 3: Style the chart

We will use Tailwind CSS classes to style the chart. We will set the width and height of the chart and add a background color.

.chart {
  width: 100%;
  height: 300px;
  background-color: #f5f5f5;
}

Step 4: Add the bars

Next, we will add the bars to the chart. We will use a for loop to iterate over the data and create a div element for each bar. We will use Tailwind CSS classes to style the bars.

<div class="chart" data-bars="10,20,30,40,50">
  @for($i = 0; $i < count($bars); $i++)
    <div class="bar h-8 bg-blue-500"></div>
  @endfor
</div>

Step 5: Add interactivity with AlpineJS

Finally, we will add interactivity to the chart using AlpineJS. We will use the x-data directive to create a reactive data property for the chart. We will use the x-init directive to initialize the chart data from the data attribute. We will use the x-for directive to iterate over the data and create a div element for each bar. We will use the x-bind directive to bind the height of each bar to its corresponding data value.

<div class="chart" data-bars="10,20,30,40,50" x-data="{ bars: [] }" x-init="bars = $el.dataset.bars.split(',').map(Number)">
  <template x-for="(bar, index) in bars">
    <div class="bar h-8 bg-blue-500" x-bind:style="'height:' + bar + '%'"></div>
  </template>
</div>

Conclusion

Creating a bar chart with Tailwind CSS and AlpineJS is a straightforward process. Tailwind CSS provides a set of pre-defined classes that can be used to style HTML elements, while AlpineJS allows you to add interactivity to your user interfaces. By combining these two technologies, you can create responsive and interactive bar charts quickly and easily.