modul:ffit:react:learningunits:lu01:defining-a-component

Dies ist eine alte Version des Dokuments!


LU01a - Creating a component

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

function Product() {
 
}

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" />
    </div>
  );
}

Now we have a component. But if we want to use it in other files, we have to export the function. To export a component, you have to add the keywords „export default“ in front of the function declaration. That way, the function is marked to be exported. Now, you can include the file in an 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>
  );
}
  • modul/ffit/react/learningunits/lu01/defining-a-component.1733378833.txt.gz
  • Zuletzt geändert: 2024/12/05 07:07
  • von kdemirci