S
S
SerjSkachkov2020-10-05 21:37:12
React
SerjSkachkov, 2020-10-05 21:37:12

Dynamic state in a form?

I'm trying to create a dynamic form with validation.
Validation works in such a way that it takes keys from the state and checks for conditions.
How to put a key with the field name in the fieldsData state?

I'm a newbie so don't judge too harshly.

An example of a passed array with form fields:

const formData = {
fields: [
{ label: "Username", name: "name", type: "text", id: "username" },
{ label: "Password", name: " password", type: "password", id: "password" },
],
buttonText: "Login",
};

Form example:

import React, { useState } from "react";

import { UiFormField } from "../components/UiFormField/UiFormField";
import { UiAlert } from "../components/UiAlert/UiAlert";
import { UiButton } from "../components/UiButton/UiButton";

import validateForm from "../helpers/validateFrom";

export const Form = ({
  formData: { fields, onSubmit, buttonText },
  errorMessage,
}) => {
  const [fieldsErrors, setFieldsErrors] = useState({});
  const [fieldsData, setFieldsData] = useState({});

  const hanleChangeField = (e) => {
    setFieldsData({
      ...fieldsData,
      [e.target.name]: e.target.value,
    });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    const { error, isValid } = validateForm(fieldsData);

    if (!isValid) {
      return setFieldsErrors(error);
    }
    setFieldsErrors({});
  };
  return (
    <div className="form">
      <form onSubmit={handleSubmit}>
        {fields.map((field) => {
          const { id, name, type, label } = field;
          return (
            <UiFormField
              id={id}
              name={name}
              type={type}
              label={label}
              onChange={hanleChangeField}
              error={fieldsErrors.name}
            />
          );
        })}
        {errorMessage && <UiAlert type="danger" message={errorMessage} />}
        <UiButton className="btn-primary btn-full" onClick={handleSubmit}>{buttonText}</UiButton>
      </form>
    </div>
  );
};

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Z
Zhanna_K, 2020-10-05
@Zhanna_K

I recommend using redux-form .
It processes the data from the form itself and adds it to the store. Validation is also very easy to write!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question