Created
October 6, 2016 05:20
-
-
Save basarat/1966acc2fbae85f7f1a3ca1f4799ba8b to your computer and use it in GitHub Desktop.
React forms that don't reload page
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from 'react'; | |
interface FormProps { | |
/** | |
* Automatically prevents the default browser behavior so you don't have to | |
*/ | |
onSubmit: () => any; | |
children?: JSX.Element; | |
} | |
export const Form = ({ onSubmit, children}: FormProps) => | |
<form | |
onKeyDown={ | |
(e) => { | |
/** | |
* Note: Pressing enter in some input in a browser forms | |
* triggers onClick on the first child button | |
* | |
* So, prevent `enter` from triggering `onClick` on any buttons | |
* and instead trigger onSubmit | |
*/ | |
if (e.key === 'Enter') { | |
e.preventDefault(); | |
onSubmit(); | |
} | |
} | |
} | |
onSubmit={ | |
(e) => { | |
/** | |
* Prevent submit from reloading the page | |
*/ | |
e.preventDefault(); | |
e.stopPropagation(); | |
onSubmit(); | |
} | |
}> | |
{children} | |
</form> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks, it was really helpful.