Home » React JS

How to add CSS Style in React JS components and React JS App?

In this article, we will learn how to add some CSS styles in React JS app or how to style up some components using CSS or bootstrap?
Submitted by Godwill Tetah, on November 18, 2019

In this tutorial, we will only work with CSS styles. Please ensure you have basic knowledge of HTML, CSS, React JS and Node.Js.

In our recent articles, we talked about React JS components and how to add components in other files?

We said the first step to adding a component from an external component is to import the file into the main component.

Adding a CSS file in our React JS app is also as simple as importing a file in the React JS App.

Let's dive into our code.

Create a CSS file in the same folder with your component's file.

index.css

body {
    color: blue;
}

table {
    border-collapse: collapse;
    width: 50%;
}

th,
td {
    text-align: left;
    padding: 8px;
}

tr:nth-child(even) {
    background-color: #f2f2f2
}

th {
    background-color: yellow;
    color: green;
}

.go {
    background-color: lightblue
}

#form {
    input[type=text]:focus {
        background-color: lightblue;
    }
}

Let's add some code in our main component file,

App.js:

import React from "react" 

class App extends React.Component {
	render (){
		return (
			<div className = "go">
				<center>
					<h1> React is Cool!</h1>
					<table>
						<tr>
							<th>Course</th>
							<th>Day</th>
							<th>Coeff</th>
						</tr>
						<tr>
							<td>Algorithm</td>
							<td>monday</td>
							<td>5</td>
						</tr>
						<tr>
							<td>Database</td>
							<td>friday</td>
							<td>4</td>
						</tr>
					</table>
					<hr/>
				</center>
			</div>
		)
	}
}
export default App

Finally, our index.js where we will import our CSS file using the import keyword followed by the name of our CSS file.

import React from "react"
import ReactDOM from "react-dom"
import App from "./App"
import "./index.css"     

ReactDOM.render ( <App />  , document.getElementById('root'))

Also, adding style to a class is simply by adding the class name in your CSS code. I know you may wonder why I gave used className to assign an attribute to my div.

That's the right syntax actually because we are writing JavaScript.

Run your app and open in browser...

React JS | Adding CSS styles in React JS App | Example

Thanks for coding with me! See you @ the next article. Feel free to drop a comment or question.




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.