1

I was trying to use forEach or map functions with no success (had xxx is not a function errors). Decided to go with good old for loop but instead of creating multiple div elements my program only renders one.

Simplified example:

getTest(){
    const l = this.props.renderedDrugs.length;

    for(var i = 0; i < l; i++){
        return <div>{this.props.renderedDrugs[i].id}</div>
    }
}

render() {

    const test = (this.props.renderedDrugs) ? this.getTest() : nope()

    function nope(){
        return 'nope'
    }
    return (
        <div>{test}</div>
    )
}
}

No matter what I do I cant return multiple divs, have no problems with multiple console logs though. Am I missing something crucial from basic react functions that I completely forgot because of staring at the screen like a moron?

1 Answer 1

1

You do want map:

getTest() {
    return this.props.renderedDrugs.map(rd => <div>{rd.id}</div>)
}

The reason only one renders is because return <div>{this.props.renderedDrugs[i].id}</div>, ya know, returns that value from the function. map is a lot cleaner but you can emulate map with your for loop and an array:

getTest(){
    const l = this.props.renderedDrugs.length;
    const ary = [];

    for(var i = 0; i < l; i++){
        ary.push(<div>{this.props.renderedDrugs[i].id}</div>);
    }
    return ary;
}
Sign up to request clarification or add additional context in comments.

4 Comments

I'd love to use a map, atlhough i keep getting 'this.props.renderedDrugs.map is not a function' and cant fix that
Then this.props.renderedDrugs is not an array.
@MazMat edited answer that shows you how to build an array from a for loop.
This works for me, thank you, I completely forgot you cant map through objects

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.