Chakra UI React - Coding a Simple Landing Page
Tags: react, chankra, tutorial, webdev
Published: 2022-05-07 12:58:23

---
title: Chakra UI React - Coding a Simple Landing Page
published: true
description: How to code a simple landing page in Chakra and React - A comprehensive tutorial.
tags: react, chankra, tutorial, webdev
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pr7542uf50kdq0upizwc.jpg
canonical_url: https://blog.appseed.us/chakra-ui-react-coding-landing-page/
---
Hello Coders! 

This article explains [How to use the Chakra UI](https://blog.appseed.us/chakra-ui-react-coding-landing-page/) React Library and code a simple, responsive landing page. The page will be built with **Chakra** components only, no HTML element will be used. For newcomers, `Chakra UI` is a library that allows you to build stunning and modern web applications using various layout components. It differs from other UI frameworks in that it offers `accessibility` and `dark mode` support by default. 

> Thanks for Reading! 

- 👉 [Chakra UI Landing Page](https://react-chakra-ui-landing-page.appseed-srv1.com/) - Sample LIVE Demo
- 👉 [Chakra UI Landing Page](https://github.com/app-generator/sample-react-chakra-ui-introduction) - Source Code (all components)
- 🎁 More [Chakra UI Templates](https://www.admin-dashboards.com/chakra-ui-starters-open-source-and-free/) (all free and open-source)

---

![Coding a Simple Landing Page with Chakra UI and React.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s9l9m7htq4sa2l408705.gif)

---

## ✨ Topics

In this article, you will learn about different Chakra UI components and how to use them by building a fully responsive web page with React.js.

With no further ado, let's see an overview of what you'll be learning in this article.

- 👉 5 Key features of `Chakra UI`
- 👉 `How to setup Chakra UI` in Create-React-App
- 👉 How to `style Chakra UI components`
- 👉 Coding the `Nav component`
- 👉 Coding the `Hero component`
- 👉 Coding the `About Us component`
- 👉 Coding the `Services component`
- 👉 Coding the `Footer component`
- 👉 How to enable `Chakra UI Dark Mode`
- 🎁 Conclusions & `Free Resources`

---

## ✨ Chakra UI, Key Features

The layout components provided by Chakra UI are modern and accessible. Meaning users with disabilities can access your website without any constraints regardless of their disability. With Chakra UI, disability is not a hindrance to having a great user experience.

> 🚀 **Highly customizable**

Every web component provided by Chakra UI is highly customizable. You have complete control over their appearance and behavior. Chakra UI allows you to edit and extend the UI components to fit your needs. For example, Chakra UI has only a few icons but allows you to extend the icon library easily.

> 🚀 **Themes and Dark mode support**

Manually providing different theme options for users on your website can be a tedious task. But with Chakra UI, you don't have to do much coding because all the components have in-built support for dark mode.

You can also create custom themes or edit the default themes provided by Chakra UI.

> 🚀 **Simple learning curve**

Chakra UI has a short learning curve. You don't have to spend much time learning how to use the web components. If you are familiar with CSS or other UI libraries like Tailwind CSS, you will pick up Chakra UI within a few minutes of reading the documentation.

> 🚀 **Excellent documentation**

Chakra UI has excellent documentation, easy for new and existing users to navigate and learn about its features rapidly. Chakra UI documentation is developer and user-friendly. With Chakra UI, you are most likely not running into UI-related bugs.

---

## ✨ Setting up Chakra UI with `CRA`

As said earlier, I will guide you through building a fully responsive and modern website using Chakra UI. Before that, let's install the necessary tools needed.

- Open your terminal
- Run the code below to install Chakra UI automatically with create-react-app (CRA).

```bash
$ npx create-react-app my-app --template @chakra-ui 
```

Otherwise, you can install `CRA` and `Chakra UI` manually:

```bash
$ npx create-react-app react-chakra
$ npm i @chakra-ui/react @emotion/react@^11 @emotion/styled@^11 framer-motion@^6 
```

Open `index.js` file in your CRA project and add `ChakraProvider`:

```javascript
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import { ChakraProvider } from '@chakra-ui/react';
 
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <ChakraProvider>
    <App />
  </ChakraProvider>
); 
```

Open `App.js` file and copy the following code:

```javascript
import AboutUs from './components/AboutUs';
import ContactUs from './components/ContactUs';
import Footer from './components/Footer';
import Hero from './components/Hero';
import Nav from './components/Nav';
import Services from './components/Services';
import Testimonials from './components/Testimonials';
 
function App() {
  return (
    <div>
      <Nav />
      <Hero />
      <AboutUs />
      <Services />
      <Testimonials />
      <ContactUs />
      <Footer />
    </div>
  );
}
 
export default App 
```

**From the code snippet above:**

- I created the structure for the web page by dividing it into 7 different components - Nav, Hero, About Us, etc.
- Go ahead and create these components in the src/components folder.

Once you've successfully set up your `CRA` project with `Chakra UI`, let's learn how to style Chakra UI components.

---

## ✨ How to style Chakra Components

In contrast to other UI libraries, Chakra UI components are styled by passing CSS attributes as props to web components. This makes it easier to edit the layout of different web components while reducing the number of styles you have to write.

**Let's take a look at an example:**

```javascript
import React from 'react';
import { Text, Box, Flex } from '@chakra-ui/react';
 
const Example = () => {
  return (
    <Box>
      <Flex
        alignItems="center"
        height="100vh"
        bg="red.400"
        justifyContent="space-between"
        p="16"
      >
        <Text fontSize="3xl" color="green.700">
          Hello World
        </Text>
        <Text>Welcome to Chakra UI</Text>
      </Flex>
    </Box>
  );
};
 
export default Example; 
```

**From the code snippet above:**

- I imported three components from `Chakra UI`.
- Text renders text on our web pages. It accepts different props such as `fontSize`, `color`, and other text-related attributes.
- `Chakra UI` has a library of colors that are used in this format - color. opacity. For example, blue.900 means a very dark variant of `blue` and `blue.50` is the lightest. Check the docs for more.
- `Box` is the same as the div tag.
- `Flex` represents a div tag with a display of flex. It also accepts different props - `bg` stands for background color, and padding.

We can now start coding each section of the webpage. As we go further in this article, you will learn more about the different components available in Chakra UI.

---

## ✨ Coding the Nav Component

This component contains the navigation bar - logo, and menu bar of the webpage.

**Let's examine the code below:**

```javascript
import React, { useState } from 'react';
import { Text, Flex, Spacer } from '@chakra-ui/react';
 
const Nav = () => {
  const [scroll, setScroll] = useState(false);
 
  const changeScroll = () =>
    document.body.scrollTop > 80 || document.documentElement.scrollTop > 80
      ? setScroll(true)
      : setScroll(false);
 
  window.addEventListener('scroll', changeScroll);
 
  return (
    <Flex
      h="10vh"
      alignItems="center"
      p="6"
      boxShadow={scroll ? 'base' : 'none'}
      position="sticky"
      top="0"
      zIndex="sticky"
      w="full"
    >
      <Text fontSize="xl" fontWeight="bold">
        Chakra Sample
      </Text>
 
      <Spacer />
 
      <Flex alignItems="center">
        <Text fontSize="md" mr="10">
          About
        </Text>
        <Text fontSize="md">More Apps</Text>
      </Flex>
    </Flex>
  );
};
 
export default Nav; 
```

**From the code snippet above:**

- I imported the `Text`, `Flex`, and `Spacer` components from Chakra UI.
- The Spacer component creates space between the flex items, similar to the justify-content: space-between CSS property.
- The `changeScroll()` function elevates the navigation bar when the user scrolls down the webpage.
- The `scroll state` is used to toggle the boxShadow property when the user scrolls through the webpage.

---

## ✨ Building the `Hero Component`

Here, you will learn about the `useMediaQuery` hook, different breakpoints, and how the screen responds to various screen sizes in Chakra UI.

![React Chakra UI Sample - Hero Component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6tt6jh1uvc2l8vyob6r1.png)

---

```javascript
import {
  Box,
  Button,
  Flex,
  Image,
  Spacer,
  Text,
  useMediaQuery,
} from '@chakra-ui/react';
import React from 'react';
import chakraHero from '../assets/chakraHero.jpg';
 
const Hero = () => {
  const [isLargerThan62] = useMediaQuery('(min-width: 62em)');
 
  return (
    <Flex
      alignItems="center"
      w="full"
      px={isLargerThan62 ? '16' : '6'}
      py="16"
      minHeight="90vh"
      justifyContent="space-between"
      flexDirection={isLargerThan62 ? 'row' : 'column'}
    >
      <Box mr={isLargerThan62 ? '6' : '0'} w={isLargerThan62 ? '60%' : 'full'}>
        <Text
          fontSize={isLargerThan62 ? '5xl' : '4xl'}
          fontWeight="bold"
          mb="4"
        >
          {' '}
          Let's scale your business
        </Text>
 
        <Text mb="6" fontSize={isLargerThan62 ? 'lg' : 'base'} opacity={0.7}>
          Hire professionals who will help your business make 10X
        </Text>
 
        <Button
          w="200px"
          colorScheme="blue"
          variant="solid"
          h="50px"
          size={isLargerThan62 ? 'lg' : 'md'}
          mb={isLargerThan62 ? '0' : '10'}
        >
          HIRE US
        </Button>
      </Box>
 
      <Spacer />
 
      <Flex
        w={isLargerThan62 ? '40%' : 'full'}
        alignItems="center"
        justifyContent="center"
      >
        <Image src={chakraHero} alt="Chakra UI" />
      </Flex>
    </Flex>
  );
};
 
export default Hero;
```

**From the code snippet above:**

- The `Hero component` returns the parent component, Flex which contains a Box and another Flex component.
- The `Box component` contains the Text and Button components, while the child Flex component contains the image.
- I also imported the `useMediaQuery` hook that checks if the user's screen size matches the specified breakpoint. It returns an array of boolean values representing each breakpoint.
- The variable `isLargerThan62` is false if the screen size is smaller than 62em and true if otherwise.
- `isLargerThan62` is also destructured from the array of boolean values returned from the useMediaQuery hook. Below are the pre-defined breakpoints available in Chakra UI. These breakpoints can also be extended or customized.

---

## ✨ Coding About Us Component

In this section, you will learn how to use a third-party icon library in Chakra UI while building the `AboutUs component`.

---

![React Chakra UI Sample - About US Component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uxd5j7wcmamnso0r0qa2.png)

---
 
**Let's examine the code below**:

```javascript
import React from 'react';
import { Flex, Spacer, Text, useMediaQuery, Icon } from '@chakra-ui/react';
import { FaTools, FaHandshake, FaStar } from 'react-icons/fa';
 
const AboutUs = () => {
  const [isLargerThan48] = useMediaQuery('(min-width: 48em)');
 
  const array = [
    {
      id: 1,
      text: ' Solving world ... [truncated]',
      icon: FaTools,
    },
    {
      id: 2,
      text: 'Through team work, ... [truncated]',
      icon: FaHandshake,
    },
    {
      id: 3,
      text: 'Five star service with ... [truncated]',
      icon: FaStar,
    },
  ];
 
  return (
    <Flex
      minH="70vh"
      alignItems="center"
      justifyContent="space-between"
      w="full"
      py="16"
      px={isLargerThan48 ? '16' : '6'}
      flexWrap="wrap"
      flexDirection={isLargerThan48 ? 'row' : 'column'}
    >
      {array.map((arr) => (
        <>
          <Flex
            height="300px"
            bg="blackAlpha.200"
            width={isLargerThan48 ? '32%' : 'full'}
            shadow="md"
            p="6"
            alignItems="center"
            justifyContent="center"
            borderRadius="md"
            flexDirection="column"
            textAlign="center"
            mb={isLargerThan48 ? '0' : '4'}
            border="1px solid #C4DDFF"
          >
            <Icon as={arr.icon} boxSize={14} color="blue.600" mb="5" />
            <Text>{arr.text}</Text>
          </Flex>
 
          <Spacer />
        </>
      ))}
    </Flex>
  );
};
 
export default AboutUs; 
``` 

**From the code snippet above:**

- I installed a package called react-icons and imported `FaTools`, `FaHandshake`, and `FaStar`.
- `Chakra UI` does not have a vast library of icons, but it provides a simple way to extend the package. Read more about using a third-party icon library.
- `useMediaQuery` checks if the screen size is bigger than 48em. isLargerThan48 holds the boolean value returned from useMediaQuery.
- Array holds the content to display on the screen, then maps the contents into view.

---

## ✨ Services Component

This component uses an image on the left that might be used to present the team behind your project.  

---

![React Chakra UI Sample - Services Component.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9qy14rfnsgwrhdncdrkf.png)

---
 
**Let's analyze the code below:**

```javascript
import {
  Flex,
  Spacer,
  Image,
  Text,
  Button,
  useMediaQuery,
} from '@chakra-ui/react';
import React from 'react';
import teamImage from '../assets/teamImage.jpg';
 
const Services = () => {
  const [isLargerThan62] = useMediaQuery('(min-width: 62em)');
 
  return (
    <Flex
      width="full"
      minHeight="70vh"
      alignItems="center"
      px={isLargerThan62 ? '16' : '6'}
      py="16"
      justifyContent="center"
      flexDirection={isLargerThan62 ? 'row' : 'column'}
    >
      <Flex
        w={isLargerThan62 ? '40%' : 'full'}
        mb={isLargerThan62 ? '0' : '6'}
        alignItems="center"
        justifyContent="center"
      >
        <Image src={teamImage} alt="Chakra Team" w="full" />
      </Flex>
 
      <Spacer />
 
      <Flex
        w={isLargerThan62 ? '60%' : 'full'}
        flexDirection="column"
        ml={isLargerThan62 ? '7' : '0'}
      >
        <Text fontSize={isLargerThan62 ? '5xl' : '4xl'} fontWeight="bold">
          We build, We revive
        </Text>
 
        <Text mb="6" opacity="0.8">
          Your business needs to be .. [truncated]
        </Text>
 
        <Button width="200px" size="lg" colorScheme="blue">
          CONTACT US
        </Button>
      </Flex>
    </Flex>
  );
};
 
export default Services; 
```

From the code above, `Chakra UI` provides an Image component that is used to display images. It also accepts the same props as the IMG tag in HTML.

---

## ✨ Coding the Footer Component

In this section, we will build the footer section of the webpage and learn about the Link component in `Chakra UI`.

---

![React Chakra UI Sample - Footer Component.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g367aboxx42hxclqwnak.png)

---
 
```javascript
import { Flex, Text, Link } from '@chakra-ui/react';
import React from 'react';
 
const Footer = () => {
  return (
    <Flex
      w="full"
      bg="blackAlpha.50"
      minHeight="20vh"
      flexDirection="column"
      alignItems="center"
      textAlign="center"
      justifyContent="center"
    >
      <Text mb="3">
        Provided by{' '}
        <Link href="https://appseed.us" isExternal color="blue.500">
          AppSeed
        </Link>
      </Text>
      <Text opacity="0.5">Open-Source Sample - Buit with Chakra UI</Text>
    </Flex>
  );
};
 
export default Footer; 
```

**From the code snippet above:**

- `Link` is a component that is used to navigate to various parts of the website or an external resource.
- `Link` accepts an `isExternal` prop for links to external resources.

---

## ✨ Enable Dark Mode

This section explains how to enable dark mode and add custom color schemes using the `useColorModeValue`. Here are the steps:

---

> 👉 **#1** - Create a `theme.js` file in the `src` folder and import `extendTheme`

```javascript
//in theme.js
 
import { extendTheme } from '@chakra-ui/react';
```

---

> 👉 **#2** - Create a config object containing two properties - `initialColorMode` and `useSystemColorMode`.

```javascript
import { extendTheme } from '@chakra-ui/react';
const config = {
  initialColorMode: 'light',
  useSystemColorMode: false,
};
```

**From the code snippet above:**

- `initialColorMode` represents the initial colour mode shown when a user visits your website for the first time.
- `useSystemColorMode` - can either be true or false.

---

> 👉 **#3** - Create a theme variable and export the config using `extendTheme`.

```javascript
import { extendTheme } from '@chakra-ui/react';
const config = {
  initialColorMode: 'light',
  useSystemColorMode: false,
};
const theme = extendTheme({ config });
 
export default theme;
```

---

> 👉 **#4** -  Edit the `index.js` file to use `ChakraProvider`

Import `ChakraProvider` and `ColorModeScript` from Chakra UI and theme from `theme.js`.

```javascript
import { ChakraProvider, ColorModeScript } from '@chakra-ui/react';
import theme from './theme'
```

---

> 👉 **#5** - Enable the access to the theme settings (all components)

```javascript
import { ChakraProvider, ColorModeScript } from '@chakra-ui/react';
import theme from './theme';
 
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <ChakraProvider>
    <ColorModeScript initialColorMode={theme.config.initialColorMode} />
    <App />
  </ChakraProvider>
); 
```

Finally, we have set up dark mode in our web application. Next, let's learn how to switch between the light and dark colour modes.

---

## ✨ Switching `dark` / `light` mode

In this section, we will create a switch that can be used to toggle between light and dark modes.

---

![React Chakra UI Sample - Dark Mode](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gemr3zo8lh6ake02nyhy.gif)

---

> 👉 **1#** - Open the src/components/Nav.js and import the following:

```javascript
import { useColorMode, useColorModeValue } from '@chakra-ui/react';
 
/* 
  useColorMode is a hook that selects and toggles between different colour modes.
  useColorModeValue is a hook that allows you to select the colour you want a Chakra UI component to change to.
*/
```

---

> 👉 **2#** - Declare the hooks in the component 

```javascript
import { useColorMode, useColorModeValue } from '@chakra-ui/react';
 
const Nav = () => {
  const { colorMode, toggleColorMode } = useColorMode();
  const navBg = useColorModeValue('white', 'blackAlpha.200');
  ....
  ....
    return (
    <Flex
      bg={navBg}
    >
    ....
    ....
    </Flex>
  )
}
 
export default Nav;
```

**From the code snippet above**

- `colorMode` holds the current colour scheme, and toggleColorMode is the function that changes the colour scheme from light to dark.
- `navBg` is a variable that dictates the exact colour the Flex component should have in both colour modes. In light mode, the background colour will be white, and in `dark mode`, it will be `blackAlpha.200`.

---

> 👉 **3#** - Add the icon that toggles the colour mode when clicked

```javascript
import { useColorMode, useColorModeValue, Icon } from '@chakra-ui/react';
import { MoonIcon, SunIcon } from '@chakra-ui/icons';
 
const Nav = () => {
  const { colorMode, toggleColorMode } = useColorMode();
  const navBg = useColorModeValue('white', 'blackAlpha.200');
  ....
  ....
    return (
    <Flex
      bg={navBg}
    >
    <IconButton onClick={toggleColorMode}>
      {colorMode === 'light' ? <MoonIcon /> : <SunIcon />}
    </IconButton>
  ....
    ....
    </Flex>
  )
}
 
export default Nav;
```

**From the code snippet above:**

- If `colorMode` is light, it shows the Moon icon otherwise it shows the Sun icon.
- When the icon is clicked, it also calls the `toggleColorMode` function.

---

## ✨ Conclusions & Resources    

In this article, we've been able to build a complete and fully responsive webpage using Chakra UI. You have also learned about various layout components available in Chakra UI.

*Chakra UI enables you to build a modern website with less code. With its easy-to-navigate documentation, you can learn about the various layout components and features Chakra UI provides.*

It provides a clean and efficient way to change colour modes using local storage. If you want to build a website that allows users to select different colour schemes, **Chakra UI** is an excellent choice.

---

> Thanks for reading! For more resources, feel free to access Free [Chakra UI Templates](https://www.admin-dashboards.com/chakra-ui-starters-open-source-and-free/) (a curated list)

---

![Chakra UI - Curated list with FREE Starters](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/af280free8vft9iqzfnz.png)

---