blankface
blankface

Reputation: 6347

Dynamically generate <tr> through a function in React

I have the following function that is supposed to return a <tr> when we map over the elements:

renderProductRow = () => {
    let table;
        for(let product in this.props.productProgressInfo){
            productName.push(this.props.productProgressInfo[product]);
        }
//productName is an array that simply holds the name of the products
        productName.map((name:any)=> {
            table = <tr>
                        <td>Product</td>
                        <td>{name}</td>
                        <td>{this.props.siteStatusQueued}</td>
                    </tr>
            return table;
        })
      return table;
    }
  return table;
}

In my render() return statement I am calling this.renderProductRow(). When it fires, I can see 1 row getting rendered for a split second and then disappearing. My guess is I'm somehow messing up the return statement in the function.

Upvotes: 0

Views: 122

Answers (1)

Joshua R.
Joshua R.

Reputation: 2302

The result of map, which you'd like to return, is an array, but you're not storing the result. Using table as variable is confusing because after your map function exits, it stays set to the value produced by the last entry in productName.

It looks like you mean to do this:

renderProductRow = () => {

  if (<condition>) {

    for(let product in this.props.productProgressInfo){
        productName.push(this.props.productProgressInfo[product]);
    }

   return  productName.map((name:any)=> {
        return (<tr>
                    <td>Product</td>
                    <td>{name}</td>
                    <td>{this.props.siteStatusQueued}</td>
                </tr>)
    }) }
   else
   {return null}  // or return an empty array [] depending on what parent component expects.
}

Upvotes: 1

Related Questions