Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

133
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda