This article was originally published on my blog
This tutorial covers how to:
β
Create a form
β
Get data from the form for processing
β
Handle submitting form data
π©βπ» Code is available on github so feel free to download! π¨βπ»
We will create a form with one text input field called name. Then we will extract the data from the field and store it in state. Lastly, we will handle what happens when the form is submitted.
Create a form
/* Form.re */
[@react.component]
let make = () => {
<form>
<label> {React.string("Name")} </label>
<input type_="text" name="name" />
<button type_="submit"> {React.string("submit")} </button>
</form>;
};
Looks like this
We've added a form element with a label, input and button. It doesn't do much right now, but we'll fix that.
Get data from the form for processing
Next, we're going to capture and store the data from the name field.
/* Form.re */
[@react.component]
let make = () => {
/* NEW STUFF BELOW THIS LINE */
let (name, setName) = React.useState(() => "");
let onChange = (e: ReactEvent.Form.t): unit => {
let value = e->ReactEvent.Form.target##value;
setName(value);
};
/* NEW STUFF ABOVE THIS LINE */
<form>
<label> {React.string("Name")} </label>
<input type_="text" name="name" value=name onChange /> /* added OnChange here */
<button type_="submit"> {React.string("submit")} </button>
</form>;
};
Incase you're not familiar with "pipe first" syntax
e->ReactEvent.Form.target##value;
/* πis syntax sugar for π */
ReactEvent.Form.target(e)##value;
We've added a state hook to store the name and an onChange handler. The handler takes the name from the React event when the input changes and stores it in the component state.
We were able to do this because ReasonReact exposes an interface for all events from React. The module ReactEvent also has methods for handling events from the keyboard, mouse, clipboard, animation and so much more.
Handle submitting form data
/* Form.re */
[@react.component]
let make = () => {
let (name, setName) = React.useState(() => "");
let onChange = (e: ReactEvent.Form.t): unit => {
let value = e->ReactEvent.Form.target##value;
setName(value);
};
/* NEW STUFF BELOW THIS LINE */
let onSubmit = (e: ReactEvent.Form.t): unit => {
ReactEvent.Form.preventDefault(e);
/* code to run on submit */
};
/* NEW STUFF ABOVE THIS LINE */
<form onSubmit> /* added onSubmit here */
<label> {React.string("Name")} </label>
<input type_="text" name="name" value=name onChange />
<button type_="submit"> {React.string("submit")} </button>
</form>;
};
We've added an onSubmit handler that captures the submit event. The handler also calls the preventDefault method to stop the browser from making the form request for you.
That's it!
We were able to create a form, capture the data when the form changes, and run our own method when the form is submitted.
This should help you get started making your own forms in your ReasonReact app!
Top comments (0)