In this lesson we'll take a look at how to make a basic form with React. We'll see how to use the onSubmit
event to prevent the default submit behavior of forms with React and then how to use that event to get the values from the form. We'll also see how you can use the React ref
prop to get the value of form elements as well.
Using refs
would we be able to add a value to the input field. Say for example I have some resource I am editing through a form and need to prefill the input fields with existing values.
Hi Hozefa!
So you could do that. But there is a better (more declarative) way to accomplish the same thing. You can use the defaultValue
prop when rendering: <input defaultValue="hello world" />
.
Also, there's a concept of controlling the input value which you can see in a future lesson in this course :)
Sure I can use defaultValue
. Actually the problem I have is that, there is a page with a pretty long form(internal tool) that I am working on. So I am using controlled component for it. But that in turn causes me to have pretty big state
for that component.
So I was wondering if there is another way to achieve this, without having to put every form field value in state
?
So, if you can use defaultValue
then I suggest you do that. It's much simpler. If that's not an option for some reason, then there's not really any option to avoid having a lot of stuff in state
(and it's not really a problem if what you're putting into state is really stateful).
Just out of curiosity... when I console.log(event.target), I get the html if that makes sense, but when I log it like you did, console.log({target:event.target}) I get a more detailed response. Is there any reason for this?
Alex,
That's a feature of the browser developer tools. It's kind of neat, but also a little annoying. That's why I did the object form. You can also do: console.dir(event.target)
and that will show you the object form as well.