@CarlHumm
Posted
Hi there
The image does change, but only on initial load. To see this you can open up dev tools (F12) and inspect the img elements src. As you resize the webpage you will see the image src does not change. But if you resize and then refresh it does.
This is because the code responsible for changing the image is your if/else logic in your App.js component. This component is rendered once and then doesn't change. To get this to change you could implement some useState and then setState dependent on a resize event - but you don't need to do this, and probably shouldn't.
There are already more suitable native solutions to change images based on viewport that don't require JS, they include:
For a project like this I would probably use the Picture element.
Good luck.
Marked as helpful
@AshongAbdallah06
Posted
Wow Thanks a lot, Carl Humm. This works perfectly. Now I can see the changes based on the viewport.
@CarlHumm
Posted
@AshongAbdallah06
No problem, I am happy to help
Good job on changes. However, your picture element is missing the media attribute which you may want to fix.
Code Example
<picture>
<source srcset={desktopHeaderImage} media="(min-width: 600px)" />
<img src={mobileHeaderImage} alt="MDN" />
</picture>
I've added a basic media attribute to your code above so that the desktop image will show on viewports greater than 600px. You can change this to whatever condition you want, for example media="(orientation: portrait)"
, media="(min-width: 40em)"
, etc.
How to check if it's working?
To check to see if it works, you can open dev tools again (F12), go to network tab, click img, and then resize the page. As you resize the page you will see a new image source pop up.
Good luck on your next challenge
Marked as helpful
@AshongAbdallah06
Posted
Thanks again, @CarlHumm. I never even heard of this tag until you mentioned it. It's a game changer. Hopefully I'll be able to use it more. Thanks once again.