Skip to content
Advertisement

Toggle Icon on Button click React

I am trying to toggle the button icon when clicked in React app. I looked into the console, the value of “togglePassword” is changing on click but the button icon is not changing… How to correct this out? Here is my code…

class Register extends Component {

    constructor() {
        super();
        this.state = {
            togglePassword: false
        };

        this.onToggle = this.onToggle.bind(this);
    }

    onToggle(e) {
      this.setState({ togglePassword: !this.state.togglePassword })
    }

    render() {
       return (
          <button onClick={this.onToggle} type="button">
             {
              this.state.togglePassword ? 
              <i className="fas fa-eye-slash"></i> : 
              <i className="fas fa-eye"></i>
             }
          </button>
       );
    }
}

The other method I tried is as below but the console gave me the following error when I clicked the button…

<button onClick={this.onToggle} type="button">
           {
            this.state.togglePassword &&
            (<i className="fas fa-eye-slash"></i>)
           }
           {
            !this.state.togglePassword &&
            (<i className="fas fa-eye"></i>)
           }        
</button>

Error: failed to execute “remove child” on “Node”. The node to be removed is not a child of this node.

Advertisement

Answer

There might be something else apart from the code you have provided,

Below code snippet, this is exact copy of your code, and its working fine :


class App extends React.Component {

    constructor() {
        super();
        this.state = {
            togglePassword: false
        };

        this.onToggle = this.onToggle.bind(this);
    }

    onToggle(e) {
      this.setState({ togglePassword: !this.state.togglePassword })
    }

    render() {
       return (
          <button onClick={this.onToggle} type="button">
             {
              this.state.togglePassword ? 
              "fa-eye-slash": 
              "fa-eye"
             }
          </button>
       );
    }
}

ReactDOM.render(<App />, document.getElementById('react-root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react-root"></div>

WORKING DEMO : with font awesome

Edit #SO-react-font-awesome

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement