1 year ago

#323478

test-img

Sana

I wanna turn off focused for all inputs once a form is submitted in react

I have been working on a quiz app in react and firebase and currently on validation for a form to create a new quiz. I could nail it after working on it until noon. The problem I got is after I submitted the form, I got validation errors on the new form. When I implement validations for each input, I add them true or false if they are focused with useState(). After submission, they were still turned on so I got a validation error for all inputs. I want to delete inputs' values which are successfully stored in Firestore and show the new quiz form for creating a new quiz.

Could anyone teach me how to turn off focus with useState()??

FormInputText.jsx

import React, { useState } from 'react';

const FormInputText = props => {
  const [focused, setFocused] = useState(false);
  const handleFocus = e => {
    setFocused(true);
  };

  const { label, err, onChange, id, ...inputProps } = props;
  return (
    <div className='quizFormInputText'>
      <label htmlFor={label}>{label}</label>
      <input
        {...inputProps}
        onChange={onChange}
        required
        onBlur={handleFocus}
        focused={focused.toString()}
      />
      <span className='quizFormErrMsg'>{err}</span>
    </div>
  );
};

export default FormInputText;

When users click the submit button, the function below, which is one of some functions in NewQuiz.jsx, is triggered. I am guessing I can do something in this function to fix this bug showing validation errors in the new quiz form:

NewQuiz.jsx

  const handleSubmit = async e => {
    // const quizRef = doc(db, 'quizzes', 'category');
    // await setDoc(quizRef, payload);
    e.preventDefault();
    console.log("handlesubmit")


    // When all validatations are fine.
    const quizCollectionRef = collection(db, 'quizzes');
    const payload = {
      question: values['question'],
      answers: [
        values['answer1'],
        values['answer2'],
        values['answer3'],
        values['answer4'],
      ],
      correctAnswer: parseInt(values['correctAnswer']),
      likes: 0,
      createdAt: new Date(),
      category: values['category'],
    };
    await addDoc(quizCollectionRef, payload);

    setValues({
      question: '',
      answer1: '',
      answer2: '',
      answer3: '',
      answer4: '',
      correctAnswer: 0,
      createdAt: '',
      category: '', // how to set it to default value
    });
  };

javascript

reactjs

onfocus

0 Answers

Your Answer

Accepted video resources