onClick vs onSubmit in React

I have a simple input in react that won't work with onSubmit but with onClick. Why is that? Here is the link to an example.

const styles = {
  fontFamily: 'sans-serif',
  textAlign: 'center',
};

const clicked = e => {
  alert("Hi")
}
const App = () => (
  <div style={styles}>
    <input type='submit' value='click' onSubmit={clicked}/>
  </div>
);

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" />

3 answers

  • answered 2018-02-13 00:53 Tony

    I think it needs to be in a <form></form> for submit to work

  • answered 2018-02-13 00:55 Austin Greco

    onSubmit is a prop for <form>, you should add the handler on to that element:

    <form onSubmit={onSubmit}>
      <input ... />
    </form>
    

  • answered 2018-02-13 01:02 SakoBu

    Because you're not submitting anything. onSubmit is for submitting forms...