Use External CSS in React.js

Create a CSS File

Create a folder named css inside src, and then add a file named style.css:

src/css/style.css


Write Styles in style.css

.heading {
color: green;
}

.img-style {
width: 200px;
}

.user-card {
margin: 10px;
width: 200px;
border: 1px solid black;
box-shadow: 1px 1px 3px 1px #ddd;
}

.text-wrap {
padding: 10px;
}

.container {
display: flex;
flex-wrap: wrap;
}


Import CSS File in Your React Component

To apply external styles in React, import the CSS file at the top of your component like this:

import "./css/style.css";


Use className instead of class for JSX:

<h1 className="heading">External Style</h1>


Create a Simple Card with External Style

Now we will create multiple user cards using the external CSS classes.

<div>
<h1 className="heading">External Style</h1>
<div>
<img src="https://www.w3schools.com/howto/img_avatar.png" alt="" />
<div>
<h4>Anil Sidhu</h4>
<p>Software Developer</p>
</div>
</div>
</div>


Full React Component with External Styling

Below is the full React component that shows multiple user cards with external styles applied. (Code untouched)

import "./css/style.css"; // Importing CSS file for styling

function App() {

return (
<>
<h1 className="heading">External Style</h1>
<div className="container">
{/* Repeated cards */}
<div className="user-card">
<div>
<img
className="img-style"
src="https://www.w3schools.com/howto/img_avatar.png"
alt=""
/>
<div className="text-wrap">
<h4>Anil Sidhu</h4>
<p>Software Developer</p>
</div>
</div>
</div>

{/* Copy this div to make more cards */}
{/* ...more cards */}
</div>
</>
);
}

export default App;

\

If you want to apply styling globally to your app, you can also import the CSS file in main.js instead of App.js.

import './css/style.css';

This will apply styles across your entire project.