pizzae
pizzae

Reputation: 3025

(React) Can't have content hide on hover?

So I have this code here, where I am essentially trying to hide some icon, when I hover over its parent div. Or make it visible, but either way...

export class ProgramDescription extends React.Component {

  constructor(props) {
    super(props);
  }

  showIcon() {
    this.refs.edit.style.visibility = 'visible';
  };

  hideIcon() {
    this.refs.edit.style.visibility = 'hidden';
  };

  componentDidMount() {
    this.refs.edit.style.visibility = 'hidden';
  }

  render() {
    return (
        <div className="ui one cards">
          <div className="card">
            <div className="content">
              <div className="header">Program description</div>
              <div className="description package" onMouseEnter={ this.showIcon }
              onMouseLeave={ this.hideIcon }>
                <i ref="edit" id="edit-icon" className="edit icon"/>
                <p id="desc">
                  Lorem Ipsum</p>
              </div>
            </div>
          </div>
        </div>
    );
  }
}

But apparently im getting this error, whenever I hover:

Uncaught TypeError: Cannot read property 'edit' of undefined

Even though I do have an element with ref='edit'. The code for the componentDidMount() function does work though, so I am assuming that the references in both showIcon() and hideIcon() are generated at the start, before the 'edit' element is even rendered. I think thats dumb of js to just "precache" and not read my functions "as-is".

Anyways, how do I fix this? Something about states?

Upvotes: 0

Views: 1495

Answers (1)

abhirathore2006
abhirathore2006

Reputation: 3745

its because you didn't bind the functions so its context is of event instead of react, you can bind functions it in two ways

1.constructor ( Preferred way )

this.showIcon = this.showIcon.bind(this)

then in Jsx use

this.showIcon
  1. in JSX

    //use

    this.showIcon.bind(this)

    //instead of

    this.showIcon

Upvotes: 3

Related Questions