0
votes

I have a list of Mui cards. On a card hover, I would like a Floating Action Button to appear inside the card. I'm using state to achieve this, the issue is that the hover state is being applied to ALL cards during state change, meaning the button is showing up on every card, and not the one that's being pointed at/hovered. How can I control this to that the button is only showing on THE card where the state action was being fired off.

Also, is there anyway to not cause state change to re-render other components? I have a <ChartistGraph> that is being re-rendered on hover which constantly has it's animation repeated.

Essentially this is what I'm doing:

    const [state, setState] = useState({
        actionButton: false
    });

My card:

                        <Card
                          className="miniGraphCards"
                          onMouseOver={() => setState({ actionButton: true })}
                          onMouseOut={() => setState({ actionButton: false })}
                        >

Conditional rendering based off state and hover:

                            {state && state.actionButton != false &&
                              <Fab>
                                <EmojiEmotionsIcon />
                              </Fab>}

Please see reproducible code: You will notice the repeat re-rendering of the graphs and the button being applied to all cards on hover.

https://codesandbox.io/s/elastic-kowalevski-j3wjx

1

1 Answers

1
votes

You are saving the 'state' on the App component. Your boolean actionButton will trigger for all the items.

Since you want the App to know what item is active/hover, consider saving a unique value of that Card, so you can determine wich Card is being hovered on.

Since I still know how the app works from your previous question, I would recommend to save the data.symbol for the Card you are hovering on.

First, onHover, remember the current data.symbol

<Card
    onMouseOver={() => setState({ actionButton: data.symbol })}
    onMouseOut={() => setState({ actionButton: null })}
>

The, while looping over all the Cards, you can check if the curent one needs an icon like so:

{state && state.actionButton === data.symbol && (
    <Fab>
        <EmojiEmotionsIcon />
    </Fab>
)}

Updated sandbox