Lucky500
Lucky500

Reputation: 507

Toggle arrow using react

I am trying to toggle an arrow using React. found some examples online, but still not able to make it work.

this is what I have so far:

class Footer extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      active: false,
    };
  }

  handleClick() {
    const currentState = this.state.active;
    this.setState({
      active: !currentState
    })
  }
  

render() {
    return (
        <footer className="footer">
          <section className="container">
            <a className="visible-xs" role="button">
                       Social
              <i onClick={this.handleClick} className={this.state.active ? "fa fa-chevron-up" : "fa fa-chevron-down"} aria-hidden="true"></i>
             </a>
          </section>
         </footer>
    )
  }
}
         
module.exports = Footer;
  
  

Any help would be appreciated.

Upvotes: 1

Views: 3298

Answers (2)

ilrein
ilrein

Reputation: 3923

If you are using ES7 you can use helpful syntax to automatically bind your methods to your class, and make it more legible:

class Footer extends React.Component {  
  state = { active: false }

  handleClick = () => {
    const { currentState } = this.state;
    this.setState({ active: !currentState });
  }

  render() {
    const { active } = this.state;
    return (
      <footer className="footer">
        <section className="container">
          <a className="visible-xs" role="button">
            Social
            <i onClick={this.handleClick} className={active ? "fa fa-chevron-up" : "fa fa-chevron-down"} aria-hidden="true"></i>
          </a>
        </section>
      </footer>
    )
  }
}

module.exports = Footer;

Upvotes: 3

Jonathan.Brink
Jonathan.Brink

Reputation: 25383

The problem is that your handleClick function is not being called with the expected scope.

From the React doc:

You have to be careful about the meaning of this in JSX callbacks. In JavaScript, class methods are not bound by default. If you forget to bind this.handleClick and pass it to onClick, this will be undefined when the function is actually called.

Add this line of code at the end of your constructor:

// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);

Upvotes: 3

Related Questions