Styling (스타일링)
HeroUI Native 컴포넌트는 Tailwind CSS 유틸리티, StyleSheet API, 그리고 동적 스타일링을 위한 렌더 프롭 등 유연한 스타일링 옵션을 제공해요. 이 글에서는 className을 중심으로 한 스타일링 원칙부터 반응형 디자인과 유틸리티 함수까지 하나씩 살펴볼게요.
출처: 문서
본문
HeroUI Native 컴포넌트는 유연한 스타일링 옵션을 제공해요: Tailwind CSS 유틸리티, StyleSheet API, 그리고 동적 스타일링을 위한 렌더 프롭이 있어요.
스타일링 원칙 (Styling Principles)
HeroUI Native는 className을 기본 스타일링 수단으로 삼아 만들어졌어요. 모든 컴포넌트에서 className 프롭을 통해 Tailwind CSS 클래스를 사용할 수 있어요.
StyleSheet 우선순위: style 프롭(StyleSheet API)도 사용할 수 있으며, 둘 다 제공되면 className보다 우선해요. 이렇게 해서 필요할 때 Tailwind 클래스를 재정의할 수 있어요.
애니메이션 스타일: 일부 스타일 속성은 react-native-reanimated로 애니메이션되며, StyleSheet 스타일처럼 className보다 우선해요. 어떤 스타일이 애니메이션되며 className으로 사용할 수 없는지 확인하려면:
- IDE에서
className위에 마우스를 올려 보세요 — TypeScript 정의가 어떤 속성을 사용할 수 있는지 보여줘요 - 컴포넌트 문서를 확인하세요 — 각 컴포넌트 페이지 상단에 컴포넌트 스타일 소스 링크가 있으며, 거기에 애니메이션 속성에 대한 참고가 있어요
애니메이션 스타일 커스터마이징: 스타일이 애니메이션에 사용되고 있다면, 이를 지원하는 컴포넌트의 animation 프롭으로 수정할 수 있어요.
기본 스타일링 (Basic Styling)
className 사용: 모든 HeroUI Native 컴포넌트는 className 프롭을 받아요:
import { Button } from 'heroui-native';
<Button className="bg-accent px-6 py-3 rounded-lg">
<Button.Label>Custom Button</Button.Label>
</Button>;
style 사용: 컴포넌트는 style 프롭으로 인라인 스타일도 받아요:
import { Button } from 'heroui-native';
<Button style={{ backgroundColor: '#8B5CF6', paddingHorizontal: 24 }}>
<Button.Label>Styled Button</Button.Label>
</Button>;
렌더 프롭 (Render Props)
렌더 함수를 사용해 컴포넌트 상태에 접근하고 콘텐츠를 동적으로 커스터마이징해요:
import { RadioGroup, Label, cn } from 'heroui-native';
<RadioGroup value={value} onValueChange={setValue}>
<RadioGroup.Item value="option1">
{({ isSelected, isInvalid, isDisabled }) => (
<>
<Label
className={cn(
'text-foreground',
isSelected && 'text-accent font-semibold'
)}
>
Option 1
</Label>
<Radio
className={cn(
'border-2 rounded-full',
isSelected && 'border-accent bg-accent'
)}
>
{isSelected && <CustomIcon />}
</Radio>
</>
)}
</RadioGroup.Item>
</RadioGroup>;
래퍼 컴포넌트 만들기 (Creating Wrapper Components)
tailwind-variants를 사용해 재사용 가능한 커스텀 컴포넌트를 만들어요 — Tailwind CSS 일급 variant API예요:
import { Button } from 'heroui-native';
import type { ButtonRootProps } from 'heroui-native';
import { tv, type VariantProps } from 'tailwind-variants';
const customButtonVariants = tv({
base: 'font-semibold rounded-lg',
variants: {
intent: {
primary: 'bg-blue-500',
secondary: 'bg-gray-200',
danger: 'bg-red-500',
},
},
defaultVariants: {
intent: 'primary',
},
});
const customLabelVariants = tv({
base: '',
variants: {
intent: {
primary: 'text-white',
secondary: 'text-gray-800',
danger: 'text-white',
},
},
defaultVariants: {
intent: 'primary',
},
});
type CustomButtonVariants = VariantProps<typeof customButtonVariants>;
interface CustomButtonProps
extends Omit<ButtonRootProps, 'className' | 'variant'>,
CustomButtonVariants {
className?: string;
labelClassName?: string;
}
export function CustomButton({
intent,
className,
labelClassName,
children,
...props
}: CustomButtonProps) {
return (
<Button
className={customButtonVariants({ intent, className })}
{...props}
>
<Button.Label
className={customLabelVariants({ intent, className: labelClassName })}
>
{children}
</Button.Label>
</Button>
);
}
컴포넌트 classNames 사용하기 (Using Component classNames)
모든 HeroUI Native 컴포넌트는 컴포넌트 내부에서 사용하는 것과 동일한 스타일링 함수를 포함하는 classNames 객체를 내보내요. 이는 커스텀 컴포넌트를 HeroUI Native 컴포넌트 모양과 일치시키고 싶을 때 특히 유용해요.
예를 들어 커스텀 Link 컴포넌트를 Button처럼 보이게 스타일링할 수 있어요:
import { buttonClassNames, cn } from 'heroui-native';
import { Pressable, Text } from 'react-native';
interface LinkProps {
href: string;
variant?: 'primary' | 'secondary' | 'outline' | 'ghost';
size?: 'sm' | 'md' | 'lg';
children: React.ReactNode;
className?: string;
}
export function Link({
href,
variant = 'primary',
size = 'md',
children,
className,
}: LinkProps) {
return (
<Pressable
className={cn(
buttonClassNames.root({ variant, size }),
className
)}
onPress={() => {
// Handle navigation
}}
>
<Text className={buttonClassNames.label({ variant, size })}>
{children}
</Text>
</Pressable>
);
}
사용 가능한 classNames 내보내기:
각 컴포넌트는 자신의 classNames 객체를 내보내요. 예를 들어:
buttonClassNames—root와label함수를 포함해요cardClassNames—root,header,body,footer,label,description함수를 포함해요chipClassNames—root와label함수를 포함해요- 그 외에도 많아요...
사용 패턴:
import { buttonClassNames } from 'heroui-native';
// Use with variant and size options
const rootClasses = buttonClassNames.root({
variant: 'primary',
size: 'md',
className: 'custom-class', // Optional: merge with your own classes
});
const labelClasses = buttonClassNames.label({
variant: 'primary',
size: 'md',
});
classNames 함수는 컴포넌트 자체와 동일한 variant 프롭을 받아요. 덕분에 커스텀 컴포넌트와 HeroUI Native 컴포넌트 사이에서 시각적 일관성을 유지할 수 있어요.
반응형 디자인 (Responsive Design)
HeroUI Native는 Uniwind을 통해 Tailwind의 반응형 breakpoint 시스템을 지원해요. sm:, md:, lg:, xl: 같은 breakpoint 접두사를 사용해 화면 너비에 따라 스타일을 조건부로 적용해요.
모바일 우선 접근: 모바일 스타일(접두사 없음)로 시작한 뒤, breakpoint로 더 큰 화면을 향상시키세요.
반응형 타이포그래피와 간격 (Responsive Typography and Spacing)
import { Button } from 'heroui-native';
import { View, Text } from 'react-native';
<View className="px-4 sm:px-6 lg:px-8 py-6 sm:py-8">
<Text className="text-2xl sm:text-3xl lg:text-4xl font-bold mb-4 sm:mb-6">
Responsive Heading
</Text>
<Button className="px-3 sm:px-4 lg:px-6">
<Button.Label className="text-sm sm:text-base lg:text-lg">
Responsive Button
</Button.Label>
</Button>
</View>;
반응형 레이아웃 (Responsive Layouts)
import { View, Text } from 'react-native';
<View className="flex-row flex-wrap">
{/* Mobile: 1 column, Tablet: 2 columns, Desktop: 3 columns */}
<View className="w-full sm:w-1/2 lg:w-1/3 p-2">
<View className="bg-accent p-4 rounded-lg">
<Text className="text-accent-foreground">Item 1</Text>
</View>
</View>
</View>;
기본 breakpoint:
sm: 640pxmd: 768pxlg: 1024pxxl: 1280px2xl: 1536px
커스텀 breakpoint와 더 자세한 내용은 Uniwind breakpoints 문서를 참고하세요.
유틸리티 (Utilities)
HeroUI Native는 컴포넌트 스타일링을 돕는 유틸리티 함수를 제공해요.
cn 유틸리티 (cn Utility)
cn 유틸리티 함수는 충돌을 제대로 해결하면서 Tailwind CSS 클래스를 병합해요. 조건부 클래스를 조합하거나 프롭에서 클래스를 병합할 때 특히 유용해요:
import { cn } from 'heroui-native';
import { View } from 'react-native';
function MyComponent({ className, isActive }) {
return (
<View
className={cn(
'bg-background p-4 rounded-lg',
'border border-separator',
isActive && 'bg-accent',
className
)}
/>
);
}
cn 유틸리티는 tailwind-variants 기반이며 다음을 포함해요:
- 자동 Tailwind 클래스 병합 (
twMerge: true) - 커스텀 opacity 클래스 그룹 지원
- 적절한 충돌 해결 (나중 클래스가 앞선 클래스를 덮어써요)
충돌 예시:
// 'bg-accent' overrides 'bg-background'
cn('bg-background p-4', 'bg-accent');
// Result: 'p-4 bg-accent'
useThemeColor 훅 (useThemeColor Hook)
CSS 변수에서 테마 색상 값을 가져와요. 효율적인 배치 조회를 위해 단일 색상과 여러 색상을 모두 지원해요.
단일 색상 사용:
import { useThemeColor } from 'heroui-native';
function MyComponent() {
const accentColor = useThemeColor('accent');
const dangerColor = useThemeColor('danger');
return (
<View style={{ borderColor: accentColor }}>
<Text style={{ color: dangerColor }}>Error message</Text>
</View>
);
}
여러 색상 사용 (더 효율적):
import { useThemeColor } from 'heroui-native';
function MyComponent() {
const [accentColor, backgroundColor, dangerColor] = useThemeColor([
'accent',
'background',
'danger',
]);
return (
<View style={{ borderColor: accentColor, backgroundColor }}>
<Text style={{ color: dangerColor }}>Error message</Text>
</View>
);
}
타입 시그니처:
// Single color
useThemeColor(themeColor: ThemeColor): string
// Multiple colors (with type inference for tuples)
useThemeColor<T extends readonly [ThemeColor, ...ThemeColor[]]>(
themeColor: T
): CreateStringTuple<T['length']>
// Multiple colors (array)
useThemeColor(themeColor: ThemeColor[]): string[]
사용 가능한 테마 색상은 background, foreground, surface, accent, default, success, warning, danger, 그리고 이들의 모든 variant(hover, soft, foreground 등)와 muted, border, separator, field, overlay 같은 의미론적 색상이 포함돼요.
다음 단계 (Next Steps)
더 알아보기 (Learn more)
- tailwind-variants 공식 문서에서 variant API를 더 알아보세요.
- Uniwind breakpoints에서 반응형 브레이크포인트 시스템을 확인해 보세요.
- 공식 HeroUI Native Styling 문서에서 최신 정보를 확인할 수 있어요.