Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switching between images to avoid "jumping" behaviour

Tags:

html

css

reactjs

I am trying to imitate the behaviour of a checkbox by switching custom checkbox images depending on the condition (true or false). I get a very annoying visual bug where as I set state to the truthy or falsy condition the images depending on it and the box does a little flickr before switching, here's my code:

import React from 'react';
import boxCheckedIcon from '../../../../assets/SmallBoxChecked.svg';
import boxUncheckedIcon from '../../../../assets/SmallBoxUnchecked.svg';


class Example extends React.Component {

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


    handleSelect = () => {
        this.setState(prevState => ({
            condition: !prevState.condition
        }));
    }


    renderCheckbox = condition => {
        return condition ? <img
            id="checkedCheck"
            src={boxCheckedIcon}
            alt="checked check box"
        /> : <img
                id="uncheckedCheck"
                src={boxUncheckedIcon}
                alt="unchecked check box"
            />
    };

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

        return (
            <div onClick={() => handleSelect()}>
                {renderCheckbox(condition)}
            </div>
        );
    }
}

any idea how to make the transition between the two images smoother? CSS, React or otherwise..

like image 450
ksenia Avatar asked Jan 24 '23 17:01

ksenia


1 Answers

The most correct would be to move your images to a CSS-sprite and switch it background-position by an additional class

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

  return (
    <div
      className={classNames(
        'checkbox__icon',
        condition && 'is-checked',
      )}
      onClick={this.handleSelect}
    />
  );
}

In the example, I use the lib https://www.npmjs.com/package/classnames

like image 99
Alexandr Avatar answered Jan 27 '23 05:01

Alexandr