Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

map function not working in React

I am new to React JS, I was testing out some functions in fiddler. I am not sure why I get an error pointing to the map function. I am not able to render the array i defined.

Relevant snippet:

      {this.props.data.productSpecs.map(function(productSpec){
        <b>Category Name:</b> {productSpec};
      })}

Full code:

var productCategory = {
    productName: 'SamamgaTV1',
  productCategory: 'Television', 
  productSpecs: ['32inch','black','hd']
};

var ProductComponent = React.createClass({
  render: function() {
    return( <div>
                        <h2>Product</h2>
              <b>Product Name:</b> {this.props.data.productName}
              <h2>Category</h2>
              <b>Category Name:</b> {this.props.data.productCategory}
              <h2>Specs</h2>
              {this.props.data.productSpecs.map(function(productSpec){
                <b>Category Name:</b> {productSpec};
              })}
           </div>);
  }
});

ReactDOM.render(
  <ProductComponent data={productCategory} />,
  document.getElementById('container')
);
like image 462
eagercoder Avatar asked Oct 12 '16 13:10

eagercoder


People also ask

Why is map not working in React?

TypeError: map() is not a function in React # The "TypeError: map is not a function" occurs when we call the map() method on a value that is not an array. To solve the error, console. log the value you're calling the map() method on and make sure to only call map on valid arrays.

How do I fix type error in React?

The React. js "Uncaught TypeError: X is not a function" occurs when we try to call a value that is not a function as a function, e.g. calling the props object instead of a function. To solve the error, console. log the value you are calling and make sure it is a function.

How do you map objects in React?

To map through an object's value in React:Use the Object. values() method to get an array of the object's values. Call the map() method on the array of values.


1 Answers

First you missed to return, then you must return ONE element. Here you return a <p> and a TextNode

Moreover you need to provide a unique key.

Try with this :

{this.props.data.productSpecs.map(function(productSpec, i){
        return <span key={i}><b>Category Name:</b> {productSpec}</span>;
})}
like image 51
Steeve Pitis Avatar answered Sep 18 '22 01:09

Steeve Pitis