score:0

I use Sass (.scss) to style my React components. I have also used PostCSS. And they are also modularized. Once you have it set up via your workflow (I use webpack), all you need to do to style your React app is to import the style.scss (yes, .scss) which contains your imported partials etc into your index.js file which resides in root along with your main App.js. That's where everything else you need in order to make your app work resides as well. For example, this is what mine looks like for the React app I am working on now:

Index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import 'core-js/es6/map';
import 'core-js/es6/set';
import App from './App';
import './favicon.ico';
import './style/style.scss';

ReactDOM.render(
    <App />, document.getElementById('root')
);

score:0

As for me, I don`t use CSS in react projects.

There is a library: Themeor where you can find a better and easiest way to style your SPA.

First step:

Instalation

npm i themeor

Second step:

Import Themeor elements from 'themeor'

import React from 'react'
import theme from './theme-light.json' // here is your config file
import darkTheme from './theme-dark.json' // if you set 'darkConfig' prop, the dark theme on user's computer will be detected automatically
import {Theme, Box, Font, Line, Fit, Align, Gap} from 'themeor'

export default function App() {
  return (
    <Theme config={theme} darkConfig={darkTheme} reset>
      <Font size="xl" weight="700">Imagine that I am your app</Font>

      <Gap />
      <Line fill="faint" />
      <Gap />

      <Align row gapHor="md" vert="center">
        <Box fill="accent" strong>
          <Gap vert="sm" hor="x2l">
            <Font size="sm" weight="700" uppercase>Text #1</Font>
          </Gap>
        </Box>

        <Line.TryTagless fill="critic">
          <Box fill="critic" radius="max">
            <Gap>
              <Font fill="critic">Text #2</Font>
            </Gap>
          </Box>
        </Line.TryTagless>

        <Box fill="base" strong radius="md">
          <Fit width="300px">
            <Gap size="sm">
              <Font underline align="center">Text #3</Font>
            </Gap>
          </Fit>
        </Box>
      </Align>
    </Theme>
  )
}

Third step: Usage:

  1. Align

Controls alignment and adjustment of children

import React from 'react'
import {Align, Fit, Line, Gap} from 'themeor'

class AlignDemo extends React.Component {
  render() {
    return(
      <Fit.TryTagless width="100%" height="200px">
        <Line.TryTagless>
          <Align vert="center" hor="center">
            <Fit cover="parent">Parent</Fit>

            <Line><Gap>Child</Gap></Line>
          </Align>
        </Line.TryTagless>
      </Fit.TryTagless>
    )
  }
}

It might be used other props to adjust the position of Align children as you wish. But in this example you can use simple props 'center' instead of:

.button_class:{position:'flex',
flexDirection:'column'
justifyContent:'center'
}

Full Align props description is here

  1. Box

If you need to draw a rectangle with background, border radius, box-shadow, background image, etc.

<Box fill="accent" strong radius="md">
<Gap><Font align="center">Medium Radius</Font></Gap>
</Box>

fill - background of the box. Every color is divided into seven families (base, faint, accent, complement, critic, warning, success) and can be strong (bright, saturated version) or weak (unsaturated, barely distinguishable). You can set colors in config as following:

{
  "fill": {
    "base": {
      "strong": "#000",
      "weak": "#fff"
    },
    "faint": {
      "strong": "#8994A6",
      "weak": "#F6F8FB",
    },
    "accent": {
      "strong": "#1273F3",
      "weak": "#EBF4FF",
    },
    "complement": {
      "strong": "#8889E2",
      "weak": "#EEECFD"
    },
    "critic": {
      "strong": "#F74545",
      "weak": "#FDEDED"
    },
    "warning": {
      "strong": "#E1922D",
      "weak": "#FCEBCF"
    },
    "success": {
      "strong": "#27AE60",
      "weak": "#DEF8E9"
    }
  }
}

For the full-color description with example and detailed explanation, you better click here

All components dimensions are the same as clothes dimensions - starts from "s" - and end with "x3l". All config is here

  1. Font

Controls all text parameters. Such as color, size, letter spacing, weight, etc

Text will be automatically inversed (switched from strong to weak) if it's placed upon strong background from config.themeContext.shallInverseOn

Example:

import React from 'react'
import {Font, Align} from 'themeor'

class FontDemo extends React.Component {
  render() {
    return(
      <Align pattern="1fr 1fr 1fr">
        <Font fill='base' weight="700" align="center">Bold Text</Font>
        <Font fill='accent' underline align="center">Underlined Text</Font>
        <Font fill='error' uppercase align="center">Uppercased Text</Font>
      </Align>
    )
  }
}
  1. Line

Controls all lines including borders

  1. Icon

Controls icons' color and size.

The first step here - you have to prepare and pass your icons to the Theme

import React from 'react'
import {Theme} from 'themeor'

// Import SVG
import ReactComponent as placeholder from './placeholder.svg'
import ReactComponent as bell from './bell.svg'
import ReactComponent as search from './search.svg'

// Form an object for medium size icons
const md = {placeholder, bell, search}

// Form an object to pass it to the Theme component
// Can contain keys according to the Scale (from x3s to x3l)
// If you use the same icons for different sizes, you can duplicate them
const iconSet = {xs: md, sm: md, lg: md, xl: md}

class App extends React.Component {
  render() {
    return (
      <Theme icons={iconSet}>
        Your app
      </Theme>
    )
  }
}

Then you have to call an Icon component:

import React from 'react'
import {Icon, Align} from 'themeor'

class IconDemo extends React.Component {
  render() {
    return(
      <Align row gapHor="lg" vert="center">
        <Icon />
        <Icon name="bell" fill="accent" size="lg" />
        <Icon name="search" fill="critic" size="xl" />
      </Align>
    )
  }
}

'placeholder' will be used as a default name

score:1

I think first of all you need to import your css or scss files, i recommend doing it to the direct path like:

import "components/card/card";

In order for this to work you need to have SASS loaders and webpack running in your project.

You need to have sass loaders in your webpack.config

  module: {
    loaders: [
      {test: /\.scss$/, loaders: ["style", "css", "sass"]},
      {test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader")},
      {test   : /\.woff|\.woff2|\.svg|.eot|\.ttf|\.png/, loader : 'url?prefix=font/&limit=10000&name=/assets/fonts/[name].[ext]'
      }
    ]

I recoomed use the "sass-loader": "^3.0.0",

The loader needs a workaround to work with windows, on mac it works fine:

  • Display hidden files on folder option.

  • Go to the folder 'user/appData', it should be on: C:\Users\user\AppData\Roaming\npm

  • Add the windows enviroment variable:NODE_PATH C:\Users\user\AppData\Roaming\npm\nodeModules

  • Run the command npm install -g

  • Close and reopen the command prompt.

With this you can load sass and compile it with webpack, and I do recomend using it with react, it's really powerfull.

If your not usng webpack you can find more here: http://webpack.github.io/docs/tutorials/getting-started/

And here you can check and example of webpack build process: Why is my webpack bundle.js and vendor.bundle.js so incredibly big?

score:3

Sass will let you nest your CSS selectors in a way that follows the same visual hierarchy of your HTML. Be aware that overly nested rules will result in over-qualified CSS that could prove hard to maintain and is generally considered bad practice. Let me explain with an example.

Hero.jsx

import "./Hero.scss";

import React, { Component } from "react";

class Hero extends Component {
  render() {
    return (
      <div className="hero-component">
        <span className="hero-header">Scss is awsome.</span>
      </div>
    );
  }
}

export default Hero;

Hero.scss

.hero-component {
    .hero-header {
        <!-- Hero header style goes here -->
    }

    .other-class {}
}

score:4

As Vijay mentioned, React prefers inline styles.

One common pattern is for each Component to have a single styles object that contains all the styles used in that Component, like so:

var styles = {
  navBar: {
    backgroundColor: 'dark blue'
  },
  center: {
    textAlign: 'center'
  },
  rightNav: {
  },
  verticalLine: {
  },
};

var NavBar = React.createClass({
  render: function() {
    return (
      <div style={styles.navBar} >
        <img src="logo.png" />
        <div style={styles.center} >
          <div>
            <ul>
              <li>daily specials</li>
              <li>gift gallery</li>
              <li>events</li>
              <li><i className="fa fa-search" />&nbsp;search</li>
            </ul>
          </div>
        </div>
        <div style={styles.rightNav}>
          <div style={styles.center}>
            <div>
              <button type="button">Sign Up</button>
              <button type="button">Log In</button>
              <div style={styles.verticalLine} >&nbsp;</div>
              <button type="button">Cart</button>
            </div>
          </div>
        </div>
      </div>
    );
  }
});

score:7

Technically you can add the CSS in the HTML document <head> as you would with a normal CSS file. So long as your React components have the same classes (except obviously applied as className no just class) then it will work.

If you're looking for something more modern and Javascript-oriented, you can look into CSS Modules, and read more about them here:

https://css-tricks.com/css-modules-part-1-need/

There's obviously a bit more of a learning curve with the second approach though.

score:12

If you want to keep things compartmentalized, you could create a .scss file for the specific component you are styling then import it in your component file.

Example:

Folder Structure:

components
|
|--Card
   |
   |--Card.js
   |--Card.scss
   |--index.js
|--Some Other Component Folder 

Card.js:

import React, { Component } from 'react';
import classes from './Card.scss';

export class Card extends Component {

    render () {
        return (
            <div className={`${classes.layout} col`}>
                <div className={`${classes.card} card`}>
                    <div className="card-image">
                        <ProviderImage />
                    </div>
                </div>
            </div>
        );
    }
}

export default Card;

Card.scss:

.layout {
    img {
        display: block;
        max-width: 372px;
        max-height: 372px;
        height: auto;
        width: auto;
    }
}

.card {
    width: 370px;
    height: 550px;
}

This keeps the styles contained to its respective component.

score:45

A first read through your question makes it seem that your existing CSS isn't working when you 'React-ify' your webpage.

It should.

If it's not, there's something else going on that will need further diagnosing to fix. I recently rewrote one of my projects in React and continued to use the exact same CSS file and things worked great.

However, if you're asking about the best way to go about this...

As others have said, React prefers inline styles.

However, I don't. It's messy, can be difficult to change, and easily gets unwieldy.

SCSS or LESS are the best ways to style in React.

But why? Here are a few reasons:

Your CSS Is Reusable

If you style inline with the React way, it works great for a couple components.

But when those components start to stack up, you start realizing you're using the same styles again and again. Which sucks.

It's Easy to Make Changes

When a component needs an updated style, you no longer have to dig through your React code to find the right component (or was it the parent component?) and fix it.

Instead, just use CSS like you've always used.

You Don't Have to Worry About Overwriting

In the cascading part of CSS, inline styles are the final stop. They overwrite everything.

At first, it sounds like a great solution to the styles you're implementing, and in a brochure website, perhaps it would be fine. But when you start working with bigger apps, you run into issues that are almost impossible to troubleshoot.

Instead of fighting with the cascading part of CSS, work with it and keep your styles in the same place.

You Use SCSS & LESS Everywhere

The biggest point for me is yes, if you're working in React and you prefer inline styles, they can work great.

But what happens when you move to any other framework? All of a sudden those inline styles don't work so well, and you're back to writing 'normal' CSS with the rest of us. So why change things up just for one framework?

I understand if you work in React full-time and it makes sense to experiment with new best practices, but for most of us, it doesn't make sense to re-invent the wheel when you only can use that wheel on one model of car.


Related Query

More Query from same tag