Home > OS >  get special labels in a ajax request
get special labels in a ajax request

Time:10-13

I'm making an AJAX request and I get my object correctly; but there's a problem with some labels, these labels have "-" (sales-price i.e.). So when I want to print in the screen I can't call them properly in my JSX code

render(){
    return(
            <div>{
                this.state.products.map((products)=>{
                    return  <div>
                                <p>{productt.id}</p>
                                <p>{productt.name}</p>
                                <p>{productt.sales-price}</p>
                            </div>
                })
            }</div>
            }
        );
}

If anyone wants to learn more about the object there's some links that could help: JSON example
Documentation about the API I'm using

CodePudding user response:

You are mapping over an array. The first argument for the map callback is the current element (object) of the array you're iterating over, so ideally it should be product (singular) rather than products (plural). And then you need to access the properties of that object.

If you're returning multiple lines of JSX you should wrap them in parentheses.

Finally, objects which have hyphenate property names need special consideration. You should use bracket notation to access the values.

this.state.products.map(product => {
  return (
    <div>
      <p>{product.id}</p>
      <p>{product.name}</p>
      <p>{product['sales-price']}</p>
    </div>
  );
});

CodePudding user response:

Try {product['sales-price']} instead of {product.sales-price}

render() {
    return (
        <div>
        {
            this.state.products.map((product) => (
                <div>
                     <p>{product.id}</p>
                     <p>{product.name}</p>
                     <p>{product['sales-price']}</p>
                </div>
            ))
        }
        </div>
    );
}

More about objects

  • Related