Skip to content

Instantly share code, notes, and snippets.

@drenther drenther/App.js
Created Jun 25, 2018

Embed
What would you like to do?
Theming in styled-components
/* src/App.js */
import styled, { ThemeProvider } from 'styled-components';
.
.
.
import { getUsers } from './utils/apiCalls';
import { invertTheme, getColor } from './utils/theme';
class AppContainer extends Component {
state = {
users: [],
themeInverted: false,
};
invertTheme = () => {
this.setState(state => ({
themeInverted: !state.themeInverted,
}));
};
.
.
.
render() {
const { users, themeInverted } = this.state;
return themeInverted ? (
<ThemeProvider theme={invertTheme}>
<AppPresentional
users={users}
className={this.props.className}
invertTheme={this.invertTheme}
/>
</ThemeProvider>
) : (
<AppPresentional
users={users}
className={this.props.className}
invertTheme={this.invertTheme}
/>
);
}
}
const AppPresentional = ({ className, invertTheme, users }) => (
<div className={className}>
<Header invertTheme={invertTheme}>
<p>Random People</p>
<Button onClick={invertTheme}>Invert Theme</Button>
</Header>
.
.
.
</div>
);
export default styled(AppContainer)`
width: 100%;
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: center;
min-height: 100vh;
background: ${getColor('light')}
font-family: 'Roboto', sans-serif;
`;
/* src/index.js */
.
.
.
const rootElement = document.getElementById('root');
ReactDOM.render(
<ThemeProvider theme={theme}>
<BrowserRouter>
<App />
</BrowserRouter>
</ThemeProvider>,
rootElement,
);
/* src/utils/theme.js */
export const theme = {
color: {
primary: '#5755d9',
secondary: '#f1f1fc',
dark: '#454d5d',
light: '#f8f9fa',
},
fontSize: {
hg: '32px',
md: '24px',
sm: '18px',
tn: '14px',
},
};
export const invertTheme = ({
color: { primary, secondary, dark, light },
...rest
}) => ({
color: {
primary: secondary,
secondary: primary,
dark: light,
light: dark,
},
...rest,
});
export const getFontSize = size => props => props.theme.fontSize[size];
export const getColor = color => props => props.theme.color[color];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.