0

I am new to ReactJS and encountered an error when using a simple for loop in my code. The error points to the semicolon within the loop, but I'm not sure how to fix it. Here's the code snippet:

const resume = {
interest :['Drawing','Photography','Design','Programming','Computer Science'],

skills :['Web Design with React'],

education :['Wilton High School','Silvermine School of Arts','Codeacademy'],

experience :['Student Technology Intern for Wilton School','Babysitter'],

extracurriculas :['Recycling Club','Gardening Club','Book Club']
    }
    
    function App() {
    
      var len = resume.interest.length;
    
      return (
    
        <>
          for (let index = 0; index < len; index++) {
            <h1>{resume.interest[index]}</h1>
            
          }
        </>
      )
    }
    
    export default App;

The error message I'm getting is: "Parsing error : Unexpected token". It seems that the for loop is causing the issue, specifically the semicolon. How can I resolve this error and successfully loop through the resume.interest array to display each interest as an element? This above code throw error like that:Screenshot of error

But it works when I did

<h1>{resume.interest[0]}</h1>

without for loop

  • [Loop inside React JSX](https://stackoverflow.com/questions/22876978/loop-inside-react-jsx) you may want to check this out – Khairani F May 13 '23 at 04:16
  • I answered below but then saw @KhairaniF's comment and realized it's a duplicate, so voting to close [in favor of this one](https://stackoverflow.com/questions/22876978/loop-inside-react-jsx) – Zac Anger May 13 '23 at 04:19

1 Answers1

0

All JavaScript in JSX (the HTML-ish part) needs to be wrapped in braces. This would cause a problem when using a for loop, because you can't return more JSX from a for loop, because it's not a function. Instead you'll want to use map:

function App() {
  return (
    <>
      {resume.interest.map((int) => <h1 key={int}>{int}</h1>)}
    </>
  )
}

Any elements returned by a map have to have a key prop that is unique, so we're using the same element that's getting passed into the h1.

If it helps, you might try using React without JSX, to understand how putting plain JS inside your JSX works. Each tag is just syntax sugar for a function call, and the children argument is an array, not arbitrary code, under the hood. Check out the docs if you're curious.

Zac Anger
  • 6,983
  • 2
  • 15
  • 42