mochamethod
mochamethod

Reputation: 107

Creating elements through a function, and appending the new elements to parents in the render function?

I have an object that I want to return data from through iteration, e.g.,
{"hello": 1, "world": 2}

Could I write a function that iterated through the object, and return the values as elements, like so:

iterateObject() {
    for (var key in myObject) {
        return <span>{myObject[key]}</span>
    }
}

And if I can return elements that way, how would I go about adding them to existing parent elements in my render function?

render() {
    return(
        <div className="objectData">
            APPEND NEW ELEMENTS HERE
        </div>
    )
}

Upvotes: 0

Views: 20

Answers (1)

Anthony
Anthony

Reputation: 6482

You can return the Array from map():

iterateObject() {
    return Object.values(myObject).map((item,i) => {
        return <span key={i}>{item}</span>
    }
}

render() {
    return(
        <div className="objectData">
            {this.iterateObject()}
        </div>
    )
}

Upvotes: 1

Related Questions