I am going through the react tutorial on codecademy
and have reached the reactjs part 2 course.
I have reached the part where one component changes the name
and other component displays it.
the handlechange function below is supposed to select the name and pass it to the parent function
BUt I am not really sure how this works.
could any of you guys help me understand the below code?
here’s the link to the page in case you want to check the other components too
not sure though if this link will work for you - i mean if you need to be signed in or something to see the link.
var Child = React.createClass({
handleChange: function(e) {
var name = e.target.value;
this.props.onChange(name);
},
<select id="great-names" onChange={this.handleChange}>
in your handleChange function, the ‘e’ that is passed in is the event. Every time there is a change in the tag, it triggers the handleChange function and passes it an event object. Inside that object, you have a target.value, which is normally the value your passed into that tag.
I assume that within your tag there must be some options. When an option is selected, the value of the tag would become the value of that option.
the e.target.value is used in forms to get the value that the user passes in.
Yes, I did read your answer and understood most of it,
except for the part with the ‘e’
and the part where this comes up → this.props.onChange(name)
you see, I only think I have properly understood a concept when I’d be using the same/similar code on my own, without any help at all.
and I dont think I’d be using this code or if I could even come up with this code on my own.
Maybe it’s just a kind of format that is being used, but then I’d like to know where to read about this, so I can understand that this is a type of code formula being used and I can use it in a similar manner in the future.
yep, e.target.value is the standard way to get the value of an input field.
If you want to get into details, it is the value (whatever is passed in) of the target (select tag) of the event(change in the input selected), hence e.target.value.
as for the this.props.onChange(name)…
the parent component must have passed in a props of onChange, equal to a function.
So the parent component must look like:
onChange:function(name){
//do something with the name
},
render:function(){
return <Child onChange={this.onChange} />
}
By using this.props.onChange, the child is triggering the function inside the parent and passing it the variable name
Ah,yes!
that’s what I wanted to know.
maybe I’ll go read up on e.target.value a little bit so I get very familiar with this code.
Thanks for helping out.