skip to Main Content

I tried using ternary operator but it did not work

import cclogomobile from '../../assets/cc-logo-mobile.svg'
import React, { useState } from 'react'

export default function imag(){
return(
 <>
  <img src={(window.width>700)? {cclogo}:{cclogomobile}} alt="cclogo" />
 </>
)}

this is what it showed when window.width>700

2

Answers


  1. Try adding an EventListener to look for event change if you want to include that functionality. Other than that, you just have to use window.innerWidth instead of window.width inside your component. Also make sure to import the other image you are using

    import cclogomobile from '../../assets/cc-logo-mobile.svg'
    import React, { useState, useEffect } from 'react'        
    
    export default function Image() {
      const [largeScreen, setLargeScreen] = useState(false);
        
      useEffect(() => {
        // Handler to call on window resize
        function handleResize() {
           if (window.innerWidth>700) {
              setLargeScreen(true);
           }
        }
        
        // Add event listener
        window.addEventListener("resize", handleResize);
        handleResize();
        
        // Remove event listener on cleanup
        return () => window.removeEventListener("resize", handleResize);
      }, []);
        
        return <img src={largeScreen ? {cclogo}:{cclogomobile}} alt="cclogo" />
    }
    
    Login or Signup to reply.
  2. The react answer is correct but you really dont need to use an eventListener there is an html picture element that will do this for you.

    <picture>
      <source media="(max-width: 700px)" srcset={cclogomobile} />
      <img src={cclogo} alt="cclogo" />
    </picture>
    

    https://developer.mozilla.org/en-US/docs/Web/HTML/Element/picture

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search