Last active
July 24, 2018 21:51
-
-
Save chris-brown/144b2921ec69a58f54534a161fdf2894 to your computer and use it in GitHub Desktop.
Overrides React Styled Component HOC - https://www.styled-components.com/docs/advanced#theming
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import styled from 'styled-components'; | |
const MyComponent = styled.div` | |
background: red; | |
color: white; | |
`; | |
MyComponent.displayName = 'MyComponent'; | |
const ThemeMyComponent = styled(MyComponent).attrs({ | |
overrides: props => props.theme[this.constructor.displayName].css | |
})` | |
${overrides} | |
`; | |
/* | |
theme passed to theme provider | |
*/ | |
const theme = { | |
MyComponent: { | |
css:` | |
background: black; | |
colour: white; | |
`; // this could be require('MyComponent.css'); | |
} | |
} |
Or something more reusable
const ThemedComponent = component => styled(component).attrs({
overrides: props => props.theme[this.constructor.displayName].css
})`
${overrides}
`;
<ThemedComponent component={MyComponent} />
or
const ThemedComponent = ({children})=> styled(component).attrs({
overrides: props => props.theme[this.constructor.displayName].css
})`
${overrides}
`;
<ThemedComponent>
<MyComponent myprop="Hello" />
</ThemedComponent>
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
alternatively just create a HOC similar to
withTheme
https://github.com/styled-components/styled-components/blob/master/src/hoc/withTheme.js eg.