Home > Software engineering >  how do I solve preview.className.remove is not a function in React?
how do I solve preview.className.remove is not a function in React?

Time:05-04

Ive created an image gallery in react but when you try and click on the different image it doesnt swap to the big image. When I console.log the image preview it comes up as preview.className.remove is not a function. Can anyone help please? Thank you in advance

import React, { useState } from 'react';

export default function ImageGallery(prod) {


console.log("image-preview")

const product=prod


 const highlight = document.querySelector (".gallery-highlight");
 const previews = document.querySelectorAll (".image-preview img");


 previews.forEach(preview => {
 preview.addEventListener("click", function() {
 const smallSrc = this.src;
 const bigSrc = smallSrc.replace ("small", "big");
 previews.forEach(preview => preview.className.remove("image-active"));
 highlight.src = bigSrc;
 preview.className.add("image-active");
 });
 });


return (

<div className="image-gallery">
 <img className="gallery-highlight" src={product.prod.image} alt={product.prod.name} 
 />
<div className="image-preview">
<img src={product.prod.image2} alt={product.prod.name}className="image-active" />
<img src={product.prod.image3} alt={product.prod.name}/>

<br />

</div>
 );
 }

CodePudding user response:

const previews = document.querySelectorAll (".image-preview img");

Will give you the list of HTML nodes that are available on UI with that selector. You are accessing className from that list item and you'll get a string value. You can't execute remove on a string value.

You can try with classList instead of className. Your code will be changed like this.

 previews.forEach(preview => preview.classList.remove("image-active"));

CodePudding user response:

Seems like you're trying to add dynamically css classes I'd suggest you to do it bases on state or props like:

const [active, setActive] = useState(false);
<div className={active? "active" : ""}></div>

Here you can find more examples.

  • Related