'Having an issue with e.target.value returning Undefined in React

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;


Solution 1:[1]

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!

Solution 2:[2]

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;

Solution 3:[3]

In React e.target.value will appear null if it's not saved in another variable. in 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 uses 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.

Solution 4:[4]

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.

Solution 5:[5]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pranesh Ravi
Solution 2 Chris
Solution 3 FabricioG
Solution 4 Tomerikoo
Solution 5 vimuth