Search code examples
reactjsreact-bootstrapreactstrap

How Can I Get Form/Submit To Work with ReactStrap in a React functional component?


I like how Reactstrap handles Modal so I want to keep using it, but I can't figure out how to get the data out of a form and capture it in state.

const handleSubmit = (evt) => {
    evt.preventDefault();
    alert(`Submitting Name ${name}`);
};

With Reactstrap

<Form onSubmit={handleSubmit}>
   <FormGroup>
      <Label for="firstname">First Name</Label>{' '}
      <Input name="speakername"></Input>
    </FormGroup>
</Form>
    

When I use standard form and input elements, I'm able to capture what I need in handleSubmit, but I can't figure out how to do the same thing with the Form and Input tags of Reactstrap

Regular form and input elements

<form onSubmit={handleSubmit}>
    <label>
        First Name:
        <input
            type="text"
            value={name}
            onChange={e => setName(e.target.value)}
        />
    </label>
    <input type="submit" value="Submit" />
</form>

Solution

  • Add a Button component with type=submit to your reactstrap form the same way you had an <input> with type=submit so that React know's to fire the onSubmit handler when the Button is clicked.

    import { Form, FormGroup, Input, Label, Button } from "reactstrap";
    
    <Form onSubmit={handleSubmit}>
       <FormGroup>
          <Label for="firstname">First Name</Label>{' '}
          <Input name="speakername"></Input>
        </FormGroup>
        <Button type="submit">Submit</Button>
    </Form>