1

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!

K. Alabssi
  • 11
  • 2
  • There's a lot of code missing from your question. What does `submitHandler` do? And why are you relying on state to tell the input that it should be required? Under what circumstances are you changing that state? – Andy Mar 13 '22 at 15:51

2 Answers2

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({});
Willey Ohana
  • 317
  • 1
  • 9
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

PR7
  • 1,524
  • 1
  • 13
  • 24