7. Event Handling in ReactJs
Why we use bind(this)
1. We use bind(this) for form function in reactJs, and reason is, because that's what the documentation is saying, in the example which you saw in the video, I am using two files, but even if I am using one file, I still have to use bind(this) as per the documentation if I dont use bind(this), this key word will be undefined, and our code will not work,
2. basically bind(this) give function context (component), so even though you call the function from another component, it still going to call the function in the given context(component), and if you dont use bind(this), there will not be any context, hence our function code will fail.
Why we use onChange event handle with form input
And the reason we use onChange – As soon as you add value tag in the form, react will render read only field, so if you want to change it, you have to use bind this function.
Few notes before running the exercise
1. We are going to use two file for the example, layout.js and header.js, in both file, basic shell for component is ready, but in the header.js file we are also returning one extra h1 tag.
2. Import the header.js into the layout and return the Header component as well.
First Exercise –
1. Create a state name, name and give it value, William, and inject this individual state name into Header component
2. Return the props name, in h1 tag in header, check the out put
3. Now add a form in the Header component with one input field
a) Type for our input field is text and value is equal to the this.props.name
4. As you can see we can not change the value in the input, so add a onChange event handle, with the input field, and name for that event handle is nameChange,
a) this event handle nameChange, basically going to change the value of input box, when ever user press any key on the key board.
b) And that value will be equal too what ever user is typing in the input box, at the moment input value is equal to this.props.name
5. Given the above point, where you are going to create event handle, in the Layout Component or in Header Component?
a) If you dont know the answer to this question, leave a comment and we will discuss it in the comment section.
6. After creating this nameChange function in the Layout component, inject this as a props, into the header component.
a) Make sure you understand why we are using e.target.value in this function.
b) And you should also understand why we use bind(this) when we injected this function into Header component
7. Now check your out put, and change the input value to see weather our code is working fine or not.