0

I am using react and using this for of loop here gives me an error "x is undefined".

import { useEffect } from "react";

export default function HomeContent() {
  useEffect(() => {
    let content = document.getElementsByClassName("content");
    let contentList = [
      "Hi! I am Aaditya",
      "I'm a Freelance Web Designer currently based in New Delhi, India",
    ];
    for (x in contentList) {
      console.log(x);
    }
  }, []);

  return (
    <div className="HomeContent">
      <div className="content"></div>
      <i className="fas fa-sort-down fa-5x next"></i>
    </div>
  );
}
  • es6 modules run in strict-mode, so you need to define `x` in your for loop: `for(const x of contentList)` - also, don't use a `for...in` to iterate an array (see: [For-each over an array in JavaScript](https://stackoverflow.com/a/9329476)) – Nick Parsons Aug 10 '21 at 08:54
  • You might be looking for `for(let x of contentList)` not `in` – Abd Elbeltaji Aug 10 '21 at 08:55

2 Answers2

2

First of all, you are using a for in, and not a for of. That said, you must declare x, so:

for (let x in contentList)
  console.log(x); 
}
limdev
  • 706
  • 1
  • 5
  • 18
0

Change this:

for (x in contentList) {
    console.log(x);
}

To this:

contentList.forEach(x => console.log(x));
Marko Borković
  • 1,884
  • 1
  • 7
  • 22