Frontend Serverless with React and GraphQL

Start at the beginning and work your way through this project. The code for each step as well as the finished project can be found in the Github repository.


5. Add global style

Objective: Add global styles component to our Main Layout.

We have already added a theme to our project and now it is time to add a global style. While a theme is an object that we can add various css snippets such as margin widths, font sizes, and colors to our react components, a global style is where we can define styles that we want to, well, apply globally across our project.

The main purpose of our global style for us in the beginning will be to add text alignment, font size, font weight and line height to h1, h2, h3, and h4 tags. A useful thing about styled-components is that we can actually create a function called heading which will allow us to pass in a various font-sizes that we have saved in our theme object and apply them to each tag individually. Since our font-size-xl is larger than our font-size-sm for example, we can use that to set our h1 larger than our h4.

utils/globalStyle.ts

import { createGlobalStyle } from 'styled-components';
export const heading = (size) => {
return `
text-align: center;
font-weight: bold;
line-height: 1em;
font-size: ${size};
`;
};
export const GlobalStyle = createGlobalStyle`
${({ theme }) => `
h1 {
${heading(theme['font-size-xl'])}
}
h2 {
${heading(theme['font-size-lg'])}
}
h3 {
${heading(theme['font-size-md'])}
}
h4 {
${heading(theme['font-size-sm'])}
}
`}
`;

Once we have the global style all set up, we can use it as a component in our <MainLayout>:

components/layout/MainLayout.tsx

import { ThemeProvider } from 'styled-components';
import { Component } from 'react';
import { theme } from '../../utils/theme';
import { GlobalStyle } from '../../utils/globalStyle';
export class MainLayout extends Component {
render() {
const { children } = this.props;
return (
<ThemeProvider theme={theme}>
<GlobalStyle />
{children}
</ThemeProvider>
);
}
}