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

331
Views
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 answers
Answer question

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 Report

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