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

332
Vistas
What is the best way to set the required attribute based on a state in React?

I'd like to set the required attribute on input based on a state, I tried something like the following:

const [required, setRequired] = useState(false)

return(
  <form onSubmit={submitHandler}>
    <input id='name' type='text' required={required} onChange={changeHandler} />
  </form>
)

At the moment, I can't submit the form as the input is still required 'even if my state is false'. What am I missing? Thanks in advance!

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

This ended up being weirder than I imagined.

required is a weird one in HTML. It doesn't need to be set to a boolean value, if it is passed to an input element then that input is required.

To programmatically set attributes to your JSX elements, you can use the spread operator on an object that contains required as a key.

The way I managed to do this was with a component that looked like this:

const Component = () => {
    const [required, setRequired] = useState({ required: true });

    return (
        <form>
            <input id="name" type="text" {...required} onChange={() => { //handleChange }} />
        </form>
    )
}

Here's another interesting stackOverflow discussion about the required attribute.

EDIT: If you want to remove the required attribute later, you can set the state variable to an empty object.

setRequired({});
about 4 years ago · Juan Pablo Isaza Denunciar

0

The required attribute only works with default form actions. You'll need to do your own validation in the handler. You should also explicitly define the button type attribute as well since buttons by default are type="submit". Create a validation function and pass your state values to it. Return true if input is valid, false otherwise.

This might be the answer you are looking for: https://stackoverflow.com/a/64962453/8044582

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