0

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?

pizzae
  • 2,815
  • 6
  • 26
  • 45
  • 3
    Possible duplicate of [Unable to access React instance (this) inside event handler](http://stackoverflow.com/questions/29577977/unable-to-access-react-instance-this-inside-event-handler) – Felix Kling Nov 15 '16 at 07:23
  • @FelixKling That answer is pretty vague and im having trouble getting it working – pizzae Nov 15 '16 at 11:09

1 Answers1

3

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

abhirathore2006
  • 3,317
  • 1
  • 25
  • 29