Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In React, how to prevent a component's CSS import from applying to the entire app?

I'm using facebook's create-react app for my application:

In my Login.js container, I am importing CSS like so:

import React from 'react';
import '../../styles/users/Login.css'
const Login = () => {
....

The problem is the Login.css styles are being applied to my entire application... for example, if Login.css has:

body {
    background:Red ;
}

The entire app would have a body of background: Red; Even outside of the Login container.

What I expected/want is for a CSS import within a container to only apply to that particular container.

Is that possible w React? How are react developers supposed to handle container specific stylings? Do I need to add an ID to all containers and include that in the entire CSS file?

like image 499
AnApprentice Avatar asked Jul 08 '17 17:07

AnApprentice


1 Answers

1. Solution: Give your DOM elements class names to use them in your css.

JS:

// in Link.js

import React from 'react';

import '../../styles/Link.css'

const Link = ({children, href}) => (
   <a className="link" href={href}>{children}</a>
);

CSS:

// Link.css

.link {
    color: red;
}

2. Solution: Inline styles.

JS:

// in Link.js

import React from 'react';

import '../../styles/Link.css'

const Link = ({children, href}) => (
   <a style={color: 'red'} href={href}>{children}</a>
);

3. Solution: CSS in JS.

There are some libraries that try to solve the styling issue:

Watch this talk: https://speakerdeck.com/vjeux/react-css-in-js

And have a look at this: https://github.com/cssinjs

styled-components: https://github.com/styled-components/styled-components

like image 126
trixn Avatar answered Nov 07 '22 14:11

trixn