Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

132
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda