I like react, I was using angular 1 then switched to react, I like react but facing a pain issue using it - developing forms. In react I can't use auto fill, as the field has an onChange event. Auto fill using imacro won't work at all.
<input onChange={this.handleChange} />
Thus it make me hard to test if my form has lots of fields like checkbox, custom editor, dropdown etc.. I have to manually enter the value in every fields.
For autofill to work, you have to define the "name" attribute for the input.
<input name="firstName" onChange={this.handleChange} value={this.state.firstName} />
I've only tested this with React and Chrome, but I think this should work for other browsers as well.
While there are many "hacky" solutions the community has posted online, I found this solution the simplest.
Please like if you found this useful. Had to dig through a lot of sites and comments to find this.
Original github comment here.
Truchainz has a point with the name attribute, however there's more to this to make it work reliably.
To handle autofills gracefully you need to give the browser control over the form. The browser will not fire the onChange function when it autofills the form as it's considered a security issue (password/personal data leak), so you're better off leaving the form state to the browser.
The reason you need to give your fields a name is so that the browser attaches the input values to the submit event under the name you give it. So leave all your inputs uncontrolled and all you'll need to do is trigger the browser's own form submission with a type="submit" button.
This looks roughly like this:
const handleSubmit = (event) => {
event.preventDefault();
console.log(event.target.email.value)
console.log(event.target.password.value)
}
return (
<form onSubmit={handleSubmit}>
<input name="email" type="email" />
<input name="password" type="password" />
<button type="submit">Submit</button>
</form>
);
This is mostly based on thomasjulianstoelen's answer in the linked issue-thread: https://github.com/facebook/react/issues/1159#issuecomment-506584346 which worked well for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With