0

I can render 1 component but is there another way to render others components depending what am I hovering?

constructor(props) {
        super(props)
        
        this.handleMouseHover = this.handleMouseHover.bind(this)
        this.state={
            isHovering: false
        }
    }

    handleMouseHover(){
        this.setState(this.toggleHoverState)
    }

    toggleHoverState(state) {
        return {
            isHovering:!state.isHovering
        }
    }
<a href="#" onMouseEnter={this.handleMouseHover} onMouseLeave={this.handleMouseHover}>Hover me1</a>
<a href="#" onMouseEnter={this.handleMouseHover} onMouseLeave={this.handleMouseHover}>Hover me2</a>
{isHovering && (<Component/>)}
João Marcos
  • 63
  • 1
  • 6
  • Does this answer your question? [How can I access a hover state in reactjs?](https://stackoverflow.com/questions/32125708/how-can-i-access-a-hover-state-in-reactjs) – Karim Chaari May 04 '21 at 01:46

2 Answers2

2

You can use switch if you have more than one element to display based on hovering of one element.

Below in the example I have considered 3 anchor elements and added corresponding mouse over and mouse out event handlers in order to display the corresponding hovered element below them.

const {useState} = React;

const App = () => {
  const [hoveredOn, setHoveredOn] = useState(-1);
  
  const getElement = () => {
    switch(hoveredOn) {
      case 0: return <p>Hovered Element 0</p>
      case 1: return <p>Hovered Element 1</p>
      case 2: return <p>Hovered Element 2</p>
    }
  }
  
  const onMouseOver = (index) => {
    setHoveredOn(index);
  }
  
  const onMouseOut = () => {
    setHoveredOn(-1);
  }
  
  return (
    <div>
      <a href="#" onMouseOver={() => {onMouseOver(0)}} onMouseOut={onMouseOut}>Element 0</a>
      <a href="#" onMouseOver={() => {onMouseOver(1)}} onMouseOut={onMouseOut}>Element 1</a>
      <a href="#" onMouseOver={() => {onMouseOver(2)}} onMouseOut={onMouseOut}>Element 2</a>
      {getElement()}
    </div>
  )
}

ReactDOM.render(<App />, document.getElementById("react"));
a {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>

<div id="react"></div>

You can also add a default case to the switch case in order to display a default component or any message as well based on your requirement.

Nithish
  • 5,393
  • 2
  • 9
  • 24
1

To conditionally show a different component depending on if isHovering is true or false, this should work.

Change

{isHovering && (<Component/>)}

to

{isHovering ? (<Component1/>) : (<Component2/>)}

This will display <Component1/> if true, and <Component2/> if false.

Will Walsh
  • 1,799
  • 1
  • 6
  • 15