react-native-web icon indicating copy to clipboard operation
react-native-web copied to clipboard

TextInput incompatible with FormData due to missing name forwarding

Open TimPetricola opened this issue 2 years ago • 3 comments

Is there an existing issue for this?

  • [X] I have searched the existing issues

Describe the issue

I'm using react-native-web in a project targeting a web environment only.

To manage forms, in simple case I need to rely uncontrolled inputs and the standard FormData API:

const Form = () => {
  const handleSubmit = (e) => {
    e.preventDefault();
    const formData = new FormData(e.target);
    // do stuff to process formData, e.g. send it to API, ...
  }

  return (
    <form onSubmit={handleSubmit}>
      <TextInput name="firstName" defaultValue="Foo" />
      <Button>Submit</Button>
    </form>
}

In the above, I'm expecting formData to get a firstName entry with "Foo" value. But instead it's empty.

This is due to <TextInput /> not forwarding the name prop to the underlying <input />

Expected behavior

I'm expecting TextInput (and potentially other components) to forward name prop to the resulting DOM node.

Steps to reproduce

See codesandbox

Test case

https://codesandbox.io/s/react-native-web-input-name-2g7d2l

Additional comments

Once it's validated that name should be forwarded. I can take care of opening a PR

TimPetricola avatar Oct 18 '23 16:10 TimPetricola

React is also introducing 2 new hooks in an upcoming version (see documentation for useFormState and useFormStatus) which requires the name attribute.

I took the liberty of opening a PR to bring support to react-native-web: https://github.com/necolas/react-native-web/pull/2603

TimPetricola avatar Oct 27 '23 11:10 TimPetricola

FYI, we solved this issue using a custom TextInput component using a ref and then ref.current.setAttribute('name', name). I also did this for setting the type attribute, also for <button>-elements

efoken avatar Nov 09 '23 11:11 efoken

@efoken thanks for the tip! I didn't think about it and it's a great alternative! (I'm currently patching react-native-web for this, and I prefer your approach very much)

TimPetricola avatar Nov 09 '23 14:11 TimPetricola