javascriptreactjsonhover

React button OnHover change image inside an array


I have a dynamic component that has three buttons with different images on each of them. I need to change the images on the buttons on hover. I used onMouseOver & onMouseOut. It seems to work but as soon as I hover on the button, it crashes with an error :

TypeError: btn.map is not a function.

The possibility that there maybe some minor syntactical error, but I am unable to figure it out.

Here is the working snippet for the same: https://codesandbox.io/s/frosty-wood-fzop7

Any help to rectify this is appreciated :)


Solution

  • Just map the btn array and return new one with hovered element that will be used to change the image src :

     const changeHover = (val, bool) => {
        setBtn(btn.map((ele, id) => id === val  ? { ...ele, hovered: bool} : ele));
      };