In this lesson we’ll create a generic heading primitive component, that we could use to render headings of different levels in our app. We’ll use Styled System to create this component.
We’re going to use Styled System variants to define styles for each heading level. The number of levels depends on your app’s complexity, and it’s something you’ll need to discuss with your designer. In this lesson we’ll create three levels of headings. We'll make it possible to change the HTML element (
h3) independently from the visual heading level.
We’ll use following libraries:
You can either use this lesson’s Git repository or install them manually in your project:
npm install styled-components styled-system
Useful links and documentation:
Artem Sapegin: [0:00] First, let's create a Markdown file with some examples, Heading.md. Add examples for each heading level, and one example with custom margins.
[0:09] Now create a component file, Heading.js, and start styleguidist. Import React. Import styled-components. Import variant and space functions from styled-system.
[0:21] Define styles for each heading level. Create a new Component that we'll use internally to automatically switch the HTML element based on the heading level. For example, the first heading level will be rendered using the h1 tag, the second h2, and so on.
[0:44] We'll still be able to change html element for a particular heading we need to. Here we're destructuring the as prop and renaming it to Component because React Component names should begin with upper case letter.
[0:56] Then we're defining a default value for this prop, which is using the level prop we've destructured at the previous line. We're constructing an HTML element named h1, h2, h3 and so on. Then we're destructuring the rest of the props that are pasted to this component and we're rendering a component with these props.
[1:15] Create a new styled component based on the HeadingBase component. Reset the default Heading margins, pass our variants to the variants styled-system function. By default, it's expecting the variant prop, so we need to change it to the level because that's the API of our component.
[1:32] Paste the space styled-system function to styled-components factory and export our component. Let's also define some propTypes. PropTypes for spacing values from styled-system, the level prop which could be either 1, 2 or 3 -- this is a required prop -- and children, which is a React node.