How To Add Props To Styled Components in React.js with TypeScript

Write Predictable Code With styled-components in React.js

Photo by Lewis Ngugi on Unsplash

Using React.js with TypeScript is not as straightforward for everyone when building a React application. I have quite some experience with TypeScript that I didn’t have significant issues (anymore 😅).

I’m pleased with Styled-components. But typing them was a big question for me, until now! So I want to share them with you. 😉

If you haven’t TypeScript experience yet, please check my TypeScript beginner post. 👇

TypeScript Interface and Enum

Let’s clarify what I do here.

I want to add a prop state to my component, but the value's that I want to accept in it are: sending, received, and error`. That's what I do in my enum.

I define the property state in my interface, and I tell that I accept only the values of the sendState enum. So if I put in another value, my IDE and build system starts complaining.

TypeScript helps me write predictable code, as you can see.

Styled Component with typing

You usually define a styled-component like: export const StatusMessage = styled.div this. But now I add the iSendingState, which tells that my component accepts a state property.

Hopefully, this helps you further building an excellent application with predictable code 💪

Happy coding 🚀

I write about Frontend, JavaScript, Typescript, React, Serverless Functions, JAM Stack, Netlify, Next.js — 👉 Subscribe newsletter

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store