How to Implement Chakra UI in ReactJS ?
Chakra UI is a powerful component library for React that is designed and developed by Segun Adebayo to build front-end applications. The Chakra UI comes with simple yet easy-to-understand documentation that gives us guidelines on how to build a reusable component, thereby reducing the time spent on building the process while focusing on other aspects of the app.
The Chakra-UI GitHub repository has 18.6k stars and has been forked 1.5k times. In this article, we’ll learn how to implement the Chakra-UI Dark Mode when you click on the button in React.js.
Key features of Chakra-UI are:
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
Step 3: After creating the ReactJS application, Install the required module using the following command. In this example, we’ll install react-icons as well as a 3rd party library.
npm i @chakra-ui/react @emotion/react@^11 @emotion/styled@^11 framer-motion@^4
npm i react-icons
Project Structure: It will look like the following.
Implementing Dark Mode Switch functionality:
In the App.js file, create a basic layout by importing the Flex, Spacer, VStack, and Heading components.
- VStack: It is a stack component used to create space between the Heading and IconButton elements in a vertical direction.
- Flex and Spacer: Used to create a responsive layout where the child elements occupy 100% of the width keeping the equal spacing between them.
- Heading: It is used to render the headline.
In order to implement the Dark Mode switch, Chakra UI provides a React hook called useColorMode that gives us access to the color mode as well as the toggle color mode. This hook stores the color mode in localStorage and uses that value when the page is loaded. To make sure that our color mode is enabled we need to add ColorModeScript to the index.js file. The value of ColorModeScript is set to light.
Step to Run Application: Run the application using the following command from the root directory of the project:
Output: Now open your browser and go to http://localhost:3000/, you will see the following output: