Styled-components is a new & better way that lets you write actual CSS in your JavaScript. You can still use all the features of CSS you use and love. Styled-components is compatible with ReactJS (for web) and React Native (for mobile) meaning it’s the perfect choice even for universal apps!
In this blog, we will explore how to use Styled-Component in our projects. To get it installed using yarn:
yarn add styled-components
Using NPM:
npm install --save styled-components
Styled-components utilize tagged template literals to style components. Most important feature of styled-components is that it removes the mapping between styles and components. This means that when you are defining styles, we are creating a normal React component with styles.
In the example below we created two components with styles attached to them. Title component with H1 tag & styles, Content component with section tag & styles.
import styled from 'styled-components';
Output:
Now you would be wondering how can we change the styles of components based on any condition. Styled component made it very easy to implement conditional styling based on props. To check conditions you can pass a function (“interpolations”) to a styled component’s template literal to adapt it based on its props.
Output:
Next, in some scenarios you might want to use the same component with slight changes in style, you can achieve it by interpolated function conditional rendering as mentioned above, another easy way is to make a new component with inherits the styling of others.
Output:
There are tons of other ways as well to create a styled component. You can find complete documentation here.
React Native
In react-native default way of styling components is using StyleSheet
API. Styled-components can also be used with React Native in the same way and with the same import, we did for ReactJS. Expo also supports this library.
Thanks for reading, have you tried styled-components before, or are you planning to use it? Don’t forget to share your thoughts in the comment section!