Having an issue with e.target.value returning Undefined in React
Asked Answered
T

5

17

I have a feature where you can click an img and see a a list of names which are clickable....when you click a name, that persons image should take the place of the original img. Im working with an artist api and rather then me getting an error in the console, the image changes to an img of an artist whos name is 'undefined'...strange. might not be a huge fix but ive been tormented by this issue for some time now.

searchForArtist(query) {
    request.get(`https://api.spotify.com/v1/search?q=${query}&type=artist`)
      .then((response) => {
        const artist = response.body.artists.items[0];
        const name = artist.name;
        const id = artist.id;
        const img_url = artist.images[0].url;
        this.setState({
          selectedArtist: {
            name,
            id,
            img_url,
          },
        });
      })
      .then(() => {
        this.getArtistAlbums();
      })
      .catch((err) => {
        console.error(err);
      });
  }

  getSubsequentCollabs(artist) {
    this.setState({
      selectedArtist: {},
      selectedAlbums: {},
      artistCounts: {},
    });
    console.log(artist);
    this.searchForArtist(artist);
  }

  artistOnClick(e) {
    console.log(e);
    let artist = e.target.value;
    this.getSubsequentCollabs(artist);
  }

I have another component doing this:

const Artist = ({name, artistOnClick}) => {
  return (
    <div name={name} onClick={artistOnClick}>
      {name}
    </div>
  )
}

export default Artist;
Transfiguration answered 5/11, 2016 at 14:25 Comment(3)
You are listening to a div component 'onclick' event. what do you expect to be on e.target.value ?!Drying
Im sorry, can you elaborate or help a little more with that. I may not have as much experience as you.Transfiguration
maybe another solution ... e.nativeEvent.target.nameDrying
H
12

event.target will give you the target HTML element. Javascript will make all the attributes of the Node as a property of event.target.

For Example:

<div id="hello">Hello</div>

e.target.id //returns 'hello'

There are special cases like inputs where the property value in implicit. But, for other HTML element you need to specify the attributes explicitly.

So, you HTML should be like this

const Artist = ({name, artistOnClick}) => {
  return (
    <div value={name} onClick={artistOnClick}>
      {name}
    </div>
  )
}

e.target.value //return the name

OR

const Artist = ({name, artistOnClick}) => {
  return (
    <div onClick={() => artistOnClick(name)}>
      {name}
    </div>
  )
}

e.target.name //returns the name 

Hope this helps!

Hexane answered 5/11, 2016 at 15:51 Comment(1)
Second example not working. Html element div not has event target valueRender
H
6

A div element doesn't have a value attribute, and so nothing can be passed through on the back of an event object for that particular click event.

Depending on what you expect to happen, you could tackle it by doing something like:

const Artist = ({name, artistOnClick}) => {
  return (
    <div onClick={() => artistOnClick(name)}>
      {name}
    </div>
  )
}

export default Artist;
Helgoland answered 5/11, 2016 at 14:55 Comment(0)
I
3

In React, e.target.value will appear null if it's not saved in another variable.

For example:

const onChange = e => {
    console.log(e.target.value);
    setState({blah: e.target.value})
}

In the above example console.log(e.target.value) would appear as the value but then in setState, e.target.value would be undefined.

You would need to save e.target.value in a new variable, to be able to use it:

const eTarget = e.target.value;

React versions before 17 (and React Native) use event pooling. Read about it here:

From the docs:

Note:

If you want to access the event properties in an asynchronous way, you should call event.persist() on the event, which will remove the synthetic event from the pool and allow references to the event to be retained by user code.

and

Note:

As of v17, e.persist() doesn't do anything because the SyntheticEvent is no longer pooled.

Ineludible answered 18/2, 2020 at 18:32 Comment(0)
D
1

I was getting similar issue, my input field was returning undefined for e.target.value

I solved it by

onChange={this.mymethod.bind(this)}

I hope it will help others.

Dissimilation answered 28/7, 2019 at 22:9 Comment(1)
Can you please add some explanation in your answer?Dappled
F
0

Came up with exact same issue and it got solved by using e.target.attributes.getNamedItem. You can find out more from this link.

<div name={name} onClick={(e) => artistOnClick(e.target.attributes.getNamedItem("name").value)}>
   {name}
</div>

And this can be accessed inside artistOnClick like this,

const artistOnClick = (value) => {
  console.log(value);
  let artist = value;
};

For me, this issue came because there was no name attribute for div. I know this link is very old but posting if anyone came across this issue will find some help here.

Freakish answered 24/4, 2022 at 13:26 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.