How To Create a Dynamic Typography Component With React + Styled Components

Victor Harry
3 min readJan 3, 2023

--

To understand this article I assume that you know React, Typescript and the basics of Styled Component library.

All of us know the impact that a wrong tag in the wrong place can cause on SEO and Accessibility. It’s an error to only change font size in Typography Component. As a result of that I decided to create a dynamic Typography Component so that I could define the right tag through its properties.

Why all my titles are <p> tags with 32px… 🤔

Hands on!

We’ll start creating our component inside a Typography folder with one file for the component and the other for the styles.

Project folder structure

Let’s begin with index file. We’ll define some rules to block tags that we don’t want to receive, to do that we can create an interface with all tags that we want for our component.

Turn it dynamic

The magic happens on the styled.ts file, insted of defining a specific HTML tag after styled, we pass a callback function to get the tag prop and them return a React Component with createElement() that you can import from react, now you can pass to it’s props the dynamic tag prop! 🥳 You can set some default CSS here too.

Styling our component

One cool and clean thing that we can do to pass CSS properties to our component is to set the spread operator …props of our component inside the prop style of our DynamicTypography styled tag, and set on the Typography component the CSSProperties interface that you can import from react, this way we block our component from receiving props that are not listed on our TypographyProps interface and on CSSProperties.

Note: Now every other prop that are not listed on our TypographyProps interface must be part of CSSProperties. So, if you want to add event listeners for exemple or any other prop that you want to use besides CSS you must list it on the TypographyProps!

Now we don't need anymore to send a style object or double pass the value to get to a styled component CSS propertie. Our component can set CSS as props directly on the component instance.

Instantiating our component

We can finally instanciate our dynamic typography component and set the right tags in the right places! 🎉

--

--

Victor Harry

Average dev that likes to try a lot of diferent stuffs 🌐https://www.victor-harry.com