I have a component which by default is a button. But when pressed, it is replaced by four other buttons, each of which has a PNG image.
import React, {useState} from 'react';
import styles from './CallButton.module.css'
import whatsAppImg from '../../images/whatsapp.png'
import telegramImg from '../../images/telegram.png'
const CallButton = () => {
const [isActive, setIsActive] = useState(false);
return (<div className={styles.container}>
{isActive ?
<div className={styles.appearsLeft}>
<a className={styles.callButton} title={'Написать в WhatsApp'} href="https://wa.me/+79147726787">
<img src={whatsAppImg} className={styles.icon}/>
</a>
<a className={styles.callButton} title={'Написать в Telegram'} href="https://t.me/yolkin27">
<img src={telegramImg} className={styles.icon}/>
</a>
</div> :
<div className={styles.main}
onClick={() => setIsActive(true)}>
<div className={styles.notActiveButton}>Связаться со мной</div>
</div>
}
</div>);
};
export default CallButton;
In idle state it looks like this:
And in active state:
But the fact is that the pictures in the buttons start loading only after the transition to the active state. And I would like them to be loaded in advance. Is there a way to do this?
You can force the images loading by calling Image
constructor at the moment of component mounting.
Your code should look like this:
import React, {useState, useEffect} from 'react';
import styles from './CallButton.module.css'
import whatsAppImg from '../../images/whatsapp.png'
import telegramImg from '../../images/telegram.png'
const imagesSrcs = [whatsAppImg, telegramImg];
const CallButton = () => {
const [isActive, setIsActive] = useState(false);
useEffect(() => {
imagesSrcs.forEach(imageSrc => {
(new Image()).src = imageSrc;
})
}, []);
return (<div className={styles.container}>
{isActive ?
<div className={styles.appearsLeft}>
<a className={styles.callButton} title={'Написать в WhatsApp'} href="https://wa.me/+79147726787">
<img src={whatsAppImg} className={styles.icon}/>
</a>
<a className={styles.callButton} title={'Написать в Telegram'} href="https://t.me/yolkin27">
<img src={telegramImg} className={styles.icon}/>
</a>
</div> :
<div className={styles.main}
onClick={() => setIsActive(true)}>
<div className={styles.notActiveButton}>Связаться со мной</div>
</div>
}
</div>);
};
export default CallButton;