DEV Community

Pamela Torres-Rocca
Pamela Torres-Rocca

Posted on

# Controlled Components in React Payment Application

In my final react project which adds charges and processes payments, I had several forms that the user could interact with in order to login, logout, and submit a payment in the application.
The default HTML form behavior is to browse to a new page once the form is submitted. Unless a controlled form is used in react, the data is handled by the DOM and not the virtual DOM. However, in the controlled components that I wrote to handle login, logout, and payment submission behavior, the data added by the user is used in a callback function. The user will input the information and the component will update the state through the javascript functions that handle form change and submission. Each state attribute is also accepted by the component as a prop. When the user types their input, the component state changes and the user is able to see their changes displayed as props in the react component. Currently the only validations occur when the form is submitted on the backend. However, validations could be added in this component to give the user feedback prior to form submission.
The name and password attributes in the state are used to conditionally render different parts of components and display any associated data such as payments and charges.

const Login = ({ login, name, password, setCurrentAccount, history }) => {
  const [form, setForm] = useState({
    //array destructuring
    account: {
      name: "",
      password: "",

  const handleLoginFormChange = (event, target) => {

  const handleLoginFormSubmit = (event) => {
    //does this need to be bound?
    event.preventDefault(); //state contains most up to date form data. prevent page refresh
    login(form, history);
Enter fullscreen mode Exit fullscreen mode

The Javascript function that takes in the form data then calls the login action and updates the state.
We have an initial state of form and we can update it with the setForm function. This is defined in the useState hook.

Top comments (0)