K
K
KIberWarriorJs2022-02-06 16:38:38
React
KIberWarriorJs, 2022-02-06 16:38:38

Is the implementation of the Switch event pattern on the useState hooks correct?

Hello everyone, I recently got acquainted with the react pattern "Event switch", and wrote its implementation in my understanding. In my case, this is the usual form with inputs, but with rev. text in one input the entire component is re-rendered the entire comp. BasicForm , I would like to know if this behavior is correct and can it be improved somehow?

export default function BasicForm({ type, fields }: IBasicFormProps) {
  const [inputState, setInputState] = useState({
    title: "",
    description: "",
  });
  const handleChange = (e: any) => {
    const type = e.target.name;
    switch (type) {
      case "title":
        return setInputState({
          ...inputState,
          [e.target.name]: e.target.value,
        });
      case "description":
        return setInputState({
          ...inputState,
          [e.target.name]: e.target.value,
        });
      default:
        return console.warn(`No case for event type "${type}"`);
    }
  };
  const renderBasicForm = (type: string): JSX.Element => {
    switch (type) {
      case CREATE_ITEM_FORM:
        return (
          <Box>
            {fields.map((inputField: any, i) => {
              return (
                <InputItem
                  type={inputField.type}
                  placeholder={inputField.description}
                  value={inputState}
                  onChangeEvent={handleChange}
                  label={inputField.label}
                  name={inputField.name}
                />
              );
            })}
          </Box>
        );
      default:
        <div>There is no data to display</div>;
    }
  };
  return <div>{renderBasicForm(type)}</div>;
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question