AfonsoSalgadoSousa
AfonsoSalgadoSousa

Reputation: 405

Apply style to child component when parent is hovered

I have a li tag that has a child label with text. This child label has styling so when it is hovered it does an animation. I wanted to trigger this animation when the parent (li) is hovered. How can I do this?

Additionally, when I click the child (label) tag, the onClick event of the li is not triggered. What can I do to propagate the click over the child to the parent?

Following is a snippet of my code:

  const [activeTab, setActiveTab] = useState('1')
  const handleClick = (e) => {
    const target = e.target
    setActiveTab(target.id)
  }

  return (
    <Styled.Tabs>
      <Styled.TabList>
        {data.map(({ id, job, institution, date, summary }) => {
          return (
            <Styled.TabItem
              key={id}
              id={id.toString()}
              onClick={handleClick}
              className={activeTab === id.toString() ? 'active' : ''}
            >
              <Styled.HoverEffectText>{job}</Styled.HoverEffectText>
            </Styled.TabItem>
          )
        })}
      </Styled.TabList>

I am using styled-components. The behaviour I am getting is that I hovering over HoverEffectText (the label) triggers its hovering properties, and only hovering outside of it can I activate the li tab or trigger li onHover styling.

Thanks for any help you can provide.

Upvotes: 0

Views: 55

Answers (1)

Joseph Walker
Joseph Walker

Reputation: 72

You could create this hover effect using css like this.

 .parent:hover .child {
    //hover stlyes...
}

and as for the parent element handling the event, I'm pretty sure you would just want to put the onClick event in the parent element.

Upvotes: 1

Related Questions