Skip to content

Instantly share code, notes, and snippets.

@basarat
Created October 6, 2016 05:20
Show Gist options
  • Save basarat/1966acc2fbae85f7f1a3ca1f4799ba8b to your computer and use it in GitHub Desktop.
Save basarat/1966acc2fbae85f7f1a3ca1f4799ba8b to your computer and use it in GitHub Desktop.
React forms that don't reload page
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>
@chulavege1
Copy link

Thanks! +rep!

@sidsb
Copy link

sidsb commented May 15, 2021

thanks, it was really helpful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment