The getColor utility in the @zendeskgarden/react-theming package is a powerful function designed to retrieve and manipulate color values based on the theme. It enables consistent theming across components, supports light and dark modes, and allows fine-tuned adjustments like transparency, shade offsets, and hue modifications.
Below, I will outline the ways to use getColor, provide code examples in JavaScript, React, and styled-components, and share best practices.
Ways to Use getColor
getColor can be used in several ways depending on your scenario. These include:
Retrieve Colors by Variable
Retrieve Colors by Hue
Adjust Shades
Apply Transparency
Use in Light and Dark Modes
Combine Options (e.g., Hue, Offset, Transparency)
1. Retrieve Colors by Variable
You can retrieve colors directly using theme-defined variables (e.g., background.default, text.primary).
Example:
jsx
import { getColor } from '@zendeskgarden/react-theming';
import styled from 'styled-components';
const StyledDiv = styled.div`
background-color: ${props =>
getColor({ theme: props.theme, variable: 'background.default' })};
color: ${props =>
getColor({ theme: props.theme, variable: 'text.primary' })};
`;
const App = () => (
<StyledDiv>
This background and text color are derived from theme variables.
</StyledDiv>
);
export default App;
Best Practice:
Use variables when you want to rely on theme-defined defaults.
Validate that the variable exists in the theme to avoid runtime errors.
2. Retrieve Colors by Hue
You can retrieve colors by specifying a hue (e.g., primaryHue, blue, red) and optionally a shade (e.g., 600, 700).
Use offsets to create subtle gradients or differentiate elements while maintaining a cohesive theme.
4. Apply Transparency
You can add transparency to colors using the transparency property. You can specify a value between 0 (fully transparent) and 1 (fully opaque) or use theme-defined opacity keys.
Use combination properties for custom UI components that need fine-tuned theming.
Maintain a balance between flexibility and consistency.
Best Practices
Error Handling: Ensure variables, hues, and shades exist in the theme to avoid runtime errors. Catch and handle errors gracefully if necessary.
Consistency: Use theme variables and hues for consistency across your design system.
Accessibility: Always test colors for sufficient contrast and readability, especially when using transparency or darkening/lightening adjustments.
Memoization: Since getColor is memoized, avoid unnecessary calls with identical arguments to improve performance.
Theme Validation: Validate custom themes to ensure they align with the Garden Design System's structure.
By following these strategies and examples, you'll be able to integrate the getColor utility seamlessly into your React project while ensuring a consistent, accessible, and visually appealing UI.