Answers to Why are for loops not allowed in React - JSX? ( 4 )

  1. 2017-08-08 21:08

    It's because the JSX expects anything inside of it to return an object to be displayed. A for loop does not return anything, but map does.

    You could make a for loop if you had something like this

    const getObjects = () => {
      const objs = []
      for (var i=0; i < objects.length; i++) {
        objs.push(<ObjectRow obj={objects[i]} key={i}>)
      }
    
      return objs;
    }
    
    <tbody>{getObjects()}
    
  2. 2017-08-08 21:08

    In JSX, you have to pass expression (produces a value) into curly braces. However for loop is a statement (performs an action).

    Furthermore, what you have tried in for-loop is not a valid javascript.

  3. 2017-08-08 21:08

    The for loop doesn't return any value. The for loop simply does something to each item in an array.

    On the other hand, map returns a new array of React elements.

    For instance:

    function giveMeAnArrayPlease() {
      // Doesn't do anything, just loops through the array
      var array = ['Hey', 'Hi', 'What's up'];
      for (var i = 0; i < array.length; i++) {
        array[i];
      }
    }
    

    VS

    function giveMeAnArrayPlease() {
      // Returns a nice uppercase array
      var array = ['Hey', 'Hi', 'What's up'];
      return array.map(word => word.toUpperCase());
    }
    

    Map returns a new array with all of the words uppercased. React can take an array of elements and turn it into elements, such as in the example, but it cannot take 'undefined' and turn it into an element.

  4. 2017-08-08 23:08

    As others have noted, a for loop does not return an object whereas .map does. This also means you could use a .filter or a .reduce.

    For the record, you could use a for loop outside of the JSX and pass in the object you create. This could be done in the render method of a React Component Class before the return using the spread operator in the JSX. Here's an example:

    render() {
         const objs = []
         for (var i=0; i < objects.length; i++) {
             objs.push(<ObjectRow obj={objects[i]} key={i}>)
         }
    
         return (
             <div> {...objs} </div>
         )
    }
    

Leave a reply to - Why are for loops not allowed in React - JSX?

◀ Go back