Joe
Joe

Reputation: 41

React/JS - onMouseOver Changing the Text

So I'm trying to get additional text to display when using the onMouseHover but I can't seem to understand it, like I'm trying to figure out a way without having to use CSS or JQuery. How can I make onMouseHover display text based off a function call?

    function URL() {
        return (
            <a href={url} onMouseOver={mouseOver()}>{mouseOver()}</a>
        );
    }
    function mouseOver() {
        return (
            <p>Hovering</p>
        );
    }

Upvotes: 2

Views: 16643

Answers (3)

Arye Eidelman
Arye Eidelman

Reputation: 1966

Here is a useHover react hook.

It should make it a bit cleaner if you need to track the hover state for multiple dom elements.

import { useState } from 'react'

function useHover() {
  const [hovering, setHovering] = useState(false)
  const onHoverProps = {
    onMouseEnter: () => setHovering(true),
    onMouseLeave: () => setHovering(false),
  }
  return [hovering, onHoverProps]
}

function myComponent() {
  const [buttonAIsHovering, buttonAHoverProps] = useHover()
  const [buttonBIsHovering, buttonBHoverProps] = useHover()

  return (
    <div>
      <button  {...buttonAHoverProps}>
        {buttonAIsHovering ? "button A hovering" : "try hovering here"}
      </button>
      <button  {...buttonBHoverProps}>
        {buttonBIsHovering ? "button B hovering" : "try hovering here"}
      </button>
    </div>
  )
}

Upvotes: 8

AngelSalazar
AngelSalazar

Reputation: 3113

class HoverableComponent extends React.Component {
   constructor() {
     super();
     this.state = { text : '' }
   }
   //set the text
   onMouseover (e) {
     this.setState({text : 'some text'})
   }
   //clear the text
   onMouseout (e) {
     this.setState({text : ''})
   }
   render () {
      const {text} = this.state;
      return (
        <div 
          onMouseEnter={this.onMouseover.bind(this)}
          onMouseLeave={this.onMouseout.bind(this)}>{text}</div>
      )
   }
}

Upvotes: 11

Douglas Tyler Gordon
Douglas Tyler Gordon

Reputation: 569

You could use a combination of onMouseEnter and onMouseLeave to change state (which you'll need to initialize in your constructor function). For example:

    function URL() {
      return (
        <a href={url} onMouseEnter={showText()} onMouseLeave={hideText()}>{this.state.text}</a>
      );
    }
    function showText() {
      this.setState({text : "Hovering"}) 
    } 
    function hideText() {
      this.setState({text : ""}) 
    } 

Upvotes: 1

Related Questions