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!
CodePudding user response:
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({});
CodePudding user response:
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
CodePudding user response:
It working now, I didn't change the code I provided above. It seems like I had some issues with my machine "just restart it and all good". Still don't know what was the reason but the code working just fine ;)