Search code examples
reactjsformsbootstrap-4reactstrapform-control

React, Reactstrap - Input vs input, form-control class prevents values from submitting, returns undefined


I am working on an basic React CRUD App and I came across a strange issue. Using Reactstrap Input Component or the bootstrap class="form-control" the input values are undefined onSubmit. If I leave the elements as a standard html input the values submit just fine? I cannot figure out why this is happening. I put together this demo that illustrates the issue.

Code Sandbox Snippet <- Live Demo

On the AddName.js file I have one Input and one input on submit you can see that the first name submits but the description does not.

<FormGroup>
  <input
    placeholder="First Name"
    ref={nameInput => (this.nameInput = nameInput)}
  />
</FormGroup>
<FormGroup>
  <Input
    placeholder="Description"
    ref={descriptionInput => (this.descriptionInput = descriptionInput)}
  />
</FormGroup>

Can anyone explain why this is happening? Is it possible how I have the refs on the inputs?


Solution

  • Before utilizing 3rd party packages, you should read into using Controlled Components strictly through React. Then, once you understand the flow, incorporate the packages.

    I've rewritten your project to include all of the above, as well as written notes describing what I changed and why. There are also a few tricks and shortcuts I've used to simplify the code, such as: setState callback, ES6 Object Deconstruction and Fat Arrow Functions.

    Working example: https://codesandbox.io/s/l9m0vor4wq

    You should only need to use refs for obtaining a DOM element or a class instance for UI manipulation, instead of obtaining a data value. For example, utilizing a ref to draw attention to a DOM element via using its focus() method or removing attention from it via its blur() method. In your case, we would only use the synthetic event instead of a ref.

    On a side note, be careful about using the name as a key in <PersonCard/>, because multiple users can share the same name value. This will cause React to complain that two keys are the same, and cause issues if you ever try to remove, resort, or filter the names list. To keep it simple, I instead used the key provided by the map function. While this approach works, it's not the best solution. Ideally, each person should have an id property with a UUID. This ensures all of your keys will be unique.