Day 23:

Today I'm going to be discussing a topic I've learned a while ago, but I thought I'd share today since I've been speaking about CSS for the past few days. Let's talk about CSS in React! React.js is a front-end view library that allows you to easily create user interfaces for the browser (and potentially iOS and Android through React Native). When you're normally styling some elements, you write down your styles in a CSS file, write your selectors and that's that. Yet in React, there's lots of opportunity to "componentize" your elements. Let's take a look at the different ways to use CSS in a React project! From styled components to just using a plain CSS file there's tons of options!

Using plain CSS is probably one of the simpler solutions. You need to make sure your CSS is included on your site and then you can use classes and ids on your elements in order to style them. If you're using "create-react-app" a way to import your CSS is as follows:

import "./myFile.css"
To use it you'd add classes and ids to your elements. Let's say you wanted to add a "main" class to your div and a "importantInput" id to your input. It would look something like this:
<div className="main"></div><input id="importantInput"/>

CSS modules are a slightly more complicated way to use your CSS files. This method is built-in if you're using "create-react-app". To import a CSS file using CSS modules you'd write an import statement like this:

import style from "./myFile.css"
Using the same class as above, in order to add a "main" class to your div it'd look something like this:
<div className={style.main}></div>
What's the difference between this method and the last one? By using CSS modules your CSS is "scoped" to your components. That means you could have another class called "main" in another CSS file and it wouldn't interfere with this one.

If you'd rather not use a CSS file, you can write your CSS as an object and apply it as follows:

function App(props){
	const obj = {
	backgroundColor: "blue"
	}
	return <div style={obj}></div>
}
In React, your CSS object has to call properties using camelCase (i.e. separating a word by capitalizing the next one) instead of using dashes between words like in regular CSS.

Finally, another option available to you is styled components. An example of a styled components library is "styled-components". There's lots to choose from so find one that best fits your needs.

Good luck and use whatever tool best suits you! Until next time!

Do you have a reply you want to share? You can send me the URL here: