Importing CSS Files in React

Importing CSS Files in React

Importing CSS Files in React. Creating components in React is fairly easy. If you're coming from a component-based framework, like Angular, you're already used to the markup+logic+style trio. By using JSX, you can put markup and logic together, in the same file.

Creating components in React is fairly easy. If you’re coming from a component-based framework, like Angular, you’re already used to the markup+logic+style trio. By using JSX, you can put markup and logic together, in the same file. This is really nice. So you ask me: “How to import CSS files in a React application?”. This is exactly what you will learn in this article. And I can give you a spoiler: it’s very simple.

Our example application

To illustrate this article, we are going to use a tiny React application:

const App = () => (
  <div>
    <MovieCard
      imagePath="https://i.imgur.com/mtR0tjU.jpg"
      title="The Godfather"
      text="A 1972 film directed by Francis Ford Coppola."
      oscars={3}></MovieCard>
    <MovieCard
      imagePath="https://i.imgur.com/mhzWZtB.jpg"
      title="The Untouchables"
      text="A 1987 film directed by Brian De Palma."
      oscars={1}></MovieCard>
  </div>
);

The component above prints two cards with basic information about classic movies. It depends on aMovieCard component, which renders a card with image, title, description and number of Oscars won. Let’s check it out:

const MovieCard = (props) => (
  <div className="movie-card">
    <img src={props.imagePath} className="movie-card__image" />
    <div className="movie-card__content">
      <h3 className="movie-card-content__title">{props.title}</h3>
      <p className="movie-card-content__text">{props.text}</p>
      <ul className="movie-card-content__oscars">
        { renderOscars(props.oscars) }
      </ul>
    </div>
  </div>
);

Finally, let’s see how the renderOscars function is implemented:

function renderOscars(oscars) {
  const output = [];

  for(let i = 0; i < oscars; i++) {
    output.push(
      <li className="movie-card-content-oscars__item" key={i}>
        <img src="https://i.imgur.com/w1wYJwi.png" />
      </li>
    );
  }

  return output;
}

Simple, isn’t it? Here’s how it looks:

Well, it’s raw, it’s ugly, but it works. Note that our markup uses the className attribute instead of class. Since JSX is an extension of JavaScript, this approach prevents conflicts with the reserved keyword class.

Now we need to style our application.

Setting up Webpack

To import CSS files in a React application, you need to configure the Style and CSS loaders first.

Install both loaders:

npm i css-loader style-loader --save-dev

Or, if you love Yarn:

yarn add --dev css-loader style-loader

Add this entry to the module.rules array, in your webpack.config.js file:

{
  test: /\.css$/,
  use: [
    'style-loader',
    'css-loader'
  ]
}

That’s all. Now you can run your application.

Importing a CSS file

First, we will create a file called app.css in the same directory as your App component. To make it easier to determine if it works, we’ll add the following rule to our new stylesheet:

.movie-card {
  background-color: red;
}

Now, we can import the app.css file in our application.

import React from 'react';
import './app.css'; // here is where the magic happens

