Need help with simple React code

I have been using Scrimba to write this code in React, but it doesn’t work. I don’t know why, and would appreciate your help in figuring it out!

function App() {
    let todoItems = "";
    let maxNumber = 4;
    while(maxNumber !== 0){
        maxNumber--;
        todoItems = todoItems + <TodoItem />;
    }
    
    return (
        <div>
        <ul>
            {todoItems}
        </ul>
        </div>
    )
}

The objective of this code is to return the same component (<TodoItem />) 4 times. But instead of seeing the components, my scrimba preview shows this:

Link to my code: https://scrimba.com/c/cbqPLzUa

Make todoItems an array and .push() items to it.

1 Like

Just to explain what’s happening, this isn’t a React thing, it’s a JavaScript thing. You’re turning objects into strings and joining the strings together. And the string representation of an arbitrary object is [object Object] (an object of type object).

1 Like

Thanks Dan. I didn’t know JSX elements were objects! That’s a very good explanation.

Thank you jenovs, now it works!

import React from "react"
import TodoItem from "./TodoItem.js"

function App() {
    let todoItems = []
    let maxNumber = 4;
    while(maxNumber !== 0){
        maxNumber--;
        todoItems.push(<TodoItem key={maxNumber} />);
    }
    
    return (
        <div>
        <ul>
            {todoItems}
        </ul>
        </div>
    )
}

export default App

1 Like