Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react show button on mouse enter

Tags:

I have a react component which hold method like:

mouseEnter(){     console.log("this is mouse enter") }  render(){     var album_list;     const {albums} = this.props     if(albums.user_info){         album_list = albums.user_info.albums.data.filter(album => album.photos).map((album => {             return                 <div className={"col-sm-3"} key={album.id}     onMouseEnter={this.mouseEnter}>                     <div className={(this.state.id === album.id) ? 'panel panel-default active-album' : 'panel panel-default'} key={album.id} onClick={this.handleClick.bind(this, album.id)}>                         <div className={"panel-heading"}>{ album.name }</div>                         <div className={"panel-body"}>                             <img className={"img-responsive center-block"} src={album.photos.data[0].source} />                         </div>                     </div>                 </div>             }))         }         return (             <div className={"container"}>                 <div className="row">                     {album_list}                 </div>             </div>         )     } } 

Here I have onMouseEnter on album_list. When it is hover or mouse enter I want to dispalay a button on that div.

How can I do that ??

Thank you

like image 301
varad Avatar asked Mar 01 '16 04:03

varad


1 Answers

Update the component's state to reflect whether the mouse is inside the component, then use the state value to conditionally render a button.

getInitialState() {   return {     isMouseInside: false   }; } mouseEnter = () => {   this.setState({ isMouseInside: true }); } mouseLeave = () => {   this.setState({ isMouseInside: false }); } render() {   return (     <div onMouseEnter={this.mouseEnter} onMouseLeave={this.mouseLeave}>       {this.state.isMouseInside ? <button>Your Button</button> : null}     </div>   ); } 

Inside the render function we use the conditional operator (?) to return the button component if this.state.isMouseInside is truthy.

like image 160
Dan Prince Avatar answered Oct 15 '22 10:10

Dan Prince