React Phase 2 Project: Flatiron School
I’m finally done with Phase2! This was the most entertaining module I’ve done so far. From learning components and JSX, all the way to making fetch GET, POST and DELETE requests, I’ve absorbed a ton of information! Let’s talk about something that I’m proud of learning: Controlled Form Components!
At first glance it doesn’t look like much, but the code that makes this form ‘controlled’ is the fascinating part. Let’s get straight into it! (Keep note of the names of the input fields: image, title, rating, price, platform, review, and name (user))
First thing I did was create my <form> tags and then add <input> tags inside them with different attributes! To help capture what the user types in those text boxes, I gave each <input> their very own id (id= “something” ), and an onChange event attribute set to a callback function called ‘handleChange’ (so when there is a change in the text box, it will fire off this handleChange function). I then set the value attribute of each input to be formData.something! Let’s see what formData is 🤔…
Here formData is a simple state variable! It’s set to an object filled with those familiar id names as keys, and their value set to empty strings. I think of this as an empty template so that we can update the state to be whatever gets typed in those empty input fields. Now let’s take a look at HOW these get set!
Inside my handleChange function I’m updating the state of formData using it’s function ‘setFormData’. Then to grab those typed in values in the form, without actually directly changing (or mutating) the state, I used the spread (…) operator to make a ‘copy’ of formData. Then the ‘onChange’ event will ‘target’ the <input> tags by a key (in this case BY THEIR ID) and set their value to what the user types in the forms input fields!
Almost done! Now that we have our state set to the users input, we can just set the value of our inputs to change dynamically with formData.keys!
That’s it! I hope this was a thorough enough explanation on how controlled forms work behind the scenes. I can’t wait to continue this incredible journey as I move towards Phase 3 and to start learning Ruby!
Until Next Time!