Sardar Faisal
Sardar Faisal

Reputation: 671

Reactjs form onSubmit is never called

I have a form and a handlesubmit function. When the submit button is clicked nothing happens. I am new to React and have read different answers on the topic. Here is my code

class MyPage extends React.Component<>
{
constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
}
  state = {
    saving: false,
    message: null
  };

  t = makeTranslations(translations, this.props.request.langCode);

  async handleSubmit(e) {
  try{
    console.log('-----------------Here I AM', e);
    e.preventDefault();
    this.setState({ saving: true });
    const data = new FormData(e.target);
    let req = await fetch('/api/list/waitinglist/',
      {
        method: "POST",
        body: data,
      }
    );
  }
  catch(e){
        console.log('caught error', e);
        // Handle exceptions
    }
  };
  render() {
    const csrf_token = this.props.request.csrf_token;
  return (
...
...
...
            <form onSubmit={this.handleSubmit}
              style={{
                maxWidth: 600,
                margin: "0 auto",
                padding: "40px 0",
                display: "flex",
                flexDirection: "column",
                alignItems: "stretch"
              }}
            >
          <input
            type="hidden"
            name="csrfmiddlewaretoken"
            value={csrf_token}
          />

...
.
...

....

      <Button type="submit" onClick={this.handleSubmit} style={{ alignSelf: "center" }}>
        {this.t("Send")}
      </Button>

I have the this.handleSubmit.bind(this) in the constructor. Just to make it work i have put onClick={this.handleSubmit} on the submit button. But still nothing happens when the send button is clicked. There are some input fields that I haven't included before the button.

Upvotes: 1

Views: 1220

Answers (1)

seunggabi
seunggabi

Reputation: 1820

hmm.. I don't understand your code not working..

You check react docs example code, maybe you can do this.

https://codepen.io/gaearon/pen/VmmPgp?editors=0010

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" value={this.state.value} onChange={this.handleChange} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

ReactDOM.render(
  <NameForm />,
  document.getElementById('root')
);

Upvotes: 1

Related Questions