Use hook useStyles2(getStyles) to memoize the styles generation and try to avoid passing props to the the getStyles function and instead compose classes using emotion cx function.
For styling components, use [Emotion's `css` function](https://emotion.sh/docs/emotion#css).
```tsx
import React from 'react';
import { css } from '@emotion/css';
const ComponentA = () => (
<div
className={css`
background: red;
`}
>
As red as you can get
</div>
);
```
### Styling with theme
### Basic styling
To access the theme in your styles, use the `useStyles` hook. It provides basic memoization and access to the theme object.
@ -31,33 +14,35 @@ To access the theme in your styles, use the `useStyles` hook. It provides basic
```tsx
import React, { FC } from 'react';
import { GrafanaTheme } from '@grafana/data';
import { useStyles } from '@grafana/ui';
import { GrafanaTheme2 } from '@grafana/data';
import { useStyles2 } from '@grafana/ui';
import { css } from '@emotion/css';
const Foo: FC<FooProps> = () => {
const styles = useStyles(getStyles);
const styles = useStyles2(getStyles);
// Use styles with classNames
return <divclassName={styles}>...</div>;
};
const getStyles = (theme: GrafanaTheme) => css`
padding: ${theme.spacing.md};
`;
const getStyles = (theme: GrafanaTheme2) =>
css({
padding: theme.spacing(1, 2), // will result in 8px 16px padding
});
```
### Styling complex components
In more complex cases, especially when you need to style multiple DOM elements in one component, or when using styles that depend on properties and/or state, you should create a helper function that returns an object of styles. This function should also be wrapped in the `stylesFactory` helper function, which will provide basic memoization.
In more complex cases, especially when you need to style multiple DOM elements in one component, or when using styles that depend on properties and/or state you
can have your getStyles function return an object with many class names and use [Emotion's `cx` function](https://emotion.sh/docs/emotion#cx) to compose them.
Let's say you need to style a component that has a different background depending on the `isActive` property :
```tsx
import React from 'react';
import { css } from '@emotion/css';
import { GrafanaTheme } from '@grafana/data';
import { selectThemeVariant, stylesFactory, useTheme } from '@grafana/ui';