const MovieCard = (props) => (
[...]

**Note:**In order to simplify things, I’ve saved both MovieCard and App components in the same file.

This is how your application should look like:

The next step is to beautify things.

Making our cards look like real cards

Let’s style each element individually.

First, we will normalize the rem/px proportion and make every element use the border-box sizing:

* {
  box-sizing: border-box;
}

html {
  font-size: 62.5%;
}

Now, we can style the card wrapper:

.movie-card {
  display: inline-block;
  height: 470px;
  width: 300px;
  border: 1px solid #DDD;
  border-radius: 10px;
  overflow: hidden;
  vertical-align: top;
  margin: 5px;
  box-shadow: 1px 1px 3px rgba(0,0,0,0.05);
}

The card content container:

.movie-card__content {
  font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif;
  padding: 15px;
}

The title and body:

.movie-card-content__title {
  font-size: 2rem;
  margin: 0;
}

.movie-card-content__text {
  font-size: 1.6rem;
  line-height: 2rem;
}

Finally, the Oscars list:

.movie-card-content__oscars {
  list-style-type: none;
  padding: 0;
}

.movie-card-content-oscars__item {
  display: inline-block;
}

.movie-card-content-oscars__item img {
  width: 25px;
}

And voilà:

This looks a lot better, right?

Conclusion

  • The CSS and Style loaders are necessary to import CSS files in a React application.
  • As with JavaScript, importing CSS files is made with the importkeyword.

Learn More

The Complete React Web Developer Course (2nd Edition)

Node with React: Fullstack Web Development

Beginner Full Stack Web Development: HTML, CSS, React & Node

React JS and Redux - Mastering Web Apps

React 16 - The Complete Guide (incl. React Router 4 & Redux)

MERN Stack Front To Back: Full Stack React, Redux & Node.js

The Web Developer Bootcamp

Build Responsive Real World Websites with HTML5 and CSS3

Web Design for Beginners: Real World Coding in HTML & CSS

Beginner Full Stack Web Development: HTML, CSS, React & Node

The Complete HTML & CSS Course - From Novice To Professional

Css is not used by jsx in ReactJS

I use ReactJS with Webpack and TypeScript. I'm trying to include CSS with React. But my CSS is not use by my React application. I created a global.d.ts file to declare my css module. I imported my css into my.tsx file but when I add a class to an element, nothing works.

I use ReactJS with Webpack and TypeScript. I'm trying to include CSS with React. But my CSS is not use by my React application. I created a global.d.ts file to declare my css module. I imported my css into my.tsx file but when I add a class to an element, nothing works.

I have already tried to install a css module but I didn't succeed. So, I just made the solution to create a global.d.ts file

global.d.ts :

declare module '*.css';

Hello.tsx

import * as css from './Hello.css';

export interface HelloProps {
compiler: string;
framework: string;
}

export class Hello extends React.Component<HelloProps, {}> {

render() {
return (
<form>
<p className={css.test}> Test </p>
</form>
);
}
}

Hello.css


.test {
color: red;
}

webpack.config.js

module: {
rules: [

 .....

 { test: /\.css$/, exclude: /node_modules/, use: ['style-loader', 'css-loader'] }

]
},

The word "test" is written in black. When it should be in red

How to use CSS in JS with React / CSS & Inline Styling

How to use CSS in JS with React / CSS & Inline Styling

In this tutorial, you will learn how to style your components in react. I will take a look at how you can use inline styles, regular CSS classes, CSS modules or react styled components...

CSS in JS isn't unique to React, however, I'm a little React fanboy and it happens to be one of my favorite JS libraries to write front end applications with, so I'm going to be talking about CSS in JS solutions specifically with React and how I feel about them!

Introduction with regular CSS

Before we dive into anything I think we should take a look at what we can accomplish with some good ol' CSS in the context of a React application.

// Button.js
import React from 'react'
import './Button.css'

const Button = () => {
return(
<button className="button button-green">
I think I'm green
</button>
)
}


/* Button.css*/
.button{
border-style: solid;
border-width: 2px;
border-radius: 2rem;
}

.button-green {
background-color: green;
border-color: white;
color: white;
}

So this looks fairly normal, right? It looks like some regular HTML and CSS besides the className. If you're not familiar with React class === className because class is a reserved word in JS, and since JSX is HTML with embedded JS this is a nono.

Issues I have run into using CSS with React

Before we start here I need to state that I am definitely not an expert or guru of CSS. I can kick my feet around with it and make responsive rules that look alright. I can't name any crazy CSS tricks or create an animated Pikachu in pure CSS.

Because of this, I'm not going to even pretend to talk about all the pitfalls with CSS or any new features with CSS that aim to fix these pitfalls, so I'm going to drop this excellent resource from 2014. I'll let you decide if it still holds up! ;)

Global Namespaces

Are you saying I'll be able to use BEM?
When the time comes, you won't have to.

If you took a look at that link I put up above, you'll notice that global namespaces are the first issue it covers with CSS. However, we've all felt this tremor, which is why naming conventions like BEM exist.

.button and .button-green from our CSS example is already 2 global namespaces we introduced.

As an application grows, I've found that the CSS rules are written also grows continuously. Creating unnecessary duplicate styles with small tweaks and unused styles bulking up the application. While there are configs out there to make sure unused CSS isn't included in your bundle, they don't vanish from your codebase and that sucks.

Loose Coupling

While you can structure your react app so that your component styles exist in the same directory as your component, there's nothing in your component file strictly tying it together. Instead, you're referencing the rules you've specified for your selectors. Despite the file structure, those styles can be referenced elsewhere; It's just another thing to think about.

Clunky Controls

When using just CSS you're more or less stuck controlling all your styling changes based on changing the class of an element. While this seemed maybe more natural with something like Vanilla Javascript or JQuery, it always felt hacky to me when using React. You have this direct access to your view all in separated components yet we're throwing all this logic to reference different combinations of CSS classes.

I know Inline Styling

Another way to style your React app without any modules is inline styling. Now, pay no attention to the person in the back yelling about how bad inline styling can be, because that's actually me in disguise. We were all taught that inline styles in HTML are bad and class-based styles were rad. However, this is JSX.

// Button.js
import React from 'react'

const Button = () => {
const buttonGreen = {
backgroundColor: "green",
border: "2px solid white",
borderRadius: "2rem"
color: "white"
};

return(
<button style={buttonGreen}>
I think I'm green
</button>
)
}

This doesn't look so bad right?

You may notice that the CSS rules here don't quite look the same. Instead of seeing Kebab Case we are using Camel Case for our rules. They are mapped out in a Javascript Object with their values wrapped in quotations as a string

Global Namespaces

In our inline styling example, buttonGreen is local to that file, so we can have as many buttonGreen vars as we want across the application without running into any conflicts or following any specific naming conventions!

Loose Coupling

With these styles being locally defined, you can't use these styles unless you go through the effort to exporting and importing them; Ideally, there are enough steps to stop the bad things from happening.

I think it also promotes developers to use React in a more intended way to create generic components that can be reused.

Clunky Controls
// Button.js
import React from 'react'

const Button = ({backgroundColour, colour, children}) => {
const buttonStyles = {
backgroundColor: backgroundColour,
color: colour,
border: "2px solid white",
borderRadius: "2rem"
};

return(
<button style={buttonStyles}>
{children}
</button>
)
}


// SomePage.js
import React from 'react';
import Button from 'Button';

const SomePage = () => (
<Button backgroundColour="blue" colour="white">I'm going to be blue</Button>
)

Now, this is a super simple example but we can see that we have given our Button specific control over the colours through some props that's passed into the component. I like this approach because it's self-documenting and it keeps all the logic in the component; I know exactly what the prop in the component is controlling and the usage of the component is very clear that it's setting the backgroundColour to blue and the colour to white.

What I don't like about Inline Styling

Using objects for styles

I'm not a fan of this syntax for styling. It's enough of a departure that can cause enough tedious work converting CSS into Javascript objects replacing ; with ,, wrapping rules in "", and casing the keys into camel case. It's also scary enough for your designers that this approach can get shut down at the sight of it.

Inline styling is still inline

At the end of the day, this is still inline styling and your HTML will still end up with those ugly style attributes.

Would I personally use Inline Styling in React?

Nope.

But that's not the end for dear old CSS in JS! There are some pretty cool packages out there that do cool stuff and try to solve all kinds of issues regarding readability, scalability, and performance with CSS in JS.

In this series, I'm going to try and look at a diverse pool of these solutions whether they are highly rated or buried underneath.

As of writing this, I have used Styled Components, Emotion, and JSS. If you think one is really cool feel free to drop a comment about it!

Originally published by Phil Tietjen at dev.to

=====================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Build a Custom Full Page Slider with CSS and JavaScript

Implementing a Scroll Based Animation with JavaScript

Beginner Full Stack Web Development: HTML, CSS, React & Node

How To Build A Captivating Presentation Using HTML, CSS, & JavaScript


CSS and JS Are at War, Here’s How to Stop It

<strong>TL;DR:</strong>&nbsp;There are a lot of people who love&nbsp;<strong>both</strong>&nbsp;JS and UX/CSS/etc. If&nbsp;we&nbsp;stop labeling people just as “JS developers” or “UX developers”, we&nbsp;can&nbsp;achieve a ceasefire in the current “JS vs. CSS” war and&nbsp;get&nbsp;closer&nbsp;to&nbsp;peace.

TL;DR: There are a lot of people who love both JS and UX/CSS/etc. If we stop labeling people just as “JS developers” or “UX developers”, we can achieve a ceasefire in the current “JS vs. CSS” war and get closer to peace.

The War is Real

Some call it The Great Divide: the frontline is real, with JavaScript diehards on one side, and UX/CSS people who advocate non-JS approaches to interfaces—on another.

Front-end developers are afraid of losing their jobs if they avoid the whole JavaScript hype. And it is perfectly understandable: CSS is out of trends. There are significantly fewer CSS conferences and meetups compared to JS/React and friends. For instance, there are 6+ JS meetups in New York and 0 regular CSS meetups.

On the other hand, we see simple static websites being over-engineered out of a sheer FOMO.

We see prominent figures in the front-end community passing the blame on each other every day and that is unfortunate, to say the least.

Look Beyond

The warring factions are often labeled as:

  1. “JS-JS-JS”: Developers who create SPA with client-side JavaScript frameworks like React, Vue.js, and Angular. They are heavy users of innumerable build tools (Babel, webpack, etc.) and JS libraries.
  2. “UX developers”, “CSS developers”, “HTML-JS-CSS developers”: Developers who create static websites with vanilla JavaScript and plain CSS. Accessibility and performance are most important topics in their community.

But do we have to have this split? Maybe this dualism is based solely on our own bias?

In my opinion, this bias is largely caused by two things.

First of all, there is a trend to separate CSS and JavaScript conferences. I think it got started by a very popular and successful JSConf/CSSConf family of events and by a trend for Put-Your-Own-City-Here.js meetups. Content platforms also support the divide: some of them publishe mostly React/JS articles, others focus on CSS and UX.

Second of all, social networks are good at polarizing society. We put ourselves in a bubble of likeminded individuals by subscribing to their feeds and make things even worse by reposting only the most aggressive opinions coming from the other side.

The modern web is incredibly complex. It is extremely hard to master all the technologies that power it and no one can really call oneself a 100% “full-stack” developer. But due to the fact that the JS and CSS/UX discourses have become so (artificially) separated, people with different, but not necessarily opposing passions are bing shoved into a black-and-white “JS vs. CSS” world view. React developers who are passionate about CSS animations and a11y are labeled simple as “JS folks”. And a CSS developer who loves Babel and zero-runtime CSS-in-JS will still be painted as a “CSS guy/gal”.

People Who Love Them Both

As a creator of PostCSS, I could never really pick a side, even if I wanted to. On one hand, PostCSS is a tool for CSS (hence the name). On another hand, PostCSS is a JavaScript build tool and build tools are not well accepted in a modern CSS community.

And I am not alone, there are so many people like me: the creator of an amazing React toolkit for animations, or the creator of a CSS a11y linter, to name a few.

To say the truth, each of us knows only a small subset of technologies that exist out there. And one’s passions not necessarily come from a single topic either. It is OK to love both React and CSS. Or use complex build systems to be sure about you got your a11y right. Or you can dive into distributed systems because you want to make great UX with a bad Internet connection.

Even technologies themselves cannot be seen in black and white.

BEM is often mentioned by the proponents of “CSS faction” as a way to avoid the possible confusion of CSS-in-JS. But few people know that it was not designed by Yandex as a purely CSS technology! It also contains a JavaScript framework and originally had a set of ideas that were later used in React (like nesting small isolated components).

ESLint configs, popular in React community (like AirBnB config), contain a lot of a11y rules.

The Solution

I think the war is real. I think we can stop this war if we stop dividing developers into black and white categories.

  1. If you like technologies from both “sides”: say it out loud! Make it visible, so people can start a civilized discussion. Do you like modern JS frameworks, but also like creating static websites that don’t involve client-side rendering at all? Tell the world about it. Open source authors will create more frameworks for static websites, if they see the need.
  2. Let’s have a public forum for a conversation between JS and CSS worlds. If you are organizing a JavaScript meetup, set aside a day for CSS/UX talks. Let’s “front-end” conferences instead of “JS conferences” and “CSS conferences”, where people from different camps could explain their daily problems and preferred solutions to their opponents.
  3. Let’s try technologies coming from “the other side”:
  • If you are a CSS/UX developer, start with linters. Stylelint is a good CSS linter to start with. It will warn you about mistakes and allow you to share best practices across the team. And you can run it as a plugin for your favorite text editor, so you can start even without any bundlers.
  • If you are React developer, try some vanilla JS on your next landing page or a blog. This will allow you to better understand your framework’s internals. And your users will thank you for increased performance due to a lighter JavaScript bundle.


by : Andrey Sitnik