pepsi
pepsi

Reputation: 321

How to make submit button to work / react?

So I have a small form that a user writes some message ('title'), and a button which submits it.

The 'event happened' should be logged as I click the button, but it's not.

import React, { useState } from 'react';
import axios from 'axios';

export default () => {
  const [title, setTitle] = useState('');

  const onSubmit = async (event) => {
    event.preventDefault();
    console.log('event happened');
    await axios.post('http://localhost:4000/posts', { title });
    setTitle('');
  };

  return (
    <div>
      <form onSubmit={onSubmit}>
        <div className="form-group">
          <label>Title</label>
          <input
            value={title}
            onChange={e => setTitle(e.target.value)}
            className="form-control"
          />
        </div>
        <button className="btn btn-primary">Submit</button>
      </form>
  </div>
  );
}

Upvotes: 0

Views: 46

Answers (2)

Mohammed Al-Reai
Mohammed Al-Reai

Reputation: 2786

just add to the button **type="submit"**

<button className="btn btn-primary" type="submit">Submit</button>

Upvotes: 1

Chitrang Sharma
Chitrang Sharma

Reputation: 274

The code is working fine for me even without type="submit" its working but you should add type="submit" on button. if not works then you can try delete your package-lock.json and do npm i again maybe that would make it or maybe restart the project

Upvotes: 1

Related Questions