Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply CSS and Styling to a React component

Tags:

html

css

reactjs

People also ask

Can you add CSS to React?

You can create a new CSS file in your project directory and add your CSS inside it. You can then import it in your component, class or React JS page.

How do I change an element style in React?

You should have a initState like {style: {cursor: 'pointer'}} , and use style={this. state. style} , then in onclick, use setState to change that style to other like {cursor: 'crosshair'} ...etc.


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.


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.


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.


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>
    );
  }
});