Home > Enterprise >  How can I convert HTMLCollection to Array instead of an empty array in React?
How can I convert HTMLCollection to Array instead of an empty array in React?

Time:06-28

i'm studying react and also an beginner. ploblem had caused when i was trying to convert HTMLCollection into an array. here's code.

const HeroSlide = ({ items }) => {

  const heroSlide = useRef(null);

  useEffect(() => {
    const arr = Array.from(heroSlide.current.children);
    arr.map((child) => {
      child.className = 'text only';
    });
    console.log(arr);
    // got 4 text-only divs. divs created by using map func are excluded
  }, []);

  return (
    <div className="heroSlide" ref={heroSlide}>
      <div>text only</div>
      {items.map((e, i) => (
        <div className="heroSlide__items">
          <img
            src={apiConfig.originalImage(e.backdrop_path)}
            className="heroSlide__backgroundImage"
            alt=""
          />
        </div>
      ))}
      <div>text only</div>
      <div>text only</div>
      <div>text only</div>
    </div>
  );
};

if i use setTimeout console.log works. but i need better way.

useEffect(() => {
    setTimeout(() => {
      const arr = Array.from(heroSlide.current.children);
      console.log(arr);
    }, 50);
  }, []);

CodePudding user response:

create a variable and push values as shown below -

const heroSlide = useRef(null);
let arr = []
useEffect(() => {
console.log(heroSlide.current.children);
console.log('array is',arr.push(...heroSlide.current.children))
console.log('arr',arr)    
    }, []);

CodePudding user response:

I solved problem in this way. I passed the dynamic process to the child node to perform it. now i gets complete array.

const HeroSlideItems = ({ items }) => {
  return (
    <div className="heroSlide__items">
      {items.map((e, i) => {
        return (
          <div className="heroSlide__items__index">
            <img
              src={apiConfig.originalImage(e.backdrop_path)}
              className="heroSlide__backgroundImage"
              alt=""
            />
          </div>
        );
      })}
    </div>
  );
};

const HeroSlide = ({ items }) => {
  const heroSlideRef = useRef(null);

  useEffect(() => {
    if (heroSlideRef.current) {
      const children = Array.from(heroSlideRef.current.children);
      children.forEach((c) => {
        c.className = 'changed';
      });
    }
  }, []);

  return (
    <div className="heroSlide" ref={heroSlideRef}>
      <div>testclass</div>
      <HeroSlideItems items={items} />
      <div>testclass</div>
      <div>testclass</div>
      <div>testclass</div>
    </div>
  );
};


  • Related