Commit 390c80d7 by Andreas Opferkuch Committed by GitHub

ThemeContext: Make useStyles type-aware (#26056)

PLUS:
Make it more consise
Add unit test
parent a2737c08
import React from 'react';
import { config } from '@grafana/runtime';
import { css } from 'emotion';
import { mount } from 'enzyme';
import { useStyles } from './ThemeContext';
describe('useStyles', () => {
it('passes in theme and returns style object', () => {
const Dummy: React.FC = function() {
const styles = useStyles(theme => {
expect(theme).toEqual(config.theme);
return {
someStyle: css`
color: ${theme?.palette.critical};
`,
};
});
expect(typeof styles.someStyle).toBe('string');
return <div>dummy</div>;
};
mount(<Dummy />);
});
});
......@@ -38,12 +38,11 @@ export const withTheme = <P extends Themeable, S extends {} = {}>(Component: Rea
export function useTheme(): GrafanaTheme {
return useContext(ThemeContextMock || ThemeContext);
}
/** Hook for using memoized styles with access to the theme. */
export const useStyles = (getStyles: (theme?: GrafanaTheme) => any) => {
const currentTheme = useTheme();
const callback = stylesFactory(stylesTheme => getStyles(stylesTheme));
return callback(currentTheme);
};
export function useStyles<T>(getStyles: (theme: GrafanaTheme) => T) {
return stylesFactory(getStyles)(useTheme());
}
/**
* Enables theme context mocking
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment