MERN Stack Create
Let's add a which we'll make as a separate component
add NewForm.js
into the components folder
#
NewForm.jsconst NewForm = () => { return <div>New Form</div>;}
export default NewForm;
Add a Form in the render
<form onSubmit={handleSubmit}> <label htmlFor="name">Holiday:</label> <input type="text" id="name" name="name" placeholder="add a holiday" /> <input type="submit" value="Add a Reason to Celebrate" /></form>
#
App.jsimport NewForm from "./components/NewForm.js";// further downreturn ( <div className="container"> <h1>Holidays! Celebrate!</h1> <NewForm /> <table>...</table> </div>);
Let's build out our handleSubmit
functions
Now let's build our functionality
To submit, we have to prevent the default behavior of the form.
We also have to send this data back up to our app component so it can be passed down to the list.
#
App.jsconst addHoliday = (holiday) => { setHolidays([...holidays, holiday]); };// further down (in render)<NewForm handleAddHoliday={addHoliday} />
We then have to make a fetch request. When we are just making a get request, we just use one argument, a string, where we are making our request. However, for any other action, we have to add a second argument, an object.
We'll have to add a method, a body (the data from our form), and some headers.
THEN when we get a response we need to convert it to json. This is an extra step we didn't have to take when we used $.ajax
. Fetch is ultra-lightweight so we have to write a bit more code. You could use jQuery, axios, ky or other libraries, but our app is simple so let's just use fetch.
THEN we want to take that json-ed response and add our new holiday to our list
const handleSubmit = (event) => { event.preventDefault(); fetch("/holidays", { method: "POST", body: JSON.stringify({ name: event.target.name.value }), headers: { "Content-Type": "application/json", }, }) .then((res) => res.json()) .then((resJson) => { props.handleAddHoliday(resJson); }) .catch((error) => console.error({ Error: error }));}