'Get image src onClick react

I'm trying to print image src with the help of e.target.src to get the output as 'Person-1.jpg' but instead getting as 'localhost:3000/static/media/Person-1.bb56f19f.png'

const imageSrc = (e) => {
  console.log(e.target.src);
}

<img src={require('directory').default} onClick={imageSrc}>


Solution 1:[1]

Use console.log(e.target.getAttribute('src'));

.src returns the URL.

.getAttribute('src')); returns the source parameter as it is.

Solution 2:[2]

If the format is uniform, you can just process the string like so:

// Let's say the e.target.src is "localhost:3000/static/media/Person-1.bb56f19f.png"
const baseString = e.target.src

// Split the string by "/" to return:
// ["localhost:3000", "static", "media", "Person-1.bb56f19f.png"]
// Then pop to get the last value of the array, which is:
// "Person-1.bb56f19f.png"
const fileName = baseString.split('/').pop()

// Then split the filename by "." to return
// ["Person-1", "bb56f19f", "png"]
// Then use a template strign to append the new format with the
// first element of the previous array
const actualFileName = `${fileName.split('.')[0]}.jpg`

// Should be "Person-1.jpg"
console.log(actualFileName)

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 GetMyIsland
Solution 2 Amats