Yollo
Yollo

Reputation: 89

How to display component using forEach in ReactJS Application

How can I display my product.colors ? I need to parse them first that's why I'm trying with forEach somehow:

Here is what I tryed:

    const ParsedColors = props => {
            return(
            props.product.color.forEach(col => {
                const parsed = JSON.parse(col)
                return(
                    <button name="color" value={parsed.value} style={{backgroundColor: `${parsed.value}`}} onClick={() => colorPicker([props.product._id, parsed.value])}/>
                )
            })
            )
        }
...

<div>
    <ParsedColors product={product}/>
<div/>

I know that forEach isn't returning an array but I can't find a way to do it in map. As I said, I need to parse each color

This returns an err:

Error: ParsedColors(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.

Upvotes: 1

Views: 23

Answers (1)

Udendu Abasili
Udendu Abasili

Reputation: 1213

forEach returns nothing so you cannot assign a variable to it the way you are doing it. Use map instead

const ParsedColors = props => {
            return(
            props.product.color.map(col => {
                const parsed = JSON.parse(col)
                return(
                    <button name="color" value={parsed.value} style={{backgroundColor: `${parsed.value}`}} onClick={() => colorPicker([props.product._id, parsed.value])}/>
                )
            })
            )
        }
...

Upvotes: 1

Related Questions