Contenido del Curso
Introduction to React
Introduction to React
Functional Components
As explained in the previous chapter, functional components can render multiple HTML elements in a bunch. As the name expresses, functional components can be defined by defining a JavaScript function with a prop
argument:
Note
PascalCase is like camelCase, but the first letter is always capitalized. It is important to use PascalCase for naming functional components. Otherwise, it might give an error in the console.
The above code is the simplest example of a React component. We can render this component using the syntax:
Hence, if we place it in the render function, it will render the "Hello World!"
heading:
Upon running the app, the resultant page should look something like this:
It is important to note that we can return only one JSX element from a functional component, so doing the following will be wrong and might throw an error:
If we want a component to contain multiple other elements, we can simply return a container element, for example, a <div>
that contains other elements, something like this:
The above examples were simple. Let's try something more complicated:
We have an array of catTypes
that contains 9 strings. We use this array to add/remove elements from the list easily. The Main
component has a heading and an unordered list.
Inside the unordered list, we have the following expression:
The map method uses the catTypes
array and generates an output array where each element is a <li>
element containing a cat type as inner HTML. In this case, the output array should look like this:
This output array is embedded into the <ul>
element using braces {}
. The embedded array is automatically unpacked to create nine distinct <li>
elements inside the <ul>
.
It is equivalent to:
index
index
index
The benefit of using the smaller snippet is that we can easily modify the catTypes
array to add/remove/change elements making the app more dynamic.
Secondly, it's neater and requires less code.
We can also nest components into other components like this:
Note that we can import .css
files using the import
keyword. Similarly, we can also import resources like images using the import
keyword. Here we imported "cat.jpg"
using import cat from "./cat.jpg"
. Later we could reference that image in the Photo
component using the cat
keyword.
¡Gracias por tus comentarios!