Exploring the Chakra UI React Component Library

栏目: IT技术 · 发布时间: 4年前

内容简介:Despite my love forTailwind CSS over other frameworks, I have always been disappointed by the lack of components like what we get with more fully fledged-out frameworks like Bootstrap and Materialize. I recently discovered the perfect solution to this prob

Despite my love forTailwind CSS over other frameworks, I have always been disappointed by the lack of components like what we get with more fully fledged-out frameworks like Bootstrap and Materialize. I recently discovered the perfect solution to this problem: Chakra UI .

Chakra UI follows the same minimalistic and modular approach as Tailwind CSS, so you don’t need to waste anymore time undoing and overriding the default configurations.

In this article, we’re going to get started exploring the best of what this framework can do for us and why it’s unique.

Installation

Installation is a bit awkward since there are a few peer dependencies which, I think, should just come with it by default, but that’s how it is for some reason ¯\_(ツ)_/¯.

We just need Chakra UI itself and a few things from Emotion , since Chakra UI is dependent on :woman:‍:microphone: emotion , theCSS-in-JS library.

We’ll make use of npx and Create React App to initialize our React app:

$ npx create-react-app chakra-app
$ npm install @chakra-ui/core @emotion/core @emotion/styled emotion-theming
Exploring the Chakra UI React Component Library

This affiliate banner helps support the site :pray:

Setup

Before we can do anything we need to wrap our whole app in a ThemeProvider , which establishes all of the default styles for our components.

index.js

import { ThemeProvider } from "@chakra-ui/core";

const ThemedApp = () => <ThemeProvider> <App /> </ThemeProvider>;

ReactDOM.render(<ThemedApp />, document.getElementById('root'));

Layout

Besides our normal UI components like sliders and dropdowns, Chakra UI gives us a few “meta components” (not the official term), for easily adding a responsive layout of multiple components. With all of them you can pass-in the properties you’d expect, like bg or justifyContent in CSS as props.

  • Stack - Groups a set on components with equal spacing, is vertical by default but can be overridden with isInline .
  • Flex - Wraps everything in aFlexbox container.
  • Grid - Wraps everything in aCSS Grid container.
  • Box - Just a div for receiving style props.

App.js

import { Stack, Flex, Box, Grid } from "@chakra-ui/core";

const App = () => {
  const flexSettings = {
    flex: "1",
    minW: "300px",
    textAlign: "center",
    color: "white",
    mx: "6",
    mb: "6"
  };

  const gridSettings = {
    w: "100%",
    textAlign: "center",
    color: "white",
  };

  return (
    <div>
      <Flex w="100%" justify="space-between" flexWrap="wrap">
        <Box {...flexSettings} bg={"red.500"}>I'm a box</Box>
        <Box {...flexSettings} bg={"blue.500"}>I'm a box</Box>
        <Box {...flexSettings} bg={"green.500"}>I'm a box</Box>
        <Box {...flexSettings} bg={"purple.500"}>I'm a box</Box>
      </Flex>

      <Grid w="100%" templateColumns="repeat(auto-fit, minmax(300px, 1fr))" gap={6}>
        <Box {...gridSettings} bg={"red.500"}>I'm a box</Box>
        <Box {...gridSettings} bg={"blue.500"}>I'm a box</Box>
        <Box {...gridSettings} bg={"green.500"}>I'm a box</Box>
        <Box {...gridSettings} bg={"purple.500"}>I'm a box</Box>
      </Grid>
    </div>
  );
};

Styling

Since Chakra UI is based on Emotion for styling, is allows for using CSS-in-JS and adds its own shorthand for common properties in the same style as Tailwind CSS, that’s why we were able to use w and templateColumns instead of width and gridTemplateColumns .

If you’re unfamiliar with this approach to styling, it’s a way of writing your CSS so you get all the JavaScript goodies that even Sass doesn’t come with, like connecting a style to the state of a component.

In this example, we’re basing the styles of a box off the component’s state and using a little UI to manipulate it.

App.js

