Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onSubmit() is not working in React.js

Tags:

forms

reactjs

I have a form like below

<form className="ui form" onSubmit={this.update}>
     <input type="text" defaultValue={this.props.element} onChange={this.handleChange1}/>
     <input type="button" value="Update" className="ui positive icon button"/>
 </form>

My update function is like below

update = event => {
   console.log('hello');
   event.preventDefault();  
}

But it is not working.

like image 296
abu abu Avatar asked Dec 07 '22 14:12

abu abu


1 Answers

The submit button should not be of type button, but type submit.

Example

class App extends React.Component {
  update = event => {
    console.log("hello");
    event.preventDefault();
  };

  render() {
    return (
      <form className="ui form" onSubmit={this.update}>
        <input
          type="text"
          defaultValue={this.props.element}
          onChange={this.handleChange1}
        />
        <input
          type="submit"
          value="Update"
          className="ui positive icon button"
        />
      </form>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>
like image 167
Tholle Avatar answered Dec 11 '22 11:12

Tholle