LU01a - Creating a component

Define the function

With function Product() { } you define a JavaScript function with the name Product. This is also going to be our components name

function Product() {
 
}

Return markup

Each component must return a value. We create a return() using JSX markup. This is a special markup language made for React that allows HTML to be written in JS as well.

function Product() {
  return (
    <div>
      <img src="https://placehold.it/800" alt="Product Image" />
      <h2>Product Name</h2>
      <p>Product Description</p>
      <p>$20</p>
    </div>
  );
}

Export the component

Now we have a component. But if we want to use it in other files, we need to export the function. To export a component, you need to add the keywords „export default“ before the function declaration. This will mark the function to be exported. Now you can include the file in another file to use this component.

Product.js

export default function Product() {
  return (
    <div>
      <img src="https://placehold.it/800" alt="Product Image" />
    </div>
  );
}

ProductsList.js

import Product from './Product.js';
 
export default function ProductsList() {
  return (
    <div>
      <h1>Our Products</h1>
      <Product />
      <Product />
      <Product />
      <Product />
    </div>
  );
}