Print Page | Contact Us | Report Abuse | Sign In | Register
Latest News: asdf

4 ways to style React Components

Monday, February 25, 2019   (0 Comments)
Posted by: Raqib HasanAug

This is the fourth part of my React tutorials. See the Intro to react.js here

There are four different options to style React components. All depend on your personal preferences and the specific complexity of your application.

If you want to add just a few style properties, then inline styling is the best option.

When you want to reuse your style properties in the same file then style-component are perfect.

When your application is more complex I recommend CSS Modules or regular CSS stylesheets.

1. CSS Stylesheet

 
  • Simply import css file import './DottedBox.css' so you can have a separate css file for each component.
 

2. Inline styling

In React, inline styles are not specified as a string. Instead they are specified with an object whose key is the camelCased version of the style name, and whose value is the styleโ€™s value, usually a string.

 
  • We can create a variable that stores style properties and then pass it to the element like style={nameOfvariable}
  • We can also pass the styling directly style={{color: 'pink'}}

3. CSS Modules

A CSS Module is a CSS file in which all class names and animation names are scoped locally by default. Great article about css modules here.

 
  • Similar to css we import css file import styles './DashedBox.css'
  • then we access to className as we access to object
 

:local(.className)-this when you use create-react-app because of webpack configurations

.className-this if you use your own react boilerplate.

To make CSS modules work with Webpack you only have to include the modules mentioned above and add the following loader to your webpack.config.js file:

. . .
{
test: /\.css$/,
loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
}
. . .

4. Styled-components ๐Ÿ’…

Styled-components is a library for React and React Native that allows you to use component-level styles in your application that are written with a mixture of JavaScript and CSS

 
  • First we need to install styled-components library
  • npm install styled-components --save
  • Now we can create a variable by selecting a particular html element where we store our style keys const Div = styled.htmlElemnet`color: pink`
  • Then we use the name of our variable as a wrapper <Div></Div> kind of react component:)
  • Tips to use emoji icons key shortcut CTRL+CMD+SPACE ๐Ÿ’ก

All these ways of styling react components have pros and cons.

It all boils down to both your own personal preferences and the specific complexity of your application.

I suggest you to make 4 projects, each using different way of style.

Enjoy ๐Ÿ˜ƒ