简体   繁体   中英

Changing Font Awesome Button Style onClick

I have a button styled as a Font Awesome.

              <button
                onClick={this.changeLockButtonStyle}
                id="LockButton"
                >
                <FaLockOpen />
              </button>

I'm trying to find a way to change the style to <FaLockClosed /> From reading up online the only examples I see are regarding JQuery and class=”fas fa-lockclosed” toggle class. But I am using a button, not the normal icon. I have tried document.getElementById('LockButton').innerHTML= '<FaLockClosed />' but doesnt work. I'd like to avoid using JQuery if possible.

Here you go:

const [isLocked, setIsLocked] = useState(false);

return (
    <button
        type="button"
        onClick={() => { setIsLocked(true); }}
    >
        {isLocked ? <FaLockClose /> : <FaLockOpen />}
    </button>
);

Update: Thats how you do it in class component.

constructor(props) {
    super(props);

    this.state = {
        isLocked: false
    };

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

lockIcon() {
    this.setState({ isLocked: true });
}

render() {
    const { isLocked } = this.state;

    return (
        <button
            type="button"
            onClick={this.lockIcon}
        >
            {isLocked ? <FaLockClose /> : <FaLockOpen />}
        </button>
    );
}

My best practice solution is using css class. But if you can't do it , you can use display state for the 2 icons that controlled by a javascript variable.

If you using react or angular, I would just toggle the component depending on a variable set during button pushed.

Reference on how to do the toggle in react https://stackoverflow.com/a/46425155/14167216

Here is a jQuery example. You can set the class on the button and then check if button has class. If it has lock class then change to unlock class, and vice-versa. Check the sample code below.

 function changeLockButtonStyle() { var icon = $('#LockButton') var hasLock = icon.hasClass('fa-lock'); if(hasLock) { icon.removeClass('fa-lock').addClass('fa-unlock'); } else { icon.removeClass('fa-unlock').addClass('fa-lock'); } }
 <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> </head> <body> <button onClick='changeLockButtonStyle()' id="LockButton" class="fa fa-lock" > </button> </body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM