How do I access theme when using css-backticks notation? #2717
-
I know that when you use export const Element = styled.div`
color: ${props => props.theme.color.text};
`; or when you use css property - like this: <div css={theme => ({ color: theme.colors.primary })}>
some other text
</div> But how do I access theme when I use export const myStyle = css`
color: red;
`;
<div className={myStyle}>My Text</div> |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
You can use the /** @jsx jsx */
import { jsx, ThemeProvider, useTheme } from '@emotion/react'
const theme = {
colors: {
primary: 'hotpink'
}
}
function SomeText (props) {
const theme = useTheme()
return (
<div
css={{ color: theme.colors.primary }}
{...props}
/>
)
}
render(
<ThemeProvider theme={theme}>
<SomeText>some text</SomeText>
</ThemeProvider>
) |
Beta Was this translation helpful? Give feedback.
-
This is as clean as I could get it:
/** @jsx jsx */
import { jsx, useTheme, css } from '@emotion/react';
const MyComponent = () => {
const theme = useTheme();
const myStyles = css`
color: ${theme.colors.primary}
`;
return(
<>
<div css={myStyles}>I am a div tag</div>
<p css={myStyles}>I am a paragraph tag</p>
<h2 css={css`color: ${theme.colors.primary}`}>I am a Heading 2 tag</h2>
</>
)
}
export default MyComponent; In react there is a point where you need to have a parent component, in this case it's the Hooks can only be called before the return statement of a Functional Component. So it´s impossible to call the This is why the above code can't get any "cleaner". The css`` syntax is just a template literal with syntax highlighting provided by the I hope this helps! |
Beta Was this translation helpful? Give feedback.
@pauljfx
This is as clean as I could get it:
MyComponent.jsx
In react there is a point where you need to have a parent component, in this case it's the
MyComponent
component.Hooks can only be called before the return statement of a Functional Component. So it´s impos…