Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I use css in reactJS? [closed]

I am new to reactJS with ES6 and have read a lot about CSS and the problem they are trying to solve is the global style.css and instead use

styles/index.js

var styles = {
  transparentBg: {
    background: 'transparent'
  }
};

Many argue that you should go back and write CSS (I do not know what reacts name is for CSS, the code above) in each class instead of a separate file if you do not have hundreds of CSS classes. This feels weird. Is it true?

Many CSS frameworks, as popular Bootstrap is still in "old" CSS. Does it matter? Know that the application still works but there must be some reason that react chosen to do it this way. Can I do something about it?

What is the best practice when using CSS and CSS frameworks with ReactJS?

like image 301
Anders Avatar asked Nov 29 '22 14:11

Anders


1 Answers

This is subjective, but in my opinion, it's more practical to use traditional CSS via CSS Modules and PostCSS.

For example, you may have a CSS file like this:

.btn {
  border: 1px solid black;
  border-radius: 2px;
}

.icon {
  background: url(...);
}

Which is used a React component via css-loader?modules=true as follows:

import React from 'react';
import s from './Button.css';

function Button() {
  return (
    <button className={s.btn}><i className={s.icon} />Click Me</button>
  );
}

export default Button;

With the magic of CSS Modules that component will be rendered to the following HTML markup in debug (development) mode:

<button class="Button_btn_d41d8"><i class="Button_icon_7b91e"></i>Click Me</button>

Where each CSS classname is composed of <ComponentName>-<ClassName>-<Hash>, effectively avoiding conflicts between CSS classnames with the same names accross multiple components. And in release (production) environment, the same component will be rendered to:

<button class="d41d"><i class="7b91"></i>Click Me</button>

Where each class name is just a 4-5 characters long hash string.

This is how it works in React Starter Kit (disclaimer: I'm the author)

like image 95
Konstantin Tarkus Avatar answered Dec 04 '22 11:12

Konstantin Tarkus