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..
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With