Submitting a Form with a Button outside of the Form tags

Hi, I’m using Reactjs and I’d like to know how to submit a form with a button that is outside of the form element tag. How is this accomplished? I’ve place my code below.

import React from 'react';

import { Drivers } from './../api/drivers';

export default class AddDriver extends React.Component {
  handleSubmit(e) {
    let firstName = e.target.firstName.value;
    let vehicleColor = e.target.vehicleColor.value;
    let vehicleModel = e.target.vehicleModel.value;
    let seats = e.target.seats.value;

    e.preventDefault();

    if (firstName && vehicleColor && vehicleModel && seats) {
      e.target.firstName.value = '';
      e.target.vehicleColor.value = '';
      e.target.vehicleModel.value = '';
      e.target.seats.value = '';

      Drivers.insert({
        name: firstName,
        vehicleColor: vehicleColor,
        vehicleModel: vehicleModel,
        seats: seats
      });
    }
  }
  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit.bind(this)}>
          <input type="text" name="firstName" placeholder="First name here"/>
          <input type="text" name="vehicleColor" placeholder="Vehicle's Color"/>
          <input type="text" name="vehicleModel" placeholder="Vehicle's Model"/>
          <input type="number" name="seats" placeholder="Seats available"/>
          <button>Add Driver</button>
        </form>
      </div>
    );
  }
}

Use the form attribute:

https://www.w3schools.com/tags/att_form.asp

1 Like

Thank you! This really helps, and I definitely should consider checking out the documentation on the W3C site more often! :smiley: