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/>)} 
1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

Yes but i mean with 4 components or more

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.