Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace element on hover in ReactJs

In this code

 <div class='wrapper'>
     <div class='icon'>
        <i className="fa fa-fw fa-globe" style={{ fontSize: '1.75em' }} />
      </div>
 </div>

whenever the user hovers over the 'icon' div, this code

<i className="fa fa-fw fa-globe" style={{ fontSize: '1.75em' }} />

should be replaced with this one

<p> Lorem ipsum </p>

I able to achieve changing styles but don't know how to replace elements. Please help me in this.

like image 369
kzrfaisal Avatar asked Aug 03 '18 11:08

kzrfaisal


2 Answers

As with most things in React, you need a state. Something like:

constructor() {
  super();
  this.state = {isHovered: false};
}

This state needs to change anytime the user hovers in or out of the icon:

toggleHover() {
  this.setState(prevState => ({isHovered: !prevState.isHovered}));
}

<div className='icon' onMouseEnter={this.toggleHover} onMouseLeave={this.toggleHover}>

Then the logic for deciding what should be displayed, depending on that state:

{this.state.isHovered ?
  <p> Lorem ipsum </p> :
  <i className="fa fa-fw fa-globe" style={{ fontSize: '1.75em' }} />
}

You may want to have two separate methods, one for onMouseEnter and one for onMouseLeave, rather than just a shared method for both, like I did.

Oh, and you had a typo: You wrote class rather than className in a few places.


Demo

class App extends React.Component {
  constructor() {
    super();
    this.state = {isHovered: false};
    this.toggleHover = this.toggleHover.bind(this);
  }
  
  toggleHover() {
    this.setState(prevState => ({isHovered: !prevState.isHovered}));
  }

  render() {
    return (
      <div className='wrapper'>
        <div className='icon' onMouseEnter={this.toggleHover} onMouseLeave={this.toggleHover}>
          {this.state.isHovered ?
            <p> Lorem ipsum </p> :
            <i className="fa fa-fw fa-globe" style={{ fontSize: '1.75em' }} />
          }
        </div>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("app"));
.icon i {
  display: block;
  width: 32px;
  height: 32px;
  background: url('https://via.placeholder.com/32x32');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
like image 176
Chris Avatar answered Sep 18 '22 02:09

Chris


In addition of @Chris's answer, If you would not like to create an event handler then you can create an inline arrow function that does the job.

onMouseEnter={()=> this.setState({isHovered: true})}

onMouseLeave={()=> this.setState({isHovered: false})}

This is just a shorthand you can go with.

like image 25
Manoz Avatar answered Sep 19 '22 02:09

Manoz