Unexpected output from functions inside React components
P粉614840363
P粉614840363 2024-04-03 00:17:44
0
1
319

I imported two images ( IMG and IMG2 ). The IMG is assumed to be displayed when the viewport width is less than 600px, and another one is displayed if the viewport width is greater than or equal to 600px. So I added a function that checks the viewport width and then it returns one of those two images, but the problem is that it only returns the first image I put in the function, which is IMG. Even if the viewport width becomes larger than 600px, it still shows IMG instead of IMG2. Note: I can solve this problem by just using media queries and setting display to None, but I would like to know how to solve this problem using React.

Link to all my code in Github: https://github.com/Issamath/PerfumeProduct.com

import IMG from '../../assets/image-product-mobile.jpg'
import IMG2 from '../../assets/image-product-desktop.jpg'

const ProductImage = () => {
  function displayImage(){
    let vw = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0);
    console.log(vw);
    if(vw < 600) {
     console.log(vw + "is smaller than 600");
     return (<img src={IMG} alt="" />);
    } else {
     console.log(vw + "is bigger than 600");
     return (<img src={IMG2} alt="" />);
    }
}
  return (
    <div className='container-img'>
      {displayImage()}
    </div>
  )
}

export default ProductImage
.container-img img {
    height: 15rem;
    width: 100%;
    background: white;
    border-radius: 0.8rem 0.8rem 0 0;
}

.container-img {
   
}

 /* -----------------for bigger phones------------------- */

@media screen and (min-width: 390px) {
    .container-img img {
        height: 20rem;
    }
}

P粉614840363
P粉614840363

reply all(1)
P粉401901266

To do this with React, you need to attach to the document resize event.

Below is a simple example that changes the text and background color on resize.

const {useEffect, useState} = React;

const getWidth = () => document.documentElement.clientWidth;

const ResizeCheck = () => {
  const [width, setWidth] = useState(getWidth());
  useEffect(() => {
    const resize = () => setWidth(getWidth());
    window.addEventListener('resize', resize);
    return () => window.removeEventListener('resize', resize);
  }, []);
  return 
{ width >= 600 ?
Greater than equal to 600
:
Less than 600
}
; } const root = ReactDOM.createRoot(document.querySelector('#mount')); root.render();
sssccc
sssccc

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!