Show button on mouse enter button

I have a react component that has a 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 hovering or mouse is being entered, I want to send a button on this div.

How can i do this?

thanks

+16
javascript reactjs
source share
3 answers

Update the state of the component to display whether the mouse is inside the component, then use the state value to conditionally display the 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 a conditional operator ( ? ) To return the button component if this.state.isMouseInside is true.

+25
source share

There is another approach that uses a reusable rendering component that will make the components β€œhang” or β€œopen” - whatever makes sense.

 class Hoverable extends Component { constructor() { super(); this.state = { isMouseInside: false }; } mouseEnter = () => { this.setState({ isMouseInside: true }); } mouseLeave = () => { this.setState({ isMouseInside: false }); } render() { return this.props.children( this.state.isMouseInside, this.mouseEnter, this.mouseLeave ) } } 

Then create a functional component that represents an element that may be overhanging. For example album

 const HoverableElement = props => ( <Hoverable> {(isMouseInside, mouseEnter, mouseLeave) => ( <div className="menu-item"> <div onMouseEnter={mouseEnter} onMouseLeave={mouseLeave}> <h2>{props.title}</h2> </div> {isMouseInside && props.children} </div> )} </Hoverable> ) 

Finally, use a HoverableElement to display a list of items, each of which will be "hoverable", such as an array of albums

 class HoverableElementsList extends Component { render() { return ( <div> <HoverableElement title="First Menu"> <p>Some children content</p> </HoverableElement> </div> ) } } 
+5
source share

cjjenkinson, thank you very much your answer save me a lot of time

-2
source share

All Articles