AnApprentice
AnApprentice

Reputation: 110940

Understanding how to approach styling in React

I'm a newbie learning React. As the next phase of my learning, I need to learn how to style React. From previous experience, the steps I need to take to style my React app are:

  1. Add Reset CSS
  2. Implement a Grid System
  3. Implement common styles for items like (buttons, headers)
  4. Implement specific styles per component

Within the React world it's challenging to find a good jumping off point to tackle the above, so I'd love some advise to point me in the right direction.

Is styled-components most popular thing to do in the React world at the moment for all the 4 items listed above? If not, what do you recommend I start learning to handle the items mentioned above.

Upvotes: 1

Views: 958

Answers (1)

gpbl
gpbl

Reputation: 4804

If you are starting with React, I'd not go with something deep like styled-components without first understanding the problem styled-components is trying to fix.

Your first approach should be as basic as just add one or more <link>s to your .css files (e.g. reset.css, grid.css, component selectors in it etc.) and use the proper classNames props in your components:

// main.css
body {
  // ...
}

// MyToolbar.css
.MyToolbar {
  // style for a MyToolbar react component
}

in your html:

<html>
    <head>
       <link rel="stylesheet" type="text/css" href="reset.css">
       <link rel="stylesheet" type="text/css" href="main.css">
       <link rel="stylesheet" type="text/css" href="grid.css">
       <link rel="stylesheet" type="text/css" href="MyToolbar.css"> 

As your app grows, you will find hard to maintain this <head>, so you would benefit from a more modular approach.

For example, your next step may be to import your CSS from javascript instead of using <link> in your header:

// App Component
import React from 'react';

// import globally used styles
import './styles/reset.css';
import './styles/main.css';

export default class App extends React.Component {
// snip
}

To import CSS files in JavaScript, you need to use a module bundler like webpack to handle those imports statements. Start reading here: https://webpack.js.org/guides/asset-management/#loading-css. Doing this way you won't need to manually the CSS files in <head>.

In fact, you will be able to import your CSS from your components:

// MyToolbar.js component
import React from 'react';
import './styles/MyToolbar.css';

export default class MyToolbar extends React.Component {
   render() {
      // render your component here
   }
}

Once your app grows, you may want to experiment with other solutions, e.g. styled-components.

Upvotes: 3

Related Questions