Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

131
Views
Formik instant feedback input box

I'm trying to make a input box component that has instant feedback using Formik. I want the input box to turn green when the user input matches a predefined string (the "answer"), gray if the input matches the prefix of the answer (including the empty string) and red otherwise. This string is stored as a property of the initial values, values.answer. The Formik validate function checks if the input equals values.answer and sets values.correct = true. I then created a css class corresponding to a green input box and set the className of the input conditional on the value of values.correct. The problem is it only seems to update (i.e turn green with a correct input) when I click out of focus of the input box (i.e onBlur). I would like it to work onChange. How would I do this?

Here is the relevant code sandbox: https://codesandbox.io/s/instant-feedback-box-lub0g?file=/src/Frame.js

about 4 years ago ยท Juan Pablo Isaza
1 answers
Answer question

0

Cool problem, but you've overcomplicated your code a little bit ๐Ÿ˜‰ Some feedback:

  • touched is set to true during onBlur by default. You can override this by using setTouched(), but I found it simpler to just use values instead of touched in your form
  • try to keep values as minimal as possible, it's only meant to access input values so there's no need for hint and answer to be assigned to it
  • the purpose of the validation function is to return an errors object and not to set values, so remove assignments like values.correct = true
  • You don't need to store isDisabled in state, you can derive it from formik.submitCount and formik.isSubmitting
const Note = () => {
  const [showFrame, setShowFrame] = useState({ 1: true });
  const onCorrectSubmission = (frameId) => {
    setShowFrame({ ...showFrame, [frameId]: true });
  };

  const text =
    "What is the sum of the first three natural numbers? (give answer as a word, i.e one, two etc.)";
  const hint = "The first three natural numbers are 1, 2, and 3";
  const answer = "six";

  return (
    <div>
      <h1>Induction</h1>
      {showFrame[1] ? (
        <Frame
          id={1}
          text={text}
          hint={hint}
          answer={answer}
          onCorrectSubmission={onCorrectSubmission}
        />
      ) : null}
      {showFrame[2] ? (
        <Frame
          id={2}
          text={text}
          hint={hint}
          answer={answer}
          onCorrectSubmission={onCorrectSubmission}
        />
      ) : null}
    </div>
  );
};


const Frame = ({
  id,
  text,
  hint,
  answer,
  values,
  onCorrectSubmission,
  ...props
}) => {
  const validate = (values) => {
    const errors = {};
    if (!answer.startsWith(values.cloze)) {
      errors.cloze = hint;
    } else if (values.cloze !== answer) {
      errors.cloze = true;
    }
    return errors;
  };

  const formik = useFormik({
    initialValues: {
      cloze: ""
    },
    validate,
    onSubmit: (values) => {
      onCorrectSubmission(id + 1);
    }
  });

  const isFinished = formik.isSubmitting || formik.submitCount > 0;

  return (
    <form enablereinitialize={true} onSubmit={formik.handleSubmit}>
      <p>{text}</p>
      <input
        id="cloze"
        name="cloze"
        type="text"
        autoComplete="off"
        {...formik.getFieldProps("cloze")}
        disabled={isFinished}
        className={`input
           ${!answer.startsWith(formik.values.cloze) ? "invalid-input" : ""}
           ${formik.values.cloze && !formik.errors.cloze ? "valid-input" : ""}
        `}
      />
      {formik.values.cloze && formik.errors.cloze ? (
        <div>{formik.errors.cloze}</div>
      ) : null}
      <button disabled={!!formik.errors.cloze || isFinished} type="submit">
        Submit
      </button>
    </form>
  );
};

export default Frame;

Live Demo

about 4 years ago ยท Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
ยฉ 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!