const BoxController = () => {
  let [boxHeight, editHeight] = useState(20);
  let [boxColor, editColor] = useState('red');
  let [colorIntensity, editIntensity] = useState(500);

  const boxSettings = {
    flex: "1",
    textAlign: "center",
    color: "white",
    h: `${boxHeight}px`,
    bg: `${boxColor}.${colorIntensity}`
  };

  return (
    <div>
      <Box {...boxSettings}>I'm a Box</Box>
      <Flex justifyContent="space-around">
        <Stack>
          <Heading size="md">Size</Heading>
          <Button variantColor="red" onClick={() => editHeight(boxHeight -= 10)} border="none">Shrink</Button>
          <Button variantColor="green" onClick={() => editHeight(boxHeight += 10)} border="none">Grow</Button>
        </Stack>

        <Stack>
          <Heading size="md">Color</Heading>

          <Flex w="200px" justifyContent="space-between">

            <Stack>
              <Button variantColor="green" onClick={() => editColor('green')} border="none">Green</Button>
              <Button variantColor="blue" onClick={() => editColor('blue')} border="none">Blue</Button>
              <Button variantColor="red" onClick={() => editColor('red')} border="none">Red</Button>
            </Stack>

            <Stack>
              <Button variantColor="gray" variant="outline" onClick={() => editIntensity(colorIntensity -= 100)} border="none">Lighter</Button>
              <Button variantColor="gray" variant="outline" onClick={() => editIntensity(colorIntensity += 100)} border="none">Darker</Button>
            </Stack>

          </Flex>
        </Stack>
      </Flex>
    </div>
  );
};

Components

We obviously can’t go over every component, so let’s just focus on a few that are unique to Chakra UI.

Drawer

The drawer component is a clean little slide out mechanism that would be perfect for any side navbar. Note that it uses Chakra’s custom useDisclosure hook that gives us isOpen , onOpen , and onClose for controlling the state of our drawer and any similar components, like a modal.

App.js

import {
  Drawer,
  DrawerBody,
  DrawerFooter,
  DrawerHeader,
  DrawerOverlay,
  DrawerContent,
  DrawerCloseButton,
  Input,
  Button,
  useDisclosure,
  Stack,
  Textarea
} from "@chakra-ui/core"

const SignUpForm = () =>  {
  const { isOpen, onOpen, onClose } = useDisclosure();
  const btnRef = useRef();

  return (
    <div>
      <Button ref={btnRef} variantColor="teal" border="none" onClick={onOpen}>
        Sign Up
      </Button>
      <Drawer
        isOpen={isOpen} placement="bottom"
        onClose={onClose} finalFocusRef={btnRef}
      >
        <DrawerOverlay />
        <DrawerContent>

          <DrawerCloseButton border="none" />
          <DrawerHeader>Sign up Now</DrawerHeader>
          
          {/* Form */}
          <DrawerBody >
            <Stack height="30vh">
              <Input w="98%" placeholder="Name" />
              <Input w="98%" placeholder="Email" />
              <Textarea w="98%" h="100%" placeholder="Message" />
            </Stack>
          </DrawerBody>

          <DrawerFooter>
            <Button variantColor="red" border="none" mr={3} onClick={onClose}>
              Cancel
            </Button>
            <Button variantColor="blue" border="none">Save</Button>
          </DrawerFooter>

        </DrawerContent>
      </Drawer>
    </div>
  );
}

Loaders

Chakra UI offers us a nice array of animated loaders that are insanely easy to customize. In this example I’ve added a loop to see our loaders in action, but they don’t need to be based on anything external, they can also be completely static.

App.js

import {
  Stack,
  CircularProgress,
  CircularProgressLabel,
  Progress,
  Spinner
} from "@chakra-ui/core"

const Spinners = () => {
  let [progress, update] = useState(0)

  const randomNum = (min, max) => Math.floor(Math.random() * (max - min + 1) + min)

  useEffect(() => setInterval(() => {
    // Reset to 0 when reaches 100
    update(progress < 100 ? progress += randomNum(0, 4) : 0)
  }, 500), [])

  return (
    <div>
      <Stack>
        <CircularProgress color="green" isIndeterminate>
          <CircularProgressLabel>{progress}%</CircularProgressLabel>
        </CircularProgress>
        <CircularProgress value={progress} size="100px" thickness={0.1} color="purple" />
        <Progress value={progress} w="90%" />
        <Progress value={progress + 10} w="90%" hasStripe isAnimated />
        <Spinner
          thickness="3px"
          speed="1s"
          emptyColor="gray.200"
          color="blue.500"
          size="2xl"
        />
      </Stack>
    </div>
  );
}

Themes

Something I have yet to see from any other framework is the ability to set themes over the entirety of your app. Whether it be a dark theme or a winter theme we can easily customize the style across our whole site/app in one place.

In this example I’ve added a few boxes whose designs and text will be based on the holiday season. I personally love when sites give you the option to pick which design you like best, like Alligator.io does. :wink:

index.js

import { useTheme, ThemeProvider } from "@chakra-ui/core"


const ThemedApp = () => {
  const theme = useTheme()
  const customTheme = {
    ...theme,
    colors: { ...theme.colors },
    holidays: {
        text: {
          none: "Welcome to the site!",
          stPatricksDay: "Happy St.Patty's Day!",
          valentinesDay: "Happy Valentines Day!",
          halloween: "Good luck trick-or-treating!",
          christmas: "Merry Christmas!"
        },
        colors: {
            none: {
              "one": "#808080",
              "two": "#808080",
              "three": "#808080"
            },
            stPatricksDay: {
              "one": "#224D17",
              "two": "#60A830",
              "three": "#099441"
            },
            valentinesDay: {
              "one": "#b11d4d",
              "two": "#fd6fa0",
              "three": "#e986a3"
            },
            halloween: {
              "one": "#810806",
              "two": "#BF200E",
              "three": "#FA4113"
            },
            christmas: {
              "one": "#44b09e",
              "two": "#e0d2c7",
              "three": "#e01c34"
            },
        }
      }
  };
  return (
    <div>
      <ThemeProvider theme={customTheme}><App /></ThemeProvider>
    </div>
  )
}

App.js

import {
  Flex,
  Button,
  useTheme,
  Box
} from "@chakra-ui/core"

const HolidayPicker = () => {
  const [holiday, updateHoliday] = useState("none")
  const theme = useTheme()

  const holidayText = theme.holidays.text[holiday]
  const holidayColor = theme.holidays.colors[holiday]

  const btnStyles = {
    border: 'none',
    h: '25px',
    borderRadius: '20px',
    color: 'white',
    fontWeight: 'bold',
    cursor: 'pointer'
  }
  return (
    <div>
      <Flex justifyContent="space-around">
        <Box bg={holidayColor.one} w="100%" h="400px" color="white">{holidayText}</Box>
        <Box bg={holidayColor.two} w="100%" h="400px" color="white">{holidayText}</Box>
        <Box bg={holidayColor.three} w="100%" h="400px" color="white">{holidayText}</Box>
      </Flex>

      <Flex justifyContent="space-around" mt="20px">
        <Button bg={theme.holidays.colors.none} {...btnStyles}
          onClick={() => updateHoliday('none')}>None</Button>
        <Button bg={theme.holidays.colors.stPatricksDay} {...btnStyles}
          onClick={() => updateHoliday('stPatricksDay')}
        >St.Patrick's Day</Button>
        <Button bg={theme.holidays.colors.valentinesDay} {...btnStyles}
          onClick={() => updateHoliday('valentinesDay')}
        >Valentine's Day</Button>
        <Button bg={theme.holidays.colors.halloween} {...btnStyles}
          onClick={() => updateHoliday('halloween')}
        >Halloween</Button>
        <Button bg={theme.holidays.colors.christmas} {...btnStyles}
          onClick={() => updateHoliday('christmas')}
        >Christmas</Button>
      </Flex>
    </div>
  );
}

Closing Thoughts

Together with TailwindCSS, Chakra UI has easily become one of the essential tools in all of my projects. It’s constantly improving and even now there are a few pull requests like appBar and carousel components that’ll probably be added soon. I hope this was enough to help you decide if Chakra UI deserves to be in your React/UI arsenal.


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

矩阵计算

矩阵计算

Gene H. Golub、Charles F. Van Loan / 袁亚湘 / 人民邮电出版社 / 2009 / 89.00元

本书是国际上数值计算方面的权威著作,有“圣经”之称。被美国加州大学、斯坦福大学、华盛顿大学、芝加哥大学、中国科学院研究生院等很多世界知名学府用作相关课程的教材或主要参考书。 本书系统地介绍了矩阵计算的基本理论和方法。书中的许多算法都有现成的软件包实现,每节后还附有习题,并有注释和大量参考文献,非常有助于自学。一起来看看 《矩阵计算》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

MD5 加密
MD5 加密

MD5 加密工具

html转js在线工具
html转js在线工具

html转js在线工具