1

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 :)

3
  • 1
    do you need something like this? Commented Aug 30, 2020 at 10:11
  • @BoussadjraBrahim Yes. It worked. Can you please explain the changes to the function? Commented Aug 30, 2020 at 10:14
  • You are changing value of btn from an array to an object with btn property. That's why when state is updated, calling .map() on btn fails. You need to change the implementation of changeHover function so that it updates the state correctly. Demo Commented Aug 30, 2020 at 10:16

2 Answers 2

1

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));
  };
Sign up to request clarification or add additional context in comments.

1 Comment

There's no need to return a new object when id === val is false. You can just return ele as it is. ? { ...ele, hovered: bool} : ele
1

You are doing set state wrong you need to do like this:

const changeHover = (val, bool) => {
    console.log(val)
    setBtn((prevstate) => prevstate.map((ele, id) =>
    console.log("STATES", ele) || id === val
      ? { ...ele, hovered: bool }
      : { ...ele }
  ));
  };

Here is the demo: https://codesandbox.io/s/bold-bush-w0zim

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.