Home > Net >  Map method in javascript gives a syntax error
Map method in javascript gives a syntax error

Time:10-15

I'm experiencing a syntax error on my map function that says:

',' expected

Here is the relevant code:

class Products extends Component {
  constructor() {
    super();
    this.state = {
    cart: []
   }
}
render () {
const { products } = this.props;
return (
  <>
   <thead>
     <th scope="col"><strong>Name</strong></th>
       {
         products.map((product, key) => {
              (product.title)
        }
    </thead>
  </>
  )
 }
}

Thank you in advance for your time!

CodePudding user response:

You're not returning the value correctly for jsx within a map function. Try this:

{
   products.map((product, key) => (
       <th key={key}>
         { product.title }
       </th>
      ))
 }

Using the parenthesis rather than the curly brackets will treat it as a returned expression. Whereas, if you use curly brackets, you'd need to return the expression (jsx) explicitly, like this:

{
   products.map((product, key) => {
      return (
       <th key={key}>
         { product.title }
       </th>
      )
    })
 }

CodePudding user response:

Try this syntax:

 {products.map((product) => (
          <td> {product.title}</td>
        ))}

CodePudding user response:

When you map products here

                    {products.map((product, key) => {
                      (product.title)
                    })}

You are not returning anything in the callback function of map. So you should make it to be

                    {products.map((product, key) => (
                      (product.title)
                    ))}

change { to ( , } to ) so the callback function returning product.title

  • Related