Building a User Registration Form in React with CSS Modules
Creating user-friendly registration forms is a critical part of user management for any web application. In this tutorial, we’ll build a simple yet functional registration form in React, using CSS Modules for styling. This approach not only ensures that styles are locally scoped to the component but also avoids conflicts with other styles in your application.
Benefits of CSS Modules
CSS Modules allow you to write CSS that is scoped locally to the component rather than globally. By doing so, you can avoid styling conflicts and maintain style encapsulation, which is especially useful in larger projects or libraries.
Step 1: Setting Up Your Form Component
Let’s start by creating the registration form component and its corresponding CSS module.
Create the RegistrationForm Component
- Create a New File: In your React project’s `
src`
folder, create a new file named `RegistrationForm.js`
. - Create a CSS Module File: In the same folder, create a new CSS file named `
Registration.module.css`
.
Add the Component Code
Here’s how you can implement the `RegistrationForm`
component:
import React, { useState } from 'react';
import styles from './Registration.module.css';
function RegistrationForm() {
const [user, setUser] = useState({
name: '',
email: '',
password: ''
});
const [submitted, setSubmitted] = useState(false);
const [valid, setValid] = useState(false);
const handleName = event => setUser({...user, name: event.target.value});
const handleEmail = event => setUser({...user, email: event.target.value});
const handlePassword = event => setUser({...user, password: event.target.value});
const handleSubmit = event => {
event.preventDefault();
if (user.name && user.email && user.password) {
setValid(true);
}
setSubmitted(true);
};
return (
);
}
export default RegistrationForm;
Step 2: Adding CSS with CSS Modules
Now, define the styles in your `Registration.module.css`
file:
.formContainer {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.registerForm {
display: flex;
flex-direction: column;
}
.formField {
margin-bottom: 20px;
padding: 10px;
font-size: 16px;
width: 300px;
border-radius: 5px;
border: 1px solid #ddd;
}
.successMessage {
color: green;
}
.error {
color: red;
}
Step 3: Include the Component in Your Application
Finally, make sure to import and render the `RegistrationForm`
component in your application’s main file, typically `App.js`
:
import React from 'react';
import RegistrationForm from './RegistrationForm';
function App() {
return (
);
}
export default App;