Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Using Chakra UI Hooks | Real World Examples
Styling React Apps with Chakra UI

bookUsing Chakra UI Hooks

メニューを表示するにはスワイプしてください

Chakra UI provides a set of React hooks designed specifically for managing common UI behavior. These hooks simplify tasks such as controlling component visibility, responding to user preferences, and providing feedback.

The useDisclosure hook manages open and close states for components like modals and drawers. The useColorMode hook allows switching between light and dark modes, while useToast enables displaying temporary notification messages to inform users about actions or state changes.

By combining these hooks, it becomes possible to manage UI logic in a clean and declarative way without writing repetitive state management code.

import {
  Box,
  Button,
  Heading,
  HStack,
  Modal,
  ModalBody,
  ModalContent,
  ModalHeader,
  ModalOverlay,
  Stack,
  Text,
  useColorMode,
  useDisclosure,
  useToast,
} from "@chakra-ui/react"

export function HeaderActions() {
  const { isOpen, onOpen, onClose } = useDisclosure()
  const { colorMode, toggleColorMode } = useColorMode()
  const toast = useToast()

  const handleThemeToggle = () => {
    toggleColorMode()
    toast({
      title: `Switched to ${colorMode === "light" ? "dark" : "light"} mode`,
      status: "success",
      duration: 2000,
      isClosable: true,
    })
  }

  return (
    <>
      <HStack gap="3">
        <Button variant="ghost" onClick={handleThemeToggle}>
          Toggle Theme
        </Button>

        <Button colorPalette="brand" onClick={onOpen}>
          Sign Up
        </Button>
      </HStack>

      <Modal isOpen={isOpen} onClose={onClose} isCentered>
        <ModalOverlay />
        <ModalContent>
          <ModalHeader>Join the Newsletter</ModalHeader>
          <ModalBody pb="6">
            <Stack gap="3">
              <Text>
                Get weekly updates about new features and UI patterns.
              </Text>
              <Button
                colorPalette="brand"
                onClick={() => {
                  onClose()
                  toast({
                    title: "Subscription successful",
                    status: "success",
                    duration: 3000,
                    isClosable: true,
                  })
                }}
              >
                Confirm Subscription
              </Button>
            </Stack>
          </ModalBody>
        </ModalContent>
      </Modal>
    </>
  )
}
question mark

Which Chakra UI hook would you use to manage modal open/close state?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 4.  1

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 4.  1
some-alt