React JS Tutorial - CSS Files
In this tutorial, we will learn about using CSS files in React. Let's see how we can add CSS to a React component.
Switch to your project and recall the form we created in the previous video. Now, let's add CSS to this form to improve its look and feel. To do this, create a new file inside the component directory, for example, AddEmployee.css.
Next, add this CSS file to the AddEmployee component. Open the AddEmployee component and add the following code:
import './AddEmployee.css';
Now, add the className attribute to the form element in the AddEmployee component:
<form className="empform">
Write the CSS for this class in the AddEmployee.css file:
.empform{
border-radius: 5px;
background-color: #f2f2f2;
padding: 20px;
width: 400px;
margin: 10px auto;
}
Save the file and let's check the result. Go to your browser, and you should see that the CSS has been applied to the form.
Now, add some CSS for the input fields and submit button. Go to the AddEmployee.css file and add the following code:
input[type=text],
input[type=email],
select {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
Add CSS for the submit button:
button[type=submit] {
width: 100%;
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
button[type=submit]:hover {
background-color: #45a049;
}
Save the file and let's check the result. You should see that the form, input fields, and submit button have all been styled.
Next, add CSS for the employee list. In the AddEmployee.css file, add the following code:
.empitem {
background: #f2f2f2;
padding: 20px;
max-width: 400px;
margin: 20px auto;
border-bottom: 2px solid #bbb;
}
Add this class to the employee list div in the Employees component by adding the ClassName attribute:
Save the file and let's see the result. You should see that the employee list has been styled.
This demonstrates how to use CSS with components in React. By following these steps, you can create visually appealing and user-friendly components for your React application.