What are the guidelines for handling CSS in a ReactJS prject?

Viewed 113

I'm not sure about what is the best practice for handling CSS in ReactJS. With create-react-app it automatically generates some .css files, so I naturally kept working that way. Sometimes though, it's more convenient to use inline CSS for tweaking some elements of the page. Sometimes I've seen components that require to set the styles in a const and use them within the component. What are the guidelines to handle CSS within a ReactJS project?

What I'm doing now is creating (if needed) for each component a .css file with classes I might use more than once, and using inline to do small tweaks as marginTop: 5px. Is this bad?

3 Answers

Using CSS for small projects is okay, but certainly not ideal. CSS is not cross browser compadible and will require a lot of additonal code and in some browsers will not function properly. There are many modern tools out there that can be used, I personally usually uses reacts inline styles for small projects and Stylus (preprocessor for largar projects). I would suggest that you take a look at the following article, it will get you started in the direction you want to go down.

https://www.javascriptstuff.com/how-to-style-react/

It's not about bad practice. Plain CSS or CSS modules are not cross browser compatible. For example, transform property is different for mozilla. Some libraries help. You can look for libraries like SASS, Styling Components.

Inline styling is helpful only for static pages and non reusable styles as you already know it.

I use styledComponents which offers bridge between Inline styling and resuability. It goes like this : Inside the component jsx :

const styledDiv = styled.div'//CSS styling inside'; . . . return (<StyledDiv>I'm styled</StyledDiv>) ;

https://www.styled-components.com

Styled Components generate class names at runtime which uses some hashing. SASS has its own advantage too. Its native CSS styling concepts and easy testing of styles by class names. You can explore more from here.

You have many option for styling your components. But using inline-styling is not the best practice, because when you have to alter it later, it would be a mess. You can style your components using:

  1. Use built-in components from libraries such as MaterialUI, AntD, Bootstrap.
  2. Use Css files.
  3. Use Javascript object for styling. And apply those object as style={someStyle} to your HTML in React.

Hope this helps.

Related