How to Implement Chakra UI Button Loading State in Next.js

Introduction

Chakra UI, a popular React component library, offers a convenient way to implement button loading states. In this article, we'll explore how to use Chakra UI's Button component with loading state in a Next.js application.Pass the isLoading prop to show its loading state. By default, the button will show a spinner and leave the button's width unchanged.

Prerequisites

  • Node.js
  • Next.js:
  • Chakra UI

Implement Chakra UI Button Loading State in Next.js

Step 1. Create the Next Js Project using the following command 

npx create-next-app my-test-app

Step 2. Install Chakra UI and its dependencies using the following command:

npm install @chakra-ui/react @emotion/react @emotion/styled framer-motion

Step 3. Install Chakra UI Icons for adding icons to your buttons:

npm install @chakra-ui/icons

Step 4

Now, let's create a Chakra UI Button component with a loading state in a Next.js application.

Create Chakra UI component :

import { Button, CircularProgress } from '@chakra-ui/react';
import { AddIcon } from '@chakra-ui/icons';
import { useState } from 'react';

const MyDemoPage = () => {
const [isLoading, setIsLoading] = useState(false);
const handleClick = () => {
  setIsLoading(true);


  setTimeout(() => {
    setIsLoading(false);
  }, 2000); 
};

return (
  <Button
    onClick={handleClick}
    isLoading={isLoading}
    loadingText="Loading..."
    leftIcon={<AddIcon />}
  >
    Add Item
  </Button>
);
}

export default MyDemoPage

Step 5. Run the application using the following command.

npm start

Chakra UI Button Loading State in Next.js

Summary

In this article, we learned about how Chakra UI Button Loading State can be implemented in Next Js.