So I'm trying to read the value of something that triggered the event, in my case its Select tag but when I change the tag its giving me an error saying TypeError: Cannot read property 'target' of undefined
. I think it means event or target in undefined, My code is like this
function RandomScreen() {
function handleChange(event) {
ChangeSomeOtherState(event.target.value)
}
return (
<select onChange={() => handleChange()}>
{StateWhichIsArray.map(String => {
return (
<option value={String} key={String} >{String}</option>
)
})}
</select>
)
}
So I'm trying to read the value of something that triggered the event, in my case its Select tag but when I change the tag its giving me an error saying TypeError: Cannot read property 'target' of undefined
. I think it means event or target in undefined, My code is like this
function RandomScreen() {
function handleChange(event) {
ChangeSomeOtherState(event.target.value)
}
return (
<select onChange={() => handleChange()}>
{StateWhichIsArray.map(String => {
return (
<option value={String} key={String} >{String}</option>
)
})}
</select>
)
}
Share
Improve this question
asked Apr 18, 2021 at 13:32
SnaccOvenFlourSnaccOvenFlour
1564 silver badges17 bronze badges
3 Answers
Reset to default 4You are not passing any value to callback function , can do it like this
<select onChange={(e) => handleChange(e)}>
Or
<select onChange={handleChange}>
You can refer to this codesandbox to do it right way
Remove expression
to make the function get called with the calling event
<element onChange={eventHandler}>
Use expression callback
when you want to pass any data to handler, Note this, when you do this way, you are creating a fn
each time event get triggered which get heavy when you attach this to events like scroll
or keypress
or drag
so be cautious when you do this
<element onChange={(yourData) => eventHandler(yourData)}>
So In your case it will look like this
return (
<select onChange={handleChange}>
{StateWhichIsArray.map(String => {
return (
<option value={String} key={String} >{String}</option>
)
})}
</select>
)
The answer was answered by Gouthman ans Satyam, but i will try to explain what happened there with more details because I've seen that is a recurrent error in a lot of developers.
- The select selector executes the arrow function that you define implicitly.
- The arrow function is who can take the event parameter but you are ignoring it and you are executing the
handleChange
function without pass the event object - the handleChange function throws error because does not recognize the event object.
- Important thing: you are using an arrow function that calls another function passing the same value that gets by itself. It is redundant an unnnecessary, you could pass directly the
handleChange
function and make your code more concise and clear.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745195474a4616066.html
评论列表(0条)