React: Show an object with JSX

Turn the data of one product into a small card using JSX expressions.

What to build

A product card that shows the name, the price and whether it is in stock.

Requirements

  • Keep the product object and show, inside a div with the class product: an h2 with the name, a p with the class price showing $ and the price with two decimals, and a p with the class stock showing In stock or Sold out.
  • Use the object's values in braces; do not type the name or the price into the JSX.

Constraints

Only the App component and the product object.

Example

For the product given, the card shows "Desk lamp", "$24.50" and "In stock".

Why it works

Braces read the values from the object, so changing the data changes the card, and toFixed(2) always shows the cents.

Hints

Hint 1

Use braces: {product.name}, and toFixed(2) for the price.

Hint 2

A conditional operator chooses between "In stock" and "Sold out".

Solution

Show one correct solution (try it yourself first)
const product = { name: "Desk lamp", price: 24.5, inStock: true };

export default function App() {
  return (
    <div className="product">
      <h2>{product.name}</h2>
      <p className="price">${product.price.toFixed(2)}</p>
      <p className="stock">{product.inStock ? "In stock" : "Sold out"}</p>
    </div>
  );
}

Lesson: JSX: HTML inside JavaScript →