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

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

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 Relatório

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 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