import css in react
Code snippet for how to import css in react with sample and detail explanation
Incorporating Cascading Style Sheets (CSS) in React can be crucial to the functionality and overall aesthetic of an application, letting you structure, design, and lay out your web page as desired. This article aims to guide you on how to import CSS into your React application using a very basic example.
Code Snippet “Importing CSS in React”
You can import CSS file into your React component as follows:
import React from 'react';
import './App.css';
function App() {
return (
<div className="App">
<header className="App-header">
<h1>Welcome to my App</h1>
</div>
</div>
);
}
export default App;
Meanwhile, your CSS should be appropriately linked in your App.css
file:
.App {
text-align: center;
}
.App-header {
background-color: #282c34;
padding: 20px;
color: white;
}
Code Explanation for “Importing CSS in React”
In this tutorial, we thoroughly check the process of CSS importation in React through easy-to-understand steps.
First, analyze the React component code. Here, you see import './App.css'
at the top, indicating that we are importing a CSS file from the same directory where our React component file is located, in this case, the App
file.
After importing, we can use the CSS styles defined in App.css
in our React App
component. So, in this application, we’re applying some styling to a <div>
, which gets the className
of “App”, and a <header>
, which receives the className
of “App-header”.
Turn now to the App.css
file. The .App
CSS class sets the text alignment of our <div>
inside the App
component to the center. Nestled inside this <div>
is our <header>
with the App-header
class, which sets the background color, padding, and text color.
Remember, in React, you use className
instead of the class
attribute for adding CSS classes to your JSX elements. This method is a general principle when working with CSS in React applications, and it helps streamline your code and increases legibility and organization of your design components.
By importing CSS into your React application, it allows you to isolate and manage styles on a component-by-component basis, making your app more scalable and easier to maintain.