Today I'm back to writing after a while without doing it and we come back strong with an article where I will show how to use media queries and custom prop inside our Styled Components in React with Typescript, this is a functionality that I needed to implement for a project recently and I think it is positive to share it with the community. So here we go.
Requirements
In this step I will assume that we have a project with React, Typescript and Styled Components configured correctly and I will only show the dependencies that will be used in this tutorial:
yarn add styled-media-query
Create media file on theme folder
We will create a file called media.ts where we will configure the breakpoints.
./src
./theme
./media.ts
Create Example component
We create an Example component where we will use the styled components. In this case we will only use the component called Container in order not to complicate the example too much.
./src
./components
./Example
./index.tsx
Create styles file
We will create a file called styles.ts where our styled components will be, which we will use later inside the Example component.
./src
./components
./Example
./styles.ts
Using media queries on styled components
In this step we will use the breakpoints created earlier for the media queries.
Using custom props on styled components
First we must pass the prop and its value in the styled component call.
We simply do a destructuring and use the prop.
Use the props with the ternary operator
For this case we will use the ternary operator, in case we do not receive a value or received empty value in the prop, we will assign the color #fff.
Using the props into media query
We will create an arrow function and pass the props as a parameter so that we can use it within the function.
Thanks for reading me. 😊