React + CSS

Paul Ly
5 min readOct 22, 2018

There are several ways of implementing CSS within a React application — let’s explore some of them!

Image result for react css

I remember having first learned React, it was challenging from the get-go:

  • State vs Props
  • JSX vs JavaScript vs HTML
  • Lifting state
  • How to connect CSS

It was one thing after another and after seeing a friend starting to learn React these past couple weeks, I realized that I wasn’t the only one who might have struggled with how CSS comes to play with React!

Inline

With the Element

The most basic way to include some CSS styling in React.

render() {
return (
<h1 style={{ backgroundColor: 'red', color: 'white' }}>
Hello World
</h1>

)
}

Notice that the syntax isn’t the CSS way but the JavaScript way! Instead of the “-”, use camelCase and all the values should be in quotes followed by a comma rather than a semi-colon.

For example:

font-size: 12px;           -->    fontSize: '12px',
background-color: black; --> backgroundColor: 'black',

Passed via Variable

You can also do inline styling like this; it is most definitely easier to read and manage.

const styles = {
backgroundColor: 'red',
color: 'white'
}
render() {
return (
<h1 style={styles}>
Hello World
</h1>

)
}

You may also take the previous manner and implement it as the following:

const styles = {
h1: {
backgroundColor: 'red',
color: 'white'
},
p: {
backgroundColor: 'blue',
color: 'green'
},
}
render() {
return (
<div>
<h1 style={styles.h1}>
Hello World
</h1>
<p style={styles.p}>Enter Text Here</p>
</div>
)
}

CSS Files

Normally you would have a separate CSS file and include it as a link tag in the head of the index.html file, or the respective html file.

<link rel="stylesheet" href="styles.css">

Instead of doing this, in React you may also simply include it in your JavaScript file such as App.js.

# App.jsimport 'styles.css'

This way you could continue writing the CSS you already know and love!

# styles.css.title {
background-color: black;
color: white,
}

Bringing it Together

In my most recent project, Hello World, I created a directory for CSS files and then imported them all into my App.js file. But when it came to combining that with reusable components I had made, I tried a different approach.

# App.jsimport './css/App.css'
import './css/TopBorder.css'
import './css/Nav.css'
import './css/Auth.css'
import './css/Chat.css'
import './css/Profile.css'
import './css/Lists.css'
import './css/List.css'
import './css/Contact.css'
import './css/Home.css'
import './css/About.css'

Here’s a reusable component I created and used in several place throughout my application — it’s an image component to be used as a user’s profile icon.

# UserIcon.jsimport React from 'react';const UserIcon = ({ onClick, imgSrc, containerStyle, imgStyle }) => {  
return (
imgSrc ?
<div
onClick={onClick}
style={containerStyle}
className='usericon-container'
>
<img
style={imgStyle}
className='usericon-img'
src={imgSrc}
/>
</div>
: null
)
}
export default UserIcon;

It’s dynamic as you can pass down functions and different styles as props to be used in different areas of the application.

Here it is being used in my user profile component:

# ProfileContainer.jsimport UserIcon from '../UserIcon'const containerStyle = {  
backgroundRepeat: 'no-repeat',
backgroundSize: 'contain',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F7A278',
}
const imgStyle = {
borderRadius: '50%',
height: '30vh',
maxWidth: '30vw',
marginLeft: '0.25rem',
}
const Profile = ({ currentUser, userPfView }) => {
return userPfView || currentUser ? (
<div className='profile'>
<UserIcon
containerStyle={containerStyle}
imgStyle={imgStyle}
imgSrc={ userPfView ?
userPfView.profile_picture
: currentUser.profile_picture }
/>
...
</div>
) : null
}

And here it is being used in my chat component inside a list of users:

# Chat.jsimport UserIcon from "../user/UserIcon";const containerStyle = {  
width: "1rem",
backgroundRepeat: "no-repeat",
backgroundSize: "contain",
alignSelf: "center",
margin: "0",
position: "relative",
top: "0.3rem"
};
const imgStyle = {
borderRadius: "50%",
width: "2rem",
height: "2rem",
position: "absolute",
top: "-1.3rem",
marginRight: "1rem"
};
class Chat extends React.Component {
...
renderUsers = () => {
...
return filtered ? filtered.map(user => { if (chattingUsers.includes(user.id)) {
openChatClass = "user active-chat";
} else {
openChatClass = "user";
}

return (
<div
key={user.id}
className={openChatClass}
onClick={e => this.handleClick(e, user)}
>
<UserIcon
onClick={this.handleUserPicClick}
containerStyle={containerStyle}
imgStyle={imgStyle}
imgSrc={user.profile_picture}
/>
<p>{user.username}</p>
</div>
)
}

render() {
...
return (
...
<aside className="users-list">{this.renderUsers()}</aside>
...
)
}
}

There’s a couple of things to note here:

  1. I’ve redefined the container style and the image style to be passed down into my UserIcon component differently than how it was in my user profile component.
  2. I’m toggling what class names to be included on the component when it is rendered based on a conditional. I already defined two separate styles, user and active-chat, in Chat.css and by declaring a variable to contain the respective class names I would like and defining it based on a if-else control-flow statement, I can manage how it looks on the page.

Styled Components

I dabbled with styled components when I was actively developing Hello World, and it was a lot of fun!

But it was also a little confusing at first. I read the documentation and followed along, but when it came to implementing it on my own I was at a loss for code.

To include it within your application:

# terminal
npm install --save styled-components

Then you may start creating HTML elements via this library with the syntax they require. Here we created a div tag and an h1 tag with their respective CSS styles.

# Component.js
import React from 'react'
import styled from 'styled-components'
const TitleWrapper = styled.div`
padding: 4em;
backgroundColor: black;
`
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: green;
`
export default class Component extends React.Component {
render() {
return (
<TitleWrapper>
<Title>Hello World</Title>
</TitleWrapper>
)
}
}

You may have noticed that the syntax is exactly the same as regular CSS, with the exception of it being inside back ticks.

Once you import it, you can build HTML DOM elements by declaring and defining a variable with styled + DOM element.

<div></div>        -->    styled.div`...`
<span></span> --> styled.span`...`
<a></a> --> styled.a`...`
<button></button> --> styled.button`...`

You could take use the power of styled components and create your own re-usable components! Then you could import the components wherever you may need them.

There you have it — various ways of implementing CSS into a ReactJS application! I know for a fact these aren’t all of them; there are plenty of other libraries and frameworks that help. I wanted to provide the ways I know of and present them in an understandable manner.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Paul Ly
Paul Ly

Written by Paul Ly

Full-Stack Web Developer - Former JPM Analyst, ESL Teacher, and Expat

No responses yet

Write a response