DEV Community

Raphael Chaula
Raphael Chaula

Posted on

How to reuse input elements in the form React

We normally use text fields with lots of similarity especially styles in our forms, they just differ in values they store, placeholders and some types they have. For that case I often iterate the array of objects (formElements) and reuse the input component.

Here is how.

Form

import React, { useState} from 'react';

const SigninForm = () => {
  const [formData, setFormData] = useState({});

  const changeFormData = (key, value) => {
    const formdata = {
      ...formData,
      [key]: value,
    };
    setFormData(formdata);
  };

  const submitFormData = (event) => {
    // Submit form data here
    event.preventDefault();
    console.log(formData);
  };

  const formElements = [
    { name: "email", type: "text", placeholder: "Email"},
    { name: "password", type: "password", placeholder: "Password"},
    { name: "button", type: "submit", value: "Submit"},
  ];

  return (
    <form onSubmit={submitFormData} >
      {formElements.map(element => {
        // Return submit button
        if (element.type === "submit") {
          return (
            <button
              key={element.name}
              type={element.type}
              onClick={submitFormData} 
            >
              {element.value}
            </button>
          );
        }
        // Return text inputs
        return (
          <input
            key={element.name}
            type={element.type}
            value={formData[element.name] || ""}
            placeholder={element.placeholder}
            onChange={(e) => changeFormData(element.name, e.target.value)}
          />
        );
      })}
    </form>
  );
};

export default SigninForm;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)