Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Pseudo and Conditional Styling | Responsive and Advanced Styling
Styling React Apps with Chakra UI

bookPseudo and Conditional Styling

Sveip for å vise menyen

Chakra UI supports interactive styling through special style props known as pseudo-props. These props allow components to change appearance based on user interaction states such as hover, focus, and active.

Common pseudo-props include _hover, _focus, and _active, which define styles applied when a component is hovered with a mouse, focused via keyboard navigation, or actively pressed. These styles are declared directly on components, keeping interaction logic and styling in one place.

Chakra UI also supports conditional styling based on component state or props. This makes it possible to visually communicate states such as loading, disabled, or selected without relying on external CSS.

import { Box, Button, Heading, Input, Stack, Text } from "@chakra-ui/react"
import { useState } from "react"

export default function App() {
  const [isSubmitting, setIsSubmitting] = useState(false)

  return (
    <Box
      minH="100vh"
      bg="gray.50"
      color="gray.900"
      display="grid"
      placeItems="center"
      p={{ base: "4", md: "8" }}
    >
      <Box
        bg="white"
        borderWidth="1px"
        borderRadius="xl"
        p={{ base: "4", md: "6" }}
        w="full"
        maxW="420px"
      >
        <Stack gap="4">
          <Heading size="md">Newsletter</Heading>

          <Text color="fg.muted">
            Get product updates once a week. No spam.
          </Text>

          <Input placeholder="Email address" />

          <Button
            colorPalette="brand"
            isDisabled={isSubmitting}
            _hover={{
              bg: "brand.600",
            }}
            _focus={{
              boxShadow: "0 0 0 3px rgba(47, 107, 255, 0.4)",
            }}
            _active={{
              bg: "brand.700",
            }}
            onClick={() => setIsSubmitting(true)}
          >
            {isSubmitting ? "Submitting…" : "Subscribe"}
          </Button>
        </Stack>
      </Box>
    </Box>
  )
}
  • _hover: visual feedback on mouse hover;
  • _focus: accessible keyboard focus styling;
  • _active: pressed state styling;
  • Conditional UI based on isSubmitting state.
question mark

Which pseudo-prop would you use to style a component when it is hovered?

Select the correct answer

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 3. Kapittel 2

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Seksjon 3. Kapittel 2
some-alt