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"
<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"
<div className={style.main}></div>
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>
}
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!