ReactJS: Clear Input Fields After onClick and Save to LocalStorage (2026)
Discover how to manage ReactJS input fields by clearing them after onClick and storing data in localStorage. Ideal for enhancing form functionality.
ReactJS: Clear Input Fields After onClick and Save to LocalStorage (2026)
Managing input fields in React is a common task, especially in forms where you need to clear the fields after submitting the data and storing it in localStorage. This tutorial will guide you through the steps necessary to implement this functionality effectively.
Key Takeaways
- Learn how to clear input fields in React after a button click.
- Understand how to store form data in localStorage.
- Implement a controlled component approach for managing form inputs.
- Handle common errors when dealing with input states and local storage.
In this tutorial, you will learn how to manage input fields in a React component, specifically how to clear them after submitting a form. This is useful in scenarios where user input is saved to localStorage, and you need to reset the form for further entries. Understanding this process will improve your ability to handle form data in React applications, making your components more responsive and user-friendly.
Prerequisites
- Basic understanding of ReactJS and JavaScript ES6.
- Node.js and npm installed on your machine.
- A code editor like VSCode.
- React Developer Tools installed in your browser for debugging.
Step 1: Set Up the React Project
First, we need to set up a new React project. You can do this using Create React App, a popular toolchain for React projects. Open your terminal and run the following command:
npx create-react-app react-clear-inputsThis will create a new directory named react-clear-inputs with all the necessary files and dependencies.
Step 2: Create the Form Component
Next, let's create a form component. This component will have input fields for an expense name and amount, along with a submit button. Open the src directory and create a new file named ExpenseForm.js. Add the following code:
import React, { useState } from 'react';
function ExpenseForm() {
const [expense, setExpense] = useState('');
const [amount, setAmount] = useState('');
const handleExpenseChange = (e) => setExpense(e.target.value);
const handleAmountChange = (e) => setAmount(e.target.value);
const handleSubmit = (e) => {
e.preventDefault();
if (!expense) {
alert('Please enter a name.');
return;
}
if (!amount || isNaN(amount)) {
alert('Please enter a valid amount.');
return;
}
const expenseList = JSON.parse(localStorage.getItem('expenses')) || [];
const newExpense = { expense, amount: parseFloat(amount) };
expenseList.push(newExpense);
localStorage.setItem('expenses', JSON.stringify(expenseList));
setExpense(''); // Clear the expense input
setAmount(''); // Clear the amount input
};
return (
Expense Name:
Amount:
Add Expense
);
}
export default ExpenseForm;
This code defines a simple form with two inputs and a submit button. We manage the inputs using React's useState hook, which allows us to clear them after submission.
Step 3: Integrate the Form into Your App
Now, let's integrate the ExpenseForm component into the main application. Open src/App.js and modify it as follows:
import React from 'react';
import ExpenseForm from './ExpenseForm';
function App() {
return (
Expense Tracker
);
}
export default App;
After saving the files, run npm start in your terminal to launch the app in the browser. You should be able to add expenses and see the inputs clear after clicking the 'Add Expense' button.
Common Errors/Troubleshooting
- Inputs Not Clearing: Ensure that the
setExpenseandsetAmountfunctions are called with empty strings after localStorage operations. - localStorage Not Updating: Verify that the data is correctly parsed and stringified using
JSON.parseandJSON.stringify. - NaN Errors: Check that the amount is parsed correctly as a float and that the input type is set to number.
Frequently Asked Questions
How do I clear an input field in React?
You can clear an input field by setting its state to an empty string after the form is submitted.
Why use localStorage in React?
localStorage is used to persist data in the browser, allowing you to save and retrieve data even after the page is refreshed.
What are controlled components in React?
Controlled components are those where the form data is handled by the React component's state, ensuring consistent control over the form inputs.
Frequently Asked Questions
How do I clear an input field in React?
You can clear an input field by setting its state to an empty string after the form is submitted.
Why use localStorage in React?
localStorage is used to persist data in the browser, allowing you to save and retrieve data even after the page is refreshed.
What are controlled components in React?
Controlled components are those where the form data is handled by the React component's state, ensuring consistent control over the form inputs.