i am just trying to change the image but it does not work
I have checked the links they are working but not the onclick function
protfolio.js
import Image from 'next/image';
import React from 'react';
const Portfolio = () => {
const changeImage = () => {
const image = document.getElementById('myImage');
if (image.src.match("https://images.unsplash.com/photo-1506905925346-21bda4d32df4?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2340&q=80")) {
image.src = "https://images.unsplash.com/photo-1594717527389-a590b56e8d0a?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2070&q=80";
}
}
return (
<div className='max-w-[1240px] mx-auto py-16 text-center'>
<button onClick={changeImage} >Travel Photos</button>
<div className='grid grid-rows-none md:grid-cols-5 p-4 gap-4'>
<div className='w-full h-full col-span-2 md:col-span-3 row-span-2'>
<Image
src='https://images.unsplash.com/photo-1506905925346-21bda4d32df4?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2340&q=80'
id='myImage'
alt='/'
layout='responsive'
width='677'
height='451'
onClick={changeImage}
/>
</div>
</div>
</div>
);
};
export default Portfolio;
CodePudding user response:
I would highly recommend you to use the useRef to replace the src for the image
const imageRef=useRef();
bind ref to image
<img ref={imageRef} />
Use imageRef to change the src like this
imageRef.current.src = {image}
Hope it will help to resolve your issue.
CodePudding user response:
Is there any reason you are not using state for this?
const [imageUrl, setImageUrl] = useState('https://images.unsplash.com/photo-1506905925346-21bda4d32df4?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2340&q=80')
And on image onClick
onClick={()=> changeImage(imageUrl); }
And you function would be like this
const changeImage = (currentImageUrl) => {
if (currentImageUrl.match("https://images.unsplash.com/photo-1506905925346-21bda4d32df4?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2340&q=80")) {
setImageUrl("https://images.unsplash.com/photo-1594717527389-a590b56e8d0a?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2070&q=80")
}