50+ HOURS REACT.JS 19 MONSTER CLASS
0:00
Así que antes de sumergirnos en el curso, primero quiero mencionar algunas cosas.
So before we dive into the course, first of all, I want to mention a few things.
0:03
No puedo hacer promesas, pero puedo decir con confianza que este curso te dará un trabajo.
I can't make any promises, but I can confidently say that this course will give you a job.
0:09
Y lo que puedo prometer es que este curso te llevará de cero a un experto en React, un monstruo de React.
And what I can promise is that this course will take you from zero to a React expert, a React monster.
0:17
Eso definitivamente puedo prometerte. Ahora podrías preguntarte por qué estoy tan seguro de esto. Y la respuesta es simple.
That I can definitely give you a promise. Now you might be wondering why I'm so sure about this. And the answer is simple.
0:24
Comencé a aprender ReactJS en 2018 y empecé a enseñarlo en 2001.
I began learning ReactJS in 2018 and started teaching it in 2001.
0:29
Subí mi primer curso de ReactJS a mi canal de YouTube hace dos años o casi dos años.
I uploaded my first ReactJS course on my YouTube channel two years ago or almost two years ago.
0:35
Y desde entonces, he adquirido una amplia experiencia construyendo numerosos proyectos y trabajando con diferentes empresas.
And since then, I gained extensive experience by building numerous projects and working with different companies.
0:42
Ahora estoy ansioso por ofrecerte un trabajo. Ahora sé que hay muchas cosas que acabo de decir.
Now I'm eager to lend you a job. Now I know there's a lot of things that I just said.
0:47
Ahora la verdadera pregunta es qué puedes esperar de este curso. En este curso, vas a aprender mucho.
Now the real question is what you can expect from this course. In this course, you are going to be learning a lot.
0:54
Y quiero decir muchas cosas. Así que ahora déjame explicarlas todas una por una de un solo aliento.
And I mean a lot of things. So now let me explain all of them one by one in one breath.
0:59
Primero que nada, comenzaremos desde los Fundamentos de React construyendo 10 proyectos y innumerables ejercicios.
First of all, we are going to be starting from the React Fundamental by building 10 projects and countless exercises.
1:05
Luego saltaremos a React con TypeScript construyendo 5 proyectos y innumerables ejercicios.
Then we will jump to React with TypeScript by building 5 projects and countless exercises.
1:09
Luego, el formulario de React con un proyecto, DES UI, Shades and UI, Redix UI, Talvin CSS, Simple Hooks, Advanced Hooks.
Then React hook form with one project, DES UI, Shades and UI, Redix UI, Talvin CSS, Simple Hooks, Advanced Hooks.
1:17
Aprenderás todo sobre Zeus 10 construyendo 10 proyectos. cada
Learn everything about Zeus 10 by building 10 projects. every
1:20
cosa que sé sobre el marco de movimiento y también sobre la animación
single thing i know about the frame of motion and also animation
1:24
en general construyendo 10 proyectos 10 stack
in general by building 10 projects 10 stack
1:27
consulta 10 stack router y también si no saben
query 10 stack router and also if you guys don't know
1:30
el marco de 10 stack que se lanzó hace tres días
the 10 stack framework which was just launched three days
1:33
y aprenderás todo eso construyendo 10 proyectos más, luego
ago and you will learn all of that by building 10 more projects then
1:37
vamos a saltar a las partes avanzadas como patrones de diseño
we are going to be jumping into the advanced parts like design patterns
1:40
en el sistema de diseño de react js, pruebas de react, redx toolkit con dos proyectos de pila completa, next js desde el principio hasta
in react js design system in react js react testing redx toolkit with two full stack projects next js from beginning to
1:48
nivel avanzado de react native con proyectos y también vamos
advanced level react native with projects and also we
1:51
a construir proyectos avanzados, está bien que
are going to be building advanced projects okay that
1:54
fue muchas cosas que acabo de explicar, voy a desglosarlas
was a lot of things that i just explained i'm going to break
1:57
una por una en unos segundos, pero sí, esto es lo que
them down one by one in a few seconds but yeah this is what
2:00
puedes esperar de este curso y este curso todavía está en construcción
you can expect from this course and this course is still in the construction
2:04
estás viendo solo la primera parte de este curso y que trata sobre casi 11 o 12 horas de contenido, así que estás viendo la primera parte de este curso y en la próxima serie.
you are watching only the first part of this course and which is about like almost uh 11 or 12 hour of content so you are watching the first part of this course and in the upcoming series.
2:15
vamos a cubrir el resto de estos temas que acabo de mencionar. Así que sí, estoy muy emocionado y espero que tú también lo estés.
We're going to be covering the rest of these topics which I just mentioned. So yeah, I'm super excited and I hope you are too.
2:22
ahora finalmente, quiero hablar sobre una cosa final y prometo que luego saltaremos al curso.
Now finally, I want to talk about one final thing and I promise then we will jump to the course.
2:27
he mencionado esto en mis cursos anteriores, en mi curso de React Native y también en mi curso de Estructura de Datos y Algoritmos, que si no quieres suscribirte a mi canal de YouTube, no tienes que hacerlo.
I've mentioned this in my previous courses, in my React Native course and also in my Data Structure and Algorithm course, that if you don't want to subscribe to my YouTube channel, you don't have to.
2:36
si no quieres enviarme dinero, no tienes que hacerlo. Si no quieres seguirme en Instagram
If you don't want to send me money, you don't have to. If you don't want to follow me on Instagram
2:40
o en x o twitter, como quieras llamarlo, ni siquiera tienes que
or in x or twitter whatever you want to call that you don't even have
2:44
seguirme en ningún lugar, no tienes que hacer nada por
to follow me anywhere you don't have to do nothing for
2:47
mí, pero ahora si estás sacando algún provecho de mi curso, por favor
me but now if you are taking some advantage from my course please
2:50
no descargues mis cursos si no quieres seguirme aquí
do not download my courses if you don't want to follow me here
2:53
y ahí puedo entender totalmente por qué, pero si tú
and there i can totally understand like why but if you
2:56
estás viendo mis cursos y estás haciendo una carrera de ahí y
are watching my courses and you are making a career out of there and
3:00
aún así, si estás descargando mis cursos, eso no es justo, como yo
still if you are downloading my courses that's not fair like i
3:03
no puedo hacer nada al respecto porque YouTube no tiene la función de descarga, pero sí, si estás viendo mi contenido, por favor no
can't do anything about that because youtube doesn't have the download feature but yeah like if you are watching my content please do not
3:10
descargues eso, así que sí, vamos a entrar en el curso y voy a
download that so yeah let's get into the course and i'm going
3:13
hacerte un monstruo de React, así que ahora hablemos sobre cuáles son
to make you a react monster so now let's talk about what are
3:16
las cosas que tienes que saber antes de saltar a este curso, así que
the things that you have to know before jumping into this course so
3:19
solo necesitas saber HTML y CSS, esto puede
you only need to know html and css this can
3:22
ser los requisitos principales para este curso, no tienes que saber
be the main prerequisites for this course you don't have to know
3:26
SAS y este es opcional, pero yo
sas and this one is optional but i
3:29
te recomendaría encarecidamente que aprendas Tailwind CSS porque en este curso
will highly recommend you to learn tailwind css because in this course
3:32
vas a construir muchos proyectos y para el estilo vamos a
you're going to be building a lot of projects and for the styling we're
3:35
usar Tailwind CSS, así que este es opcional, pero
going to be using tailwind css so this one is optional but
3:38
sí, una vez más, mi recomendación será aprender eso y también tienes que saber JavaScript, pero en este curso definitivamente puedes omitir la
yeah once again my recommendation will be to learn there and also you have to know javascript but in this course you can definitely skip the
3:47
parte de OOP, no tienes que saber qué es OOP para tomar
oop part you don't have to know what a oop is to take
3:50
este curso que estás viendo ahora mismo y si tú
this course which you are currently watching right now and if you
3:53
chicos ya vieron mi viejo
guys already saw my old
3:56
curso de react.js donde en el mundo está eso, está bien déjame buscarlo, ahí vamos, si ustedes se preguntan si deberían ver esto
react.js course where in the world is that okay let me just search for it there we go if you guys are wondering like should i have to watch this
4:04
curso antes de saltar a este curso de react.js, el video que estás
course before jumping into this react.js course the video which you are
4:07
viendo ahora mismo no tienes
currently watching right now you don't have
4:10
que ver este video y aunque voy a poner este video en privado
to watch this video and even though i'm going to private this video
4:13
y ah maldita sea, tú también
and ah god damn it you also
4:16
tienes que saber typescript, olvidé este, también tienes que
have to know typescript i forgot this one you also
4:19
saber este typescript y ahora déjame decir eso una vez más, html y
have to know this typescript and now let me just say that once again html and
4:22
css, incluso css, javascript y typescript, así que eso es lo único que tienes que saber para ver este curso, así que ahora vamos a entrar en la codificación, así que qué
css tenven css javascript and typescript so that's the only thing that you have to know for watching this course so now let's get into the coding so what
4:31
es react.js, react es una biblioteca de javascript gratuita y de código abierto
is react.js react is a free and open source javascript
4:34
especialmente diseñada para construir interfaces de usuario
library specially designed for building the user interfaces
4:37
ahora hay algunas palabras clave en esta definición, déjame
now there are a few buzzwords in this definition let
4:41
aclarar eso para ti, así que la primera que tenemos es de código abierto
me clarify that for you so the first one we have is an open
4:44
así que, ¿qué es el código abierto? El código abierto se refiere
source so what is the open source open source refers
4:47
al tipo de software o básicamente cualquier cosa donde
to the type of software or basically anything where
4:51
el código fuente se pone a disposición del público, esto significa que cualquiera puede ver, modificar y distribuir el código de esa cosa específica y en nuestro caso, ahora, ¿qué es una biblioteca?
the source code is made available to the public this means that anyone can view modify and distribute the code of that specific thing and in our case in Now, Now what is a library?
5:01
Una biblioteca es una colección de código preescrito que un desarrollador puede usar para realizar una tarea común o agregar una funcionalidad específica a sus aplicaciones.
Library is a collection of pre-written code that developer can use to perform a common task or add a specific functionality to their applications.
5:10
Ahora, ¿qué es una UI? La UI o interfaz de usuario es el medio a través del cual el usuario interactúa con nuestra aplicación.
Now what is a UI? UI or the user interface is the means through which the user interacts with our application.
5:16
React.js fue creado en 2011. Usa algo llamado el modelo de componentes, que discutiremos con más detalle en este curso, pero no ahora.
React.js was created in 2011. It uses something called the component model, which we will discuss more in detail in this course but not right now.
5:24
Nos permite construir aplicaciones modulares y, finalmente, hay un dicho sobre react.js que dice que lo aprendes una vez y lo escribes en cualquier lugar.
It allows us to build modular apps and finally there is a saying about react.js that learn it once and write it anywhere.
5:31
Así que ahora déjame desglosar todos ellos uno por uno. React es la biblioteca de front-end más popular y poderosa desarrollada y patrocinada por Facebook.
So now let me break all of them one by one. React is the most popular powerful front-end library developed and sponsored by Facebook.
5:37
Un componente es solo una parte de la UI que tiene su propia lógica y apariencia.
A component is just a piece of the UI that has its own logic and appearance.
5:42
Un componente puede ser tan pequeño como un botón o tan grande como una aplicación entera.
A component can be small as a button or large as an entire application.
5:46
Discutiremos más sobre los componentes en más detalle más adelante en este curso, pero no ahora.
We will discuss more about components in more great detail later in this course but not right now.
5:50
si aprendes react.js una vez, no solo podrás construir
if you learn react.js once you will not only be able to build
5:53
solo los sitios web, sino que también puedes construir la aplicación móvil
only the websites but you can also build the mobile application
5:57
de escritorio y también incluso la realidad virtual y hay
desktop and also even the virtual reality and there
6:00
muchas más cosas que puedes hacer con react.js, así que
are a lot more things that you can do with react.js so
6:03
solo tienes que aprenderlo una vez y escribirlo en cualquier lugar para que
you just have to learn it once and write it anywhere so that
6:06
eso fue solo una rápida introducción a react.js y ahora déjame hacer una configuración para
was just a quick intro to react.js and now let me make a setup for
6:09
nuestro viaje de codificación en este curso, usaremos un vs code para
our coding journey in this course we'll be using a vs code for
6:12
escribir código de trabajo y eres más que bienvenido a usar cualquier editor de texto
writing work code and you're more than welcome to use any text editor
6:16
que prefieras, puedes usar sublime text, puedes usar productos de Japón
that you prefer you can use sublime text you can use japan products
6:19
puedes usar cualquier cosa que prefieras, pero en mi caso voy a usar
you can use anything that you prefer but in my case i'm going to be using
6:22
un vs code para escribir mi código. Ahora, para instalar react js
a vs code for writing my code now to install react js
6:25
primero necesitaremos abrir nuestra terminal, después de eso tenemos que
first we will need to open our terminal after that we have to
6:28
escribir este comando npm create wheat at
type this command npm create wheat at
6:31
último, presiona enter. A continuación, tenemos que proporcionar algún tipo
latest hit enter next we have to provide some sort
6:35
de nombre para nuestro proyecto, lo llamaré react demos
of a name for our project i'll call mine as react demos
6:38
puedes llamarlo como quieras. A continuación, tenemos que
you can call it like anything that you want next we have
6:41
seleccionar el marco, elegiré react js porque ahora estamos aprendiendo
to select the framework i'll choose react js because we are now learning
6:44
react js y sí, solo voy a elegir react js
react js and yeah i'm gonna just choose react js
6:47
a continuación, tenemos que seleccionar la variante, por ahora solo voy a
next we have to select the variant for now i'll just
6:50
usar javascript porque sé que hay muchas personas
use javascript because i know there are a lot of people
6:54
que están viendo este curso y no tienen conocimiento de typescripts
who are watching this course they don't have the knowledge of typescripts
6:57
así que si eres alguien que ya sabe qué es un typescript, no
so if you are someone who already know what a typescript is you
7:00
tienes que preocuparte por eso, como si todavía vamos a usar un typescript en
don't have to worry about that like we're going to be still using a typescript in
7:03
este curso, pero no ahora, así que sí, voy
this course but not right now so yeah i'm
7:06
a elegir javascript por ahora, pero más tarde vamos a usar un typescript en este curso. Ahora tenemos que entrar en esa carpeta usando un comando cd o puedes decir el comando del directorio actual.
going to just choose javascript for now but later we are going to be using a typescript in this course now we have to go inside that folder by using a cd command or you can say the current directory command
7:17
ahora voy a usar el código punto y presionar enter para que se abra eso
now i'm going to use the code dot and hit enter so it's going to open that
7:20
en mi vs code ahora quiero que abras tu terminal integrada
in my vs code now i want you to open your integrated terminal
7:23
dentro de tu vs code y solo escribe este comando así
inside your vs code and just type this command so
7:26
puedes usar npm i o puedes usar npm install
you can either use npm i or you can use npm install
7:29
si así lo deseas, así que ambos funcionarán perfectamente bien, así que es
if you wanted to so both of them will work totally fine so it's
7:33
va a instalar todos los paquetes de los cuales depende react.js
going to install all of the packages by which or react.js is depends
7:36
así que va a tomar un poco de tiempo, voy a adelantar el video ahora
on so it's going to take a bit of time i'm going to fast forward the video right
7:39
ahora hablemos de estos archivos y carpetas, así que la primera carpeta
now let's discuss these files and folders so the first folder
7:42
que tenemos es una carpeta de módulos de nodo y esta carpeta tiene
that we have is a node modules folder and this folder has
7:45
todos los módulos y paquetes de los cuales depende nuestro react.js
all of the module and packages by which our react.js
7:48
y más tarde en este curso, si instalamos algún
is depends on and later in this course if we install any
7:51
paquete de terceros que también se incluirá en esta carpeta
third-party packages that will be also included in this folder
7:55
así que la siguiente carpeta que tenemos es una carpeta pública y pública
so the next folder that we have is a public folder and public
7:58
es la carpeta donde ponemos todos nuestros archivos de activos como html
is the folder where we put all of our assets file like html
8:01
etcétera, a continuación tenemos una carpeta src y
etc next we have a src folder and
8:04
src o fuente es el corazón de todo nuestro proyecto
src or source is the heart of our entire project
8:07
y vamos a estar pasando casi el 90 por ciento de nuestro tiempo en esta carpeta, así que ahora dentro de esta carpeta src tenemos
and we're going to be spending like almost 90 percent of our time in this folder so now inside this src folder we
8:14
algunos archivos y carpetas más, así que la primera
have a few more files and folder so the first
8:18
que tenemos es la carpeta de activos y como su nombre indica, en esta carpeta
one we have is the assets folder and as the name suggests that in this folder
8:21
vamos a poner todos nuestros archivos y carpetas de activos como
we are going to be putting like all of our assets files and folder like
8:24
imágenes, svgs, íconos externos y así sucesivamente
images svgs external icons and so on and so forth
8:27
a continuación tenemos otros dos archivos como app.css y
next we have two other files like app.css and
8:30
también index.css, así que como su nombre indica, vamos
also index.css so as the name suggests that we
8:34
a escribir nuestro estilo dentro de estos archivos, así que vamos a proporcionar nuestro estilo de interfaz de usuario dentro de estos archivos, a continuación tenemos dos archivos más como f.jsx y también main.jsx.
are going to be writing our style inside these files so we are going to be providing our style forward ui inside these files next we have two more files like f.jsx and also main.jsx.
8:45
Estos son algo llamado archivo de componente que vamos a discutir más adelante en este curso, pero no tienes que preocuparte por eso por ahora.
These are something called the component file which we are going to be discussing later in this course but you don't have to worry about that for now.
8:51
A continuación, tenemos un archivo git ignore y este es un archivo relacionado con github.
Next we have a git ignore file and this is a github related file.
8:55
Cuando estamos subiendo nuestro código a github, este archivo nos permite ignorar un cierto archivo o carpeta.
When we are pushing our code to github this file allows us to ignore a certain file or folder.
8:59
Por ejemplo, esta carpeta de node modules es una carpeta enorme
For example like this node modules folder is a huge folder
9:03
y si no quieres subir eso a nuestro repositorio de github, simplemente vamos a poner el nombre de nuestra carpeta de node modules dentro de este archivo .getignore y va a ignorar eso cada vez que subamos nuestro código a nuestro repositorio de github.
and if you don't want to push that to our github repository so we are going to be just putting the name of our node modules folder inside this .getignore file and it's going to just ignore that whenever we are pushing our code to our github repository.
9:15
A continuación, tenemos nuestro archivo eslin.config.js y este es un archivo de configuración para nuestro eslin.
Next we have our eslin.config.js file and this is a configuration file for our eslin.
9:21
A continuación, tenemos nuestro archivo index.html y este es el archivo más importante porque en este archivo tenemos nuestro contenido html y también tenemos un div con id de root.
Next we have our index.html file and this is the most important file because in this file we have our html content and we also have a div with id of root.
9:31
Nuestro react.js seleccionará este elemento y renderizará todo nuestro contenido
Our react.js will select this element and render all of our content
9:35
a ese div específico como voy a mostrar
to that specific div like i'm going to show
9:38
tú desde donde estamos seleccionando ese div con la clase de root
you from where we are selecting that div with the class of root
9:42
quiero decir, como con el id de root, a continuación tenemos nuestro package.json
i mean like with the id of root next we have our package.json
9:45
archivo y este archivo es el corazón de nuestro proyecto, contiene
file and this file is the heart of our project it contains
9:48
metadatos sobre el proyecto como el nombre del proyecto, versión, descripción
metadata about the project such as like project name version description
9:52
y scripts y más importante, enumera las dependencias y su versión que nuestro proyecto necesita para funcionar, algo que vamos a discutir más adelante en este curso.
and scripts and more importantly it lists the dependencies and their version that our project needs to run okay something which we are going to be discussing later in this course.
10:02
A continuación, tenemos un archivo package log.json. El archivo se genera y actualiza automáticamente cuando se instalan o modifican dependencias.
Next, we have a package log.json file. File is automatically generated and updated when installed or modified dependencies.
10:09
Registra la versión de todos los paquetes y sus dependencias para asegurar un entorno de construcción consistente y reproducible.
It logs the version of all of the packages and their dependencies to ensure a consistent and reproducible build environment.
10:15
Algo de lo que no tienes que preocuparte. Bien, así que a continuación tenemos un archivo simple readme.md y este archivo proporciona un resumen de qué trata nuestro proyecto.
Something which you don't have to worry about. Okay, so next we have a simple readme.md file and this file provides the summary of what our project is about.
10:24
Normalmente incluye información como el propósito del proyecto, características y objetivos que se pretenden lograr sobre este proyecto específico.
It usually includes information like project purpose, feature and aims to accomplish about this specific project.
10:30
También podemos previsualizar eso haciendo clic en este ícono. Y aquí puedes ver cómo se verá nuestra vista previa una vez que subamos nuestro código a nuestro repositorio de GitHub.
We can also preview that by clicking on this icon. And here you can see this is how our preview will look like once we push our code to our GitHub repository.
10:37
A continuación, tenemos nuestro archivo wheat.config.js. Y este archivo se utiliza para proporcionar configuración para el wheat en sí.
Next we have our wheat.config.js file. And this file is used to provide configuration for the wheat itself.
10:44
Así que sí, eso fue mucho sobre los archivos y carpetas. Y ni siquiera tienes que preocuparte por estos archivos y carpetas, para ser honesto.
So yeah, that was a lot about the files and folders. And you don't even have to worry about these files and folders to be honest.
10:50
Y ahora voy a eliminar todas las cosas innecesarias de nuestro proyecto.
And now I'm going to remove all of the unnecessary stuff from our project.
10:53
tiempo para la limpieza, así que por ahora no necesitamos esto
time for the cleanup so for now we don't need this
10:56
carpeta pública, así que voy a seleccionarla y eliminarla a continuación
public folder so i'm going to select that and delete that next
11:00
también no necesitamos esta carpeta de acceso, así que voy a eliminarla de aquí
we also don't need this access folder so i'm going to remove that from here we
11:03
tampoco necesitamos el app.css y también el index.css
also don't need the app.css and also the index.css
11:07
a continuación, tenemos que entrar en este man.jsx
as well next we have to go inside this man.jsx
11:11
y simplemente eliminar esta línea, por supuesto, voy a eliminar el archivo semi y ahora, finalmente, voy a entrar en mi archivo app.jsx, voy a seleccionar cada cosa de este archivo y voy a simplemente eliminar eso de aquí.
and just remove this line of course i'm going to just remove the semi file and now finally i'm going to go into my app.jsx file i'm going to select every single thing from this file and i'm And I'm going to just remove that from here.
11:23
Y a continuación, voy a crear algo llamado un componente. Pero no tienes que preocuparte por lo que es un componente por ahora. Así que solo usaré ese const app.
And next, I'm going to be just creating something called a component. But you don't have to worry about what a component is for now. So I'll just use that const app.
11:30
Y solo usaré mi función add-off. Y devolveré solo h1. O sabes qué? No h1.
And I'll just use my add-off function. And return just h1. Or you know what? Not h1.
11:36
Solo devolveré algo como sección, que dirá algo como hola. Voy a guardar mi archivo.
I'll just return like section, which will say like hello. I'm going to save my file.
11:41
Y ahora, para ejecutar este código, tendré que abrir mi terminal integrada. Y ahora solo usaré mi npm run dev.
And now to run this code, I'm going to have to open my integrated terminal. And now I'll just use my npm run dev.
11:46
Así que va a ejecutar mi código en este puerto justo aquí. Así que voy a copiar eso.
So it's going to run my code on this port right here. So I'm going to copy that.
11:50
o puedes simplemente mantener presionado command o control y hacer clic en
or you can just hold command or control and click on
11:54
eso y estamos obteniendo este error justo aquí, esto porque
that and we are getting this error right here this because we
11:57
ahora hemos creado exitosamente este componente, pero también tenemos que exportar
now successfully created this component but we also have to export
12:00
esto para que podamos usarlo en otros archivos, así que voy a usar algo como export default
this so that we can use it in other files so i'm going to use like export default
12:03
y luego mi app, así que si guardo ahí y ahora
and then my app so if i save there and now
12:06
tendré que refrescar ahí, así que ¿qué estamos obteniendo? Ahora estamos obteniendo nuestro hola justo aquí, lo cual es increíble, así que sí, así es como vamos a eliminar todas sus
i'm going to have to refresh there so what are we getting we are now getting our hello right here which is amazing so yeah this is how we are going to be removing all of their
12:15
cosas innecesarias de nuestro proyecto, así que ¿qué es
unnecessary stuff from our project so what is
12:18
componente? Los componentes son partes independientes y reutilizables
component components are independent and reusable bits
12:21
de código, sirven para el mismo propósito que una función de javascript, pero funcionan de forma aislada y devuelven html o jsx, para ser precisos, así que algo de lo que vamos a discutir muy pronto
of code they serve the same purpose as javascript function but work in isolation and return html or jsx to be precise so something which we're going to be discussing very soon
12:31
triax.js nos permite hacer que nuestro sitio web sea modular utilizando algo llamado separación de preocupaciones
triax.js allows us to make our website modular by using something called the separation of concern
12:37
así que si te pido que construyas esta interfaz de usuario, ¿cómo
so if i ask you to build this ui so how
12:40
puedes hacerlo si vienes de un fondo de html css
can you go about doing that if you're coming from html css
12:43
y javascript? Primero crearás index.html
and javascript background you will first create index.html
12:46
archivo, luego el archivo css, luego el archivo javascript y
file then css file then javascript file and
12:50
en el archivo html pondrás toda tu estructura para este proyecto
in the html file you will put all of your structure for this project
12:53
luego en el archivo css pondrás todo el estilo y
then in the css file you will put all of the styling and
12:56
en el archivo javascript proporcionarás la funcionalidad a esto
in the javascript file you will provide the functionality to it this
13:00
este proceso sigue siendo una separación de preocupaciones, pero en react.js
process is still a separation of concern but in react.js
13:03
podemos hacer eso un poco mejor en react.js, podemos dividir todo este proyecto en múltiples componentes o se puede decir las partes
we can do that a bit more better in react.js we can split this entire project into multiple components or you can say the parts
13:12
Así que se puede decir como componentes o partes. Entonces, si quieres construir este proyecto usando React.js, comenzaremos creando un componente para la barra de navegación.
So you can either say like components or parts. So if you want to build this project by using React.js, we will start by creating a component for the nav bar.
13:20
Y en eso, pondremos nuestro HTML, CSS y JavaScript dentro de su archivo específico.
And in that, we will put our HTML, CSS and JavaScript inside their specific file.
13:26
Luego crearemos otro componente para una barra de búsqueda. A continuación, para el menú y también para el artículo.
Then we will create another component for a search bar. Next for the menu and also for the article.
13:31
Y también, finalmente, crearemos un componente para la tarjeta. Y reutilizaremos esa tarjeta una y otra vez en nuestra interfaz de usuario.
And also finally, we will create a component for the card. And we will reuse that card again and again in our UI.
13:38
Eso fue sobre la teoría. Pero, ¿cómo vamos a crear un componente? Para crear un componente, solo tienes que crear una función de JavaScript.
So that was about the theory. But how are we going to make a component? To create a component, you just have to create a JavaScript function.
13:45
Pero cada vez que estés creando un componente, debes tener en cuenta algunas cosas.
But whenever you are creating a component, you have to keep a few things in mind.
13:49
La primera cosa que debes tener en cuenta es que la primera letra del nombre de tu componente debe ser mayúscula.
The first thing that you have to keep in mind is that the first letter of your component name should be uppercase.
13:54
También puedes crear tu componente usando la palabra reservada de función,
You can also create your component by either using the function reserved keyword,
13:58
o también puedes crear la sintaxis de función de flecha para tu componente.
or you can create your component arrow function syntax as well.
14:02
La última cosa que debes tener en cuenta es que cada vez que trabajes con un componente, debes devolver algún tipo de HTML desde ese componente.
The final thing that you have to keep in mind is that anytime you are working with a component, you have to return some sort of HTML from that component.
14:09
Ahora, para crear un componente, voy a ir a mi archivo app.jsx y
now to create a component i'm going to go into my app.jsx file and
14:12
voy a eliminar cada cosa de allí porque quiero empezar desde cero.
i'm going to remove every single thing from there because i want to start from scratch
14:15
Así que, como dije, los componentes son solo una función de JavaScript.
so as i said that components are just a javascript function
14:19
Así que si solo creo una función de JavaScript usando la palabra reservada de función
so if i just create a javascript function by using either the function reserved
14:22
o también puedo crear mi componente usando la función de flecha, así que por ahora me quedaré con esta función.
keyword or i can also create my component by
14:25
palabra reservada y, por cierto, cada vez que estés creando un componente hay dos cosas que debes tener en cuenta: número uno, la primera letra del nombre debe ser
using the arrow function so for now i'll just stick with this function
14:28
mayúscula y el resto de ellas será en minúscula, así que si quiero darle
reserved keyword and by the way anytime you are creating a component there are two things that you have to keep in mind number one the first letter of the name should be
14:38
mayúscula y el resto de ellas estará en minúscula, así que si quiero dar
uppercase and the rest of them will be in lowercase so if i want to give
14:41
mi componente como el nombre de la aplicación, la primera letra debe ser mayúscula y el resto puede ser como quieras, puedes crear eso en mayúscula o minúscula, eso depende de ti, pero la primera letra debe ser mayúscula
my component as the name of like app the first letter should be uppercase and the rest of them can be like anything you can create that as uppercase or lowercase that's totally on you but the first letter should be uppercase
14:53
voy a darle el nombre de la aplicación y lo siguiente que tienes
i'm going to just give it the name of like app and the next thing that you have
14:56
que tener en cuenta es que desde el componente siempre
to keep in mind is that from the component you always
14:59
como siempre tienes que devolver algún tipo de gsx
like always have to return some sort of a gsx
15:03
no discutimos sobre gsx, no ahora, pero
we did not discuss about gsx not right now but
15:06
lo haremos muy pronto, así que voy a escribir mi h1 aquí mismo y
we will very soon so i'm going to just write my h1 right here and
15:09
escribiré como hola mundo así que ahora si guardo
i'll just write like hello world so now if i save
15:12
mi archivo así es como vamos a crear nuestro componente pero ahora tenemos que decirle a nuestro react js que ahora hemos creado este componente con éxito queremos renderizar eso en nuestra interfaz de usuario
my file this is how we are going to be creating our component but now we have to tell our react js that now we successfully created this component we want to render that to our ui
15:22
así que para renderizar eso hacia la interfaz de usuario primero que nada tenemos que exportar allí para
so to render that toward ui first of all we have to export there so
15:25
que podamos usar eso en otros lugares de nuestro proyecto así que solo voy a usar
that we can use that in other places of our project so i'm going to just use
15:28
como exportar por defecto y luego agregar así que tan pronto
like export default and then add so as soon
15:31
como haga eso y guarde mi archivo ahora voy a abrir mi terminal
as i do that and save my file now i'm going to open my terminal
15:34
aquí voy a usar mi npm run dev y aquí
right here i'm going to just use my npm run dev and here
15:37
puedes ver que ahora estamos obteniendo lo que hola mundo aquí de nuestro componente así que
you can see we are now getting what hello world right here from our component so
15:41
qué está pasando así que ahora estamos creando nuestro componente con éxito y ahora lo estamos exportando allí para que podamos usar este componente en otra parte de nuestro proyecto así que donde estamos usando ese componente.
what's going on so now we are successfully creating our component and now we are exporting there so that we can use this component in other part of our project so where we are using that component.
15:51
Así que si voy a mi archivo main.jsx aquí, así que aquí puedes ver que ahora estamos renderizando este componente aquí.
So if I go into my main.jsx file right here, so here you can see we are now rendering this component right here.
15:58
Así que primero que nada, ahora estamos importando este componente, que acabamos de crear aquí dentro de este archivo app.jsx.
So first of all, we are now importing this component, which we just created right here inside this app.jsx file.
16:04
Y ahora lo estamos exportando allí. Y aquí dentro de este archivo main.jsx, ahora estamos importando este componente.
And now we are exporting there. And here inside this main.jsx file, we are now importing this component.
16:10
Y ahora lo estamos renderizando en lo que es la interfaz de usuario. Y como dije anteriormente, quiero que tengas en cuenta esta raíz.
And we are now rendering there to what UI. And as I said previously, then I want you to keep in mind this root.
16:17
Ahora estamos seleccionando esa raíz aquí usando
Now we are selecting that root right here by using
16:20
document.getElementById y ahora estamos seleccionando
document.getElementById and we are now selecting
16:23
esa raíz que está dentro de este index.html
that root which is inside this index.html
16:27
archivo como puedes ver aquí ahora estamos seleccionando esa raíz
file as you can see right here now we are selecting that root
16:30
así que aquí puedes ver que tenemos un id de raíz y ahora estamos seleccionando
so here you can see we have a root id and we are now selecting
16:33
ahí usando document.getElementById correcto
there by using document.getElementById right
16:36
aquí y ahora dentro de esa raíz como esta raíz estamos
here and now inside that root like this root we
16:40
ahora renderizando nuestro componente de aplicación aquí así que esa es la única razón por la que ahora estamos obteniendo este hola mundo aquí así que si cambio algo dentro de ese componente como si entro allí y ahora voy a cambiar eso a como mi propio nombre tal vez
are now rendering our app component right here so that's the only reason we're now getting this hello world right here so if I change something inside that component like if i go into there and now i'm going to just change that to like my own name maybe
16:52
y si guardo la entrada puedes ver que ahora estoy obteniendo mi propio nombre así que
and if i save the entry you can see i'm now getting my own name so
16:55
sí, así es como vamos a crear un componente y déjame decir eso
yeah this is how we are going to be creating a component and let me just say that
16:58
una vez más cada vez que quieras crear tu componente la primera letra
once again anytime you want to create your component the first letter
17:01
será mayúscula y el resto puede ser ya sea mayúscula
will be uppercase and the rest of them can be either uppercase
17:04
o minúsculas o eso depende solo de ti y también
or lowercase or that's only on you and also
17:07
tenemos que devolver algo de html desde esta función, está bien, así que también podemos refactorizar este código para usar la función de flecha, así que solo usaré como const y voy a convertir esta función para usar la función de flecha.
we have to return some html from this function okay so we can also refactor this code to use the arrow function so i'll just use like const and i'm going to just convert this function to use the arrow function.
17:19
Si prefieres de esta manera, también puedes crear tu componente utilizando esta sintaxis de flecha o eres más que bienvenido a usar esta palabra clave de resultado de función aquí.
If you prefer this way, you can also create your component by using this arrow syntax or you are more than welcome to use this function result keyword right here.
17:28
Así que sí, así es como vamos a trabajar con componentes. Bienvenido al primer desafío de este curso.
So yeah, this is how we are going to be working with components. Welcome to the first challenge of this course.
17:33
Así que aquí está la interfaz de usuario y quiero que dividas esta interfaz de usuario en múltiples componentes. No tienes que escribir ningún código para eso.
So here is the UI and I want you to split this UI into multiple components. You don't have to write any code for that.
17:40
Solo consigue un bolígrafo y papel si los tienes allí, pero si
Just get a pen and paper if you have there but if you
17:43
no tienes un bolígrafo y papel, también puedes usar algún tipo de software de edición portátil
don't have a pen and paper you can also use some sort of a porto editing software
17:46
que te permitirá marcar algunas cosas dentro
which will allow you to just mark a few things inside
17:49
de esta interfaz de usuario y hacerlas como un componente separado y
this ui and make them as a separate component and
17:52
sí, también tenemos otra parte de este desafío que vamos a ver
yeah we also have another part of this challenge which we are going to be seeing
17:55
en unos segundos, pero quiero que vayas y pauses el video y
in a few seconds but i want you to go ahead and pause the video and
17:59
hagas este desafío por ti mismo, así que si puedes hacerlo, vuelve y
do this challenge by yourself so if you can do it then come back and
18:02
mira la solución y ahora te voy a dar mi solución, así que voy a usar Figma para eso y si quieres usar algún otro software de edición portátil, puedes
watch the solution and now i'm going to give you my solution so i'm going to use a figma for that and if you want to use some sort of other porto editing software you
18:09
ser más que bienvenido a hacerlo, así que lo primero que quiero hacer es que
are more than welcome to do that so the first thing that i want to do is that
18:12
quiero crear un componente para este menú hamburguesa
i want to create a component for this burger menu
18:15
así que voy a crear un componente separado y voy a poner como toda
so i'm going to just create a separate component and i'm going to put like all
18:18
la estructura, el estilo y también la funcionalidad dentro de ese componente y
of the structure the styling and also the functionality inside that component and
18:23
luego también crearé un componente para la navegación
then i will also create a component for the navigation
18:26
así que solo crearé una navegación, ¿verdad?
so i'll just create a navigation right
18:29
aquí y disculpa mi dibujo y también mi cama, eh sí, entiendes la idea, así que así es como estamos
here and excuse my drawing and also my bed uh yeah you get the idea so this is how we are
18:37
creando un componente para la navegación, también podemos dividir
going to be creating a component for the navigation we can also split
18:40
toda esta navegación en múltiples componentes, pero
this entire navigation into multiple components but
18:43
no tenemos que hacerlo, así que esto será suficiente para este componente de navegación
we don't have to like this is going to be enough for this navigation component
18:46
pondremos nuestro logo dentro de ahí
we will put our logo inside there we
18:50
también pondremos nuestro campo de búsqueda que nos permitirá buscar nuestro
will also put our search field which will allow us to search our
18:53
también pondremos nuestro campo de búsqueda que nos permitirá buscar nuestro
stuff inside this wikipedia and finally
18:56
material dentro de esta wikipedia y finalmente
we are going to be also providing our create account and also the login and we also have these three dots and i don't have any idea
19:02
vamos a estar proporcionando nuestra creación de cuenta y también el inicio de sesión y también tenemos estos tres puntos y no tengo idea
what the hell these three dots do okay so that's going to be my
19:06
qué demonios hacen estos tres puntos, así que eso va a ser mi
second component next we are going to be also creating a
19:09
segundo componente, a continuación vamos a estar creando un
component for the banner in some situation we would want to show
19:12
componente para el banner en alguna situación quisiéramos mostrar
this banner and in a lot of times we are not going to be showing this banner
19:15
este banner y muchas veces no vamos a mostrar este banner
so yeah this is going to be basically my primary component
19:18
así que sí, este va a ser básicamente mi componente principal
and there is a big difference between like a huge
19:21
y hay una gran diferencia entre un componente enorme
component and a small component which we are going to be seeing inside
19:25
y un componente pequeño que vamos a ver dentro
this course but not right now so this is going to be my third component for the banner okay and also we are going to be creating a
19:32
de este curso pero no ahora mismo, así que este va a ser mi tercer componente para el banner, está bien, y también vamos a estar creando un
component for the sidebar or you can just give it the name of like
19:35
componente para la barra lateral o simplemente puedes darle el nombre de
aside if you wanted to but I'm gonna give it the name of like sidebar
19:38
aside si quieres, pero le voy a dar el nombre de barra lateral
and I guess that's gonna be fine okay and also
19:42
y supongo que eso estará bien, está bien, y también
we're going to be creating a component for the appearance so
19:45
vamos a estar creando un componente para la apariencia, así que
I'm gonna also mark there as a separate component okay
19:48
también voy a marcar eso como un componente separado, está bien
so we can also split this entire UI into like nested component as well we can also create a separate component for these radio button if you wanted to but we don't have to do
20:00
y también vamos a crear un componente para el encabezado
and also we are going to be creating a component for the header
20:03
así que ahora déjame resaltar eso justo aquí
so now let me just highlight that right here just
20:08
así que esto
like that so this
20:11
va a ser básicamente nuestro encabezado y finalmente vamos a crear un componente
is going to be basically our header and finally we are going to be creating a component
20:14
para nuestro contenido principal así que esto va a ser básicamente nuestro
for our main content so this is going to be basically our
20:17
gran componente que nos permite renderizar todo
huge component which allows us to render all
20:21
ese contenido justo aquí dentro de esta Wikipedia, está bien, como una vez más no tenemos que crear un componente
of that content right here inside this Wikipedia, okay, like once again we don't have to create a component
20:28
para todo eso, podemos poner toda esa lógica entera en un componente si quisieras, pero eso es
for all of that we can put all of that entire
20:31
logic into one component if you wanted to but that's
20:34
no va a ser la forma ideal de crear nuestro sitio web o nuestras aplicaciones así que
not going to be the ideal way to create our website or our apps so
20:37
por eso vamos a dividir toda esta interfaz en múltiples
that's why we are going to be splitting this entire ui into multiple
20:41
componentes así que sí, esa fue la parte uno
components so yeah that was the part one
20:44
de nuestro desafío uno, a continuación tenemos que crear un nuevo archivo llamado
of our challenge one next we have to create a new file called
20:47
grid.jsx y dentro de ese archivo vamos a crear nuestro componente de cuadrícula utilizando la sintaxis de decoración de funciones, después de eso vamos
grid.jsx and inside that file we are going to be creating our grid component by using the function decoration syntax after that we are going
20:54
a refactorizar ese código para usar la función de flecha en su lugar
to be refactoring that code to use the arrow function instead
20:58
y finalmente solo tenemos que renderizar eso en nuestro componente de aplicación así que
and finally we just have to render that into our app component so
21:01
una vez más, da lo mejor de ti, si puedes hacerlo, eso es completamente
once again give it your best shot if you can do it that's completely
21:04
bien, entonces regresa y mira la solución y ahora te voy a dar mi solución así que
okay then come back and watch the solution and now i'm going to give you my solution so
21:08
lo que voy a hacer es crear una carpeta de componentes y
what i'm going to do is that i'm going to create a components folder and
21:11
le voy a dar el nombre de grid.dot tsx para
i'm going to give the name of like grid dot not tsx for
21:14
jnsx y voy a usar mi rafc así que nos va a dar todo ese código, pero no voy a hacer eso, solo crearé una función y ahora voy a dar
jnsx and i'm going to use my rafc so it's going to give us all of that code but i'm not going to do that i'll just create a function and now i'm going to give
21:23
el nombre de grid, no va a tomar ningún parámetro así que voy a eliminar
the name of like grid it's not going to take any parameters so i'm going to remove
21:26
ellos y finalmente solo tenemos que devolver qué h1 y
them and finally we only have to return what h1 and
21:29
que simplemente dirá grid o hola, qué encontraríamos
which will just say like grid or hello what would
21:32
así que voy a guardar mi archivo, ahora tenemos que exportar este componente
we find so i'm going to save my file now we have to export this component
21:36
para que podamos usarlo en otros archivos, así que voy a usar export default
so that we can use that in other files so i'm going to be using like export default
21:39
de grid, así que ahora voy a guardar mi archivo, déjame ir a
of grid so now i'm going to save my file let me go into
21:42
mi componente app.jsx y vamos a registrar ese componente aquí mismo, así que si guardo mi archivo y aquí puedes ver que ahora estamos obteniendo qué hola mundo aquí, lo cual se ve increíble
my app.jsx component and let's just register that component right here okay so if i save my file and here you can see we are now getting what hello world right here which is looking amazing
21:53
pero voy a entrar y refactorizar este código para usar la
but i'm going to go in there and refactor this code to use the arrow
21:56
función de flecha, así que voy a eliminar eso y cambiarlo a const y
function so i'm going to remove that and change that to const and
21:59
también hacer eso como una función de flecha, así que ahora si guardo mi archivo y
also make that as an arrow function so now if i save my file and
22:03
aún estamos obteniendo ese mismo resultado que dice hola mundo
still we are getting that same result which is saying hello world
22:06
así que sí, ese fue nuestro primer desafío en este curso, generalmente creamos una carpeta de componentes separada y ponemos nuestros componentes dentro de allí, así que voy a crear solo dos componentes con el nombre de greet
okay so yeah that was our first challenge in this course we usually create a separate components folder and we put our components inside there so i'm going to just create two components with the name of like greet
22:18
o greeting.jsx y también add.jsx y por cierto, puedes darle cualquier nombre que prefieras y ahora voy a crear mi componente greet aquí mismo
or greeting.jsx and also add.jsx and by the way you can give it any name that you prefer and now i'm going to just create my greet component right here
22:30
y solo devolveré mi h1 que dirá uh
and i'll just return my h1 which will say uh
22:34
hola o sí, hola estaría bien, voy a guardar
hello or yeah hello would be fine i'm going to save
22:37
mi archivo y ahora te voy a mostrar una extensión que te ayudará mucho, así que quiero que vayas a tu área de extensiones y busques react.js y una vez que lo hagas, aquí puedes ver que quiero que instales esta extensión en tu VS Code.
my file and now i'm going to show you extension which will help you a lot so i want you to go into your extension area and just search for react.js and once you do here you can see i I want you to install this extension in your VS Code.
22:49
Solo instala esta extensión y te dará muchos fragmentos. Bien, a lo largo del curso te mostraré muchos fragmentos que puedes usar.
Just install this extension and it's going to give you a lot of snippets. Okay, so throughout the course I'm going to show you a lot of snippets which you can use.
22:56
Pero por cierto, si quieres usar eso, tienes que instalarlo en tu VS Code. Así que este componente tomó mucho tiempo en escribirse.
But by the way, if you want to use that, so you have to install that in your VS Code. So this component took a lot of time to write.
23:02
Ahora en este componente, solo voy a usar RAFCE.
Now in this component, I'm going to just use RAFCE.
23:06
Bien, así que solo tienes que escribir ahí y una vez que presiones enter, aquí puedes ver que te dará todo el boilerplate de nuestro componente.
Okay, so you just have to write there and once you hit enter, so here you can see it's going to give us the entire boilerplate of our component.
23:13
Déjame mostrarte eso una vez más. Solo tienes que
Let me just show you there once again. you just have to
23:16
escribir rafce y presionar tab o presionar
write rafce and hit either tab or hit
23:19
enter, te dará todo ese componente aquí mismo, así que si yo
enter it's going to give us that entire component right here so if i
23:22
guardo mi archivo ahora que hemos creado con éxito lo que añade
save my file now that we successfully created what add
23:26
componente y también nuestro componente de cuadrícula y por cierto
component and also our grid component and by the way
23:29
también tenemos que exportar eso para que podamos usarlo en otros archivos, así que tenemos
we also have to export that so that we can use in other files so we have
23:32
que usar export default y luego grid, está bien
to just use export default and then grid okay
23:35
así que si guardo mi archivo ahora, lo siguiente que tenemos que hacer es registrar los componentes dentro de nuestra aplicación para que podamos
so if i save my file now the next thing that we have to do is that we have to register the inside or app components so that we
23:41
verlos en la pantalla, así que solo eliminaré este h1 de aquí y
can see them on the screen so I'll just remove this h1 from here and
23:44
solo usaré mi cuadrícula primero y tan pronto como presione enter
I'll just use my grid first of all and as soon as I hit enter
23:48
aquí puedes ver que se importará automáticamente, así que si no lo hizo
here you can see it will automatically import this so if it didn't
23:51
tienes que importarlos manualmente, así que ahora solo cerraré ahí
you have to import them manually so now I'll just close there
23:54
así y por cierto, así es como llamamos a nuestro componente
like this and by the way this is how we call our component
23:57
así es como registramos nuestro componente, así es
this is how we register our component this is
24:00
cómo los exportamos y así es como los llamamos, está bien, así que si guardo mi archivo y aquí puedes ver que ahora estamos obteniendo nuestro
how we export them and this is how we call them okay so if I save my file and here you can see we are now getting our
24:08
hola aquí mismo que proviene de este componente de creación, eliminaré
hello right here which is coming from this create component i'll
24:11
eso de aquí y también renderizaré mi componente de añadir y
remove that from here and i'll also render my add component and
24:15
si presiono enter, se importará automáticamente, ahora voy a guardar
if i hit enter so it's going to automatically import that now i'm going to save
24:18
mi archivo y qué estamos obteniendo, ahora estamos obteniendo lo que agregar aquí
my file and what are we getting we are now getting what add right here
24:21
así que puedes escribir cualquier cosa que quieras, así que solo escribiré algo como
so you can write like anything that you want so i'll just write like
24:24
algo genial y ahora si guardo mi archivo y
something cool and now if i save my file and
24:27
ahora estamos obteniendo algo genial justo aquí, así que sí, así es como
we are now getting what something cool right here so yeah this is how
24:30
podemos crear una carpeta de componentes separada y podemos poner todos nuestros componentes dentro de allí, bienvenidos a otro desafío, así que en este desafío, vas a crear tres componentes y mucho JSX dentro de allí.
we can create a separate component folder and we can put our entire components inside there welcome to another challenge so in this challenge, you're going to be creating three components and a lot of JSX inside there.
24:41
Así que lo primero que quiero que hagas es que quiero que crees un header.jsx
So the first thing that I want you to do is that I want you to create a header.jsx
24:45
archivo y dentro de ese archivo tendrás que crear tu componente funcional
file and inside that file you're going to have to create your functional component
24:48
con el nombre de header y dentro de ese header vas a estar devolviendo
with the name of header and inside that header you're going to be returning
24:51
el elemento header y dentro de ese elemento header vas
the header element and inside that header element you're
24:54
a estar creando un h1 que dirá algo como bienvenido a mi sitio web y
going to be creating h1 which will say like welcome to my website and
24:58
también vas a estar creando debajo de este h1 vas a estar creando
also you're going to be creating underneath this h1 you're going to be creating
25:01
tu navegación y esa navegación tendrá tres enlaces
your navigation and that navigation will have three anchor
25:04
el primero dirá inicio, el segundo dirá acerca de
tags the first one will say home the second one will say about
25:08
y el tercero dirá contacto, así que esa será la
and the third one will say contact so that's going to be the
25:11
primera parte de este desafío, está bien, así que si
first part of this challenge okay so if
25:14
quieres intentarlo ahora mismo, puedes ir adelante y hacerlo, pero ahora voy a explicar estos dos y luego te daré mi solución, lo siguiente que tienes que hacer es crear un
you want to give it a shot right now so you can totally go ahead and give it a shot but now i'm going to explain these two and then i'm going to give you my solution the next thing that you have to do is that create a
25:23
archivo footer.jsx y crear tu componente funcional dentro
footer.jsx file and create your functional component inside
25:26
de allí y solo devolverá el elemento footer y dentro
there and it will only return the footer element and inside
25:29
de ese elemento footer vas a proporcionar un párrafo que
that footer element you're going to be providing a paragraph which
25:32
dirá algo como derechos de autor 2024 o
will say like copyright 2024 or
25:35
debería ser 2025, mi error, pero sí, puedes proporcionar básicamente cualquier cosa que te guste, pero en mi caso voy a especificar algo como derechos de autor 2024 o 25 y mi sitio web
it should be 2025 my bad but yeah you can provide like basically anything that you like but in my case i'm going to specify like copyright 2024 or 25 and my website
25:47
y esa es la segunda parte y ahora para la tercera parte vas a estar creando tu componente principal
and that's the second part and now for the third part you're going to be creating your main component
25:52
y ese componente principal solo devolverá tu elemento principal
and that main component will just return your main element
25:55
y también dentro de ese elemento principal vas a
and also inside that main element you're going
25:58
estar creando tu h2 que dirá algo como contenido principal y
to be creating your h2 which will say like main content and
26:01
ahora debajo de ese h2 vas a crear un párrafo y tú
now underneath that h2 you're going to be creating a paragraph and you
26:04
puedes básicamente poner cualquier cosa que prefieras, así que dale
can like basically put anything that you prefer so give
26:07
tu mejor intento, si puedes hacerlo, está completamente bien, luego vuelve y mira la solución y luego te daré mi solución y básicamente solo vas a importar allí y poner allí justo aquí dentro del componente de la aplicación, así que ahora déjame mostrarte todo allí arriba.
it your best shot if you can do it that's completely okay then come back and watch the solution and then i'm going to give you my solution and basically you're going to be just importing there and putting there right here inside the app component so now let me just show you all up there.
26:19
Así que lo primero que quiero hacer es crear mi header.jsx y voy a usar mi rfce para ese archivo semi.
So the first thing that I want to do is that I want to create my header.jsx and I'm going to be using my rfce for that semi file.
26:26
Voy a eliminar este encabezado de allí y proporcionar mi h1 que dirá algo como bienvenido a mi sitio web.
I'm going to remove this header from there and provide my h1 which will say like welcome to my website.
26:32
Así que eso va a ser lo primero. A continuación, también tenemos que crear nuestra navegación y dentro de esta navegación vamos a crear 3 etiquetas de anclaje.
So that's going to be the first thing. Next we also have to create our navigation and inside this navigation we're going to be creating a 3 anchor tag.
26:40
Así que si solo uso esto a y por 3, nos dará esta etiqueta de anclaje como 3 veces.
So if I just use like this a and times 3 so it's going to give us this anchor tag like 3 times.
26:45
Así que para el primero vamos a proporcionar un inicio y para
So for the first one we're going to be providing a home and for
26:48
el segundo vamos a proporcionar un acerca de y también para
the second one we are going to be providing a about and also for
26:52
el tercero vamos a proporcionar un contacto, está bien, así que si
the third one we are going to be providing a contact okay so if I
26:55
simplemente escribo como contacto y guardo mi archivo, así que se va a formatear allí para
just write like contact and save my file so it's going to format there for
26:58
mí, voy a seguir adelante e ir a mi aplicación y registrar mi
me I'm going to go ahead and go to my app and register my
27:01
componente de encabezado justo aquí, está bien, solo importemos
header component right here okay let's just import
27:05
eso y registremos eso aquí, así que ahora si guardo
that and register that here so now if I save
27:08
mi archivo y aquí puedes ver que ahora estamos obteniendo lo que bienvenido a mi sitio web, inicio, acerca de y contacto, así que esa fue la primera parte, ahora en la segunda parte vamos a crear un
my file and here you can see we are now getting what welcome to my website home about and contact so that was the first part now in the second part we are going to be creating a
27:16
componente principal, está bien, así que solo diré como main.jsx
main component okay so i'll just say like main.jsx
27:19
y dentro de allí vamos a crear nuestro rfc o
and inside there we are going to be creating our rfc or
27:23
sabes que debería ser un main, sabes que puedes básicamente darle cualquier nombre que prefieras, pero en mi caso le voy a dar
you know what it should be a main you know what you
27:26
el nombre de contenido principal y cambiar eso a main
can like basically give it any name that you prefer but in my case i'm going to give it
27:29
el nombre del contenido principal y cambiar eso a principal
the name of like main content and change that to main
27:33
así que voy a copiar allí y déjame colocar eso aquí mismo, está bien, y también voy a usar el h2 que dirá como contenido principal y ahora debajo de eso vamos a crear
so i'm going to copy there and let me just place there right here okay and i'm going to also use the h2 which will say like main content and now underneath there we are going to be creating
27:42
nuestro párrafo que dirá como este es el contenido principal y ahora voy a guardar allí.
our paragraph which will say like this is the main content and now I'm going to save there.
27:47
Ahora déjame ir a mi aplicación y registrar mi
Now let me just go ahead and go to my app and register my
27:50
componente principal justo aquí y ahora aquí puedes ver que ahora estamos obteniendo como contenido del contexto principal, ahí vamos.
main component right in here and now here you can see we're now getting like main context content there we go.
28:00
Así que ahora si guardo mi archivo y ahora estamos obteniendo como contenido principal y este es el contenido principal que se ve increíble.
So now if I save my file and now we are getting like main content and this is the main content which is looking amazing.
28:06
Ahora, para el componente final, vamos a crear nuestro footer.jsx y ahora dentro de él vamos a usar
Now for the final component we're going to be creating our footer.jsx and now inside there we're going to be using
28:12
nuestro RAFCE y eliminar este div y cambiar
our RAFCE and remove this div and change
28:15
eso a footer, está bien, simplemente proporcionemos nuestro
that to footer okay let's just provide our
28:18
párrafo que dirá copyright 2025 mi
paragraph which will say copyright 2025 my
28:22
sitio web, así que ahora si guardo mi archivo, también tienes que registrar
website so now if I save my file you also have to register
28:25
eso dentro de nuestro componente de aplicación así
that inside our app component like so
28:29
que está bien y voy a registrar eso
okay and I'm going to register that
28:32
archivo semi y ahora estamos obteniendo nuestro copyright 2025 mi sitio web, así que ese fue otro desafío sobre el componente básico ¿Qué es JSX?
semi file and now we are getting our copyright 2025 my website so that was another challenge about the basic component What is JSX?
28:41
JSX nos permite escribir HTML en ReactJS. JSX facilita escribir y agregar HTML en ReactJS.
JSX allows us to write HTML in ReactJS. JSX makes it easier to write and add HTML in ReactJS.
28:49
Así que así es como se ve nuestro JSX. Así que, primero que nada, tenemos nuestro componente y dentro de este componente ahora estamos devolviendo algo de HTML.
So this is how our JSX looks like. So first of all we have our component and inside this component we are now returning some HTML.
28:57
Ahora sé que muchos de ustedes me preguntarán, José, ¿por qué no podemos simplemente llamarlo HTML? ¿Por qué lo llamamos JSX?
Now I know a lot of you will ask me, Jose, like why can't we just call it HTML? Why are we calling it JSX?
29:03
JSX simplemente significa JavaScript XML. Detrás de escena estamos trabajando con JavaScript.
JSX simply means JavaScript XML. Behind the scene we are working with JavaScript.
29:10
Esto es solo la ilusión de HTML. Este no es código HTML.
This is just the illusion of HTML. This is not HTML code.
29:14
Detrás de escena, nuestro compilador de ReactJS compilará nuestro código en JavaScript puro. Entonces, ¿no me crees?
Behind the scene, our ReactJS compiler will compile our code into pure JavaScript. So, don't believe me?
29:21
Ahora déjame mostrarte. Ahora déjame escribir un poco de JSX para que puedan ver cómo podemos trabajar con JSX.
Now let me show you. Now let me write a bit of JSX so that you guys can see how we can work with JSX.
29:26
Así que solo crearé una sección y dentro de esta sección también le pondré un poco de ID.
So I'll just create a section and inside this section I'll also put a bit of ID to it.
29:30
Así que solo le daré el nombre de sección y dentro de esta sección crearé mi H1 que dirá mi sitio web.
So I'll just give it the name of like section and inside this section I'll create my H1 which will say my website.
29:37
Debajo de este H1 crearé mi artículo y dentro de este artículo crearé H2 que dirá algo como bienvenido a ReactJS.
Underneath this H1 I'll create my article and inside this article I'll create H2 which will say like welcome to ReactJS.
29:45
Ahora, debajo de este h2 crearé un párrafo que dirá contenido o texto del párrafo.
Now underneath this h2 I will create a paragraph which will say paragraph content or text.
29:54
También voy a proporcionar un nombre de clase para ello y, por cierto, en lugar
I am going to also provide a class name to it and by the way instead
29:57
de escribir una clase, tienes que escribir un nombre de clase y
of writing a class you have to write a class name and
30:00
te diré por qué, pero tienes que escribir un nombre de clase por ahora
i'm going to tell you why but you have to write a class name for now
30:03
y simplemente le daré el nombre de clase de texto aquí, así que si guardo
and i'll just give the class name of text right here so if i save
30:07
mi archivo y aquí puedes ver que ahora estamos obteniendo nuestro resultado aquí, así que
my file and here you can see we are now getting our result right here so
30:10
si hago clic derecho allí y voy a mi inspeccionar elemento, primero que nada estamos obteniendo
if i right click on there and go to my inspect element we are first of all getting
30:13
nuestra raíz y ahora dentro de esta raíz tenemos nuestra sección con
our root and now inside this root we have our section with
30:16
la idea de sección tenemos nuestro h1 también tenemos nuestro artículo
the idea of section we have our h1 we also have our article
30:19
y dentro de este artículo tenemos este h2 y también
and inside this article we have this h2 and we also
30:22
tenemos esta clase que ahora estamos proporcionando un nombre de clase
have this class we are are now providing a class name
30:25
y aquí puedes ver que ahora estamos obteniendo una clase esto es un jsx
and here you can see we are now getting a class this is a jsx
30:29
regla que voy a explicar en unos segundos pero sí aquí
rule which i'm going to explain in a few seconds but yeah here
30:32
puedes ver que así es como podemos escribir html dentro
you can see this is how we can write html inside
30:35
nuestra función de javascript así que para combinar todo eso esto
our javascript function so to combine all of that this
30:39
es cómo podemos crear nuestro componente ahora déjame mostrarte cómo nuestro
is how we can create our component now let me show you how our
30:42
reactjs convierte todo este html a javascript y
reactjs convert all of this html to javascript and
30:45
para mostrarte allí primero tienes que ir a babeljs.io y dentro de allí tienes que colocar tu contenido html. Así que solo copiaré mi contenido HTML de aquí.
to show you there first of all you have to go into this babeljs.io and inside there you have to place your html content So I'll just copy my HTML content from here.
30:55
Y ahora voy a colocarlo justo aquí. ¿Y qué estamos obteniendo? Ahora estamos obteniendo JavaScript.
And now I'm going to just place it right here. And what are we getting? We are now getting JavaScript.
30:58
Así que si copio allí, en lugar de escribir esta sección y artículo y cosas así, voy a simplemente eliminar eso de aquí.
So if I copy there, instead of writing this section and article and stuff like that, I'm going to just remove that from here.
31:05
Voy a escribir mi declaración de retorno. Y voy a colocar este contenido justo aquí. También voy a eliminar estas cosas. Simplemente eliminemos eso.
I'll just write my return statement. And I'm going to place this content right here. I'm going to also remove this stuff. Let's just remove that.
31:13
Voy a seleccionar este comentario y presionar Ctrl D, Ctrl D o Command D y Command D.
I'm going to also select this comment and hit Ctrl D, Ctrl D or Command D and Command D.
31:19
Y voy a simplemente eliminar eso de aquí. Así que si vendo mi archivo ahora,
And I'm going to just remove that from here. So if I sell my file now,
31:22
voy a alejar un poco y primero también voy a copiar esta línea de código y voy a tener que ponerla allí en la parte superior y no tienes que preocuparte por este código. No vamos a escribir nuestro código así.
I'm going to zoom out a bit and first of all I'm gonna also copy this line of code and I'm gonna have to put there at the top and you don't have to worry about this code We are not gonna be writing our code like this.
31:32
No tienes que preocuparte por este código. Así que voy a vender mi archivo y ahora si voy a mi sitio web y lo actualizo una vez más, estamos obteniendo el mismo resultado que mi sitio web.
You don't have to worry about this coding So I'm gonna sell my file and now if I go into my website and refresh there once again We are getting the same result like my website.
31:41
Bienvenido a react en contenido de párrafo. Así que si voy a una sección tenemos nuestro ID. Tenemos nuestro artículo H1 o H2 y también nuestro párrafo con una clase de texto justo aquí
Welcome to react in paragraph content So if I go into a section we have our ID We have our H1 article or H2 and also our paragraph with a class of text right here
31:50
Así que si no estuvieras usando JSX, vamos a tener que crear nuestro componente de esta manera.
So if you weren't using JSX, we are going to have to create our component this way.
31:56
Como vamos, mira esta redundancia. Ahora estamos usando algo de JSX y poniendo una sección a ello.
Like come on, look at this redundancy. We are now using some dash JSX and putting a section to it.
32:02
Luego estamos poniendo ID y niños. Y hay muchas cosas sucediendo.
Then we are putting ID and children. And there are a lot of things going on.
32:07
Así que en lugar de poner todo eso, voy a eliminarlo completamente de aquí. Y solo lo reemplazaré con esta declaración de retorno.
So instead of putting all of that, I'm going to totally remove that from here. And I will just replace that with this return statement.
32:14
Y también voy a eliminar esta primera línea. Así que esto es lo que es un JSX y este es el poder de ReactJS y también JSX en ReactJS.
And I'm going to also remove this first line. So this is what a JSX is and this is the power of ReactJS and also JSX in ReactJS.
32:24
Bienvenido a otro desafío. Así que en este desafío vas a practicar JSX.
Welcome to another challenge. So in this challenge you are going to be practicing JSX.
32:28
Así que, primero que nada, quiero que crees un archivo con el nombre de welcome message.jsx y dentro de ese archivo debes crear un componente con el nombre de welcome message.
So first of all I want you to create a file with the name of welcome message.jsx and inside that file then you have to create a component with the name of welcome message.
32:37
Dentro de ese componente tendrás un div y dentro de ese div tendrás tu h1 primero que nada y dentro de ese h1 vas a proporcionar algo como hello world.
Inside that component you will have a div and inside that div you will have your h1 first of all and inside that h1 you are going to be providing like hello world.
32:46
Debajo de este H1, también vas a crear un párrafo que dirá algo como welcome to learning JSX.
Underneath this H1, you're going to be also creating a paragraph which will say like welcome to learning JSX.
32:51
Y finalmente, tienes que importar en el app.jsx y renderizar eso en el DOM. Así que dale tu mejor esfuerzo. Si puedes hacerlo, está completamente bien.
And finally, you have to import in the app.jsx and render that to the DOM. So give it your best shot. If you can do it, that's completely okay.
32:58
Luego vuelve y mira la solución. Y ahora te voy a dar mi solución. Voy a crear un archivo con el nombre de welcome message.jsx.
Then come back and watch the solution. And now I'm going to give you my solution. I'm going to create a file with the name of welcome message.jsx.
33:06
Y dentro de ahí, vamos a usar nuestro RAFC para crear este componente aquí. Y primero que nada, tenemos nuestro div.
And inside there, we're going to be using our RAFC to create this component right here. And first of all, we have our div.
33:11
Y ahora dentro de este div, vamos a definir nuestro H1.
And now inside this div, we're going to be defining our H1.
33:15
que solo dirá algo como hello world y
which will just say like hello world and
33:18
ahora debajo de este h1 vamos a crear nuestro párrafo que dirá algo como
now underneath this h1 we're going to be creating our paragraph which will say like
33:21
welcome to learning jsx, voy a guardar
welcome to learning jsx i'm going to save
33:24
este archivo, ahora déjame ir a mi app.jsx
this file now let me go ahead and go to my app.jsx
33:28
archivo y registrar mi componente de bienvenida correctamente
file and register my welcome component right
33:31
aquí, así que solo lo cerraré así, guardar
in here okay so i'll just close then like so save
33:34
mi archivo y aquí puedes ver que ahora estamos obteniendo hello world y también welcome to learning jsx, así que sí, ese fue nuestro segundo desafío, siempre que trabajes con
my file and here you can see we are now getting hello world and also welcome to learning jsx so yeah that was our second challenge whenever you're working with
33:43
jsx hay algunas reglas que debes tener en cuenta, estoy
jsx there are a few rules that you have to keep in mind i'm
33:46
a punto de mostrarte sus reglas, pero primero voy a eliminar este artículo de
going to show you their rules but first of all i'm going to remove this article from
33:49
aquí, voy a guardar mi archivo y aquí puedes ver que ahora estamos obteniendo uno
here i'm going to save my file and here you can see we are now getting one
33:52
de mi sitio web que se ve increíble, así que la primera regla que
of my website which is looking amazing so the first rule that
33:55
debes tener en cuenta es que de un componente
you have to keep in mind is that from one component
33:58
se te permite devolver solo un padre
you are allowed to return only one parent
34:01
como no puede haber múltiples padres, así que qué
like there can't be multiple parents so what
34:04
quiero decir, supongamos que solo muevo esta línea
am i talking about let's suppose if i just move this line
34:07
de código a una nueva línea, así que ¿qué estamos obteniendo? Ahora estamos obteniendo un error, está
of code into new line so what are we getting we are now getting an error it
34:11
diciendo que no se te permite crear múltiples
is saying that you are not allowed to create multiple
34:14
padres, como este es un padre y este también es un padre.
parents like this is a parent and this is also a parent
34:17
o puedo simplemente escribir un div y aquí puedes ver que aún es
or i can just write a div and here you can see still it's
34:20
nos va a dar ese error justo aquí y ¿por qué es eso? porque
going to give us that error right here and why is that because
34:24
como dije, nuestro compilador de reactjs compilará nuestro
as i said that our reactjs compiler will compile our
34:27
código a javascript y eso no está permitido en javascript
code to javascript and that's not allowed in javascript
34:30
cada vez que trabajes con jsx, esta es la primera
anytime you are working with jsx this is the first
34:33
regla que debes tener en cuenta, que de un componente
rule that you have to keep in mind that from one component
34:36
solo se te permite devolver un div
you are only allowed to return one div
34:40
y ahora dentro de este div puedes hacer cualquier cosa
and now inside this div you can do anything
34:43
como puedes crear cualquier cantidad de cosas anidadas, así que
like you can create any amount of nested stuff so
34:46
puedes crear tu h1, puedes escribir cualquier cosa dentro de ahí, incluso
you can create your h1 you can write anything inside there even
34:49
dentro de este h1 puedes escribir un div y puedes escribir cualquier cosa dentro
inside this h1 you can write a div and you can write anything inside
34:52
de ahí debajo, pero debes tener en cuenta que de un componente debes devolver solo un padre y cualquier cosa que escribas dentro de ese padre funcionará perfectamente.
there underneath there but you have to keep in mind that from one component you have to return only one parent and anything you write inside that parent will totally work.
35:04
OK, así que esa es la primera cosa que debes tener en cuenta. La siguiente cosa que debes tener en cuenta es que en JSX, debes cerrar todas tus etiquetas.
OK, so that's the first thing that you have to keep in mind. The next thing that you have to keep in mind is that in JSX, you have to close all of your tags.
35:12
En HTML, eso no era necesario si querías trabajar con imágenes.
In HTML, like that wasn't necessary if you want to work with like images.
35:16
Así que simplemente creas tu imagen y ni siquiera tienes que cerrarla si no quieres. Pero en JSX, tienes que cerrarla.
So you just create your image and you don't even have to close that if you don't want it to. But in JSX, you have to close that.
35:23
como puedes ver aquí, así que si simplemente quito eso, nos dará ese error justo
as you can see right here so if i just remove that it will give us that error right
35:26
aquí, como el elemento jsx imagen no tiene un
here like jsx element image has no corresponding
35:29
etiqueta de cierre correspondiente, como tienes que cerrar eso y eso no importa
closing tag like you have to close that and that doesn't matter
35:32
si estás trabajando con la imagen o si estás trabajando con los devs, así que
if you are working with the image or if you are working with the devs so
35:35
voy a simplemente quitar eso de aquí y aquí puedes ver que también nos dará
i'm going to just remove that from here and here you can see it's going to also give
35:38
ese error justo aquí y también podemos hacerlo como un auto-cierre
us that error right here and we can also make it as a self-closing
35:42
etiqueta si quisieras, pero debes tener en cuenta que cada vez que trabajes con jsx, debes cerrar todas tus etiquetas html, está bien, así que esa es la segunda cosa
tag if you wanted to but you have to keep in mind that anytime you are working with jsx you have to close all of your html tags okay so that's the second thing
35:51
que debes tener en cuenta, la tercera cosa que debes tener en cuenta
you have to keep in mind the third thing that you have to keep in mind
35:54
es que cada vez que trabajes con las clases, no estás
is that anytime you are working with the classes you are
35:57
permitido proporcionar una clase usando la palabra clave class, en su lugar
not allowed to provide a class by using the class keyword instead
36:01
de una clase tienes que proporcionar un nombre de clase así que de qué estoy hablando
of a class you have to provide a class name so what am i talking
36:04
de qué estoy hablando voy a escribir cada uno y solo diré como hola y
about i'm going to just write each one and i'll just say like hello and
36:07
ahora si solo pongo una clase aquí solo escribiré
now if i just put a class right here i'll just write
36:10
una clase y ahora aquí voy a decir como uh mi
a class and now here i'm going to just say like uh my
36:14
clase y aquí puedes ver que no me va a dar ningún error ahora si guardo mi archivo y ahora si lo actualizo y voy a mi consola
class and here you can see it's not going to give me any error now if i sell my file and now if i refresh it and go into my console
36:21
ahora nos va a dar este error como propiedad dom inválida
now it's going to give us this error like invalid dom property
36:24
clase quisiste decir nombre de clase porque nuestro javascript
class did you mean class name because our javascript
36:27
el compilador ahora pensará que estás definiendo algún tipo de clase como
compiler will now think that you're defining some sort of a class as
36:31
aprendimos en la sección de oop como programación orientada a objetos
we learned in the oop section like object oriented programming
36:34
sección en nuestro curso de javascript javascript pensará que tú
section in our javascript course javascript will think like you
36:37
estás definiendo algún tipo de clase y como el polimorfismo
are defining some kind of a class and like the polymorphism
36:41
herencia y todo ese concepto que aprendimos así que javascript
inheritance and all of that concept that we learned okay so javascript
36:45
pensará que estás definiendo esa clase pero no lo estamos
will think that you are defining that class but we are not
36:48
definiendo esa clase solo estamos proporcionando una clase
defining that class we are just providing a class
36:51
a qué elemento así que para proporcionar
to what element okay so to provide
36:55
una clase tenemos que usar nuestro nombre de clase en su lugar así que
a class we have to use our class name instead so
36:58
si solo quito eso y si cambio allí al nombre de la clase
if i just remove that and if i change there to the class name
37:01
y ahora si guardo mi archivo ahora si actualizo eso y aquí
and now if i save my file now if i refresh that and here
37:04
puedes ver que el error ahora ha desaparecido así que sí eso fue
you can see that error is now gone so yeah that was
37:08
la tercera cosa que tienes que tener en cuenta y ahora la cuarta cosa que tú
the third thing that you have to keep in mind and now the fourth thing that you
37:11
tienes que tener en cuenta cada vez que trabajes con los formularios en
have to keep in mind anytime you are working with the forms in
37:14
alguna situación también queremos proporcionar una etiqueta para nuestro campo de entrada está bien
some situation we also want to provide a label for our input field okay
37:17
así que solo usaré como formulario y voy a quitar esta acción
so i'll just use like form and i'm going to just remove this action
37:20
porque no la necesitamos y ahora dentro de este formulario
because we don't need that and now inside this form we
37:24
solo crearemos nuestra etiqueta así que si solo creo mi etiqueta en
will just create our label so if i just create my label in
37:27
en alguna situación querríamos proporcionar nuestros cuatro atributos, así que si solo escribo como nombre y usaré mi nombre dentro, voy a crear mi entrada
some situation we would want to provide our four attribute to it so if i just write like name and i'll just use my name inside there i'm going to create my input
37:35
el campo que dirá como uh el texto estaría bien también lo haré
field which will say like uh text would be fine i'll also
37:38
proporcionar un poco de marcador de posición así que ingresa tu nombre voy a guardar mi archivo y ahora si solo actualizo allí y qué estamos obteniendo ahora estamos obteniendo como propiedad 4 inválida.
provide a bit of placeholder to it so enter your name i'm gonna save my file and now if i just refresh there and what are we getting we are now getting like invalid down property 4.
37:49
¿te referías al html4 porque ahora una vez más qué
did you mean the html4 because now once again what
37:52
el compilador de javascript pensará que estás creando algún tipo de un bucle completo
javascript compiler will think that you are creating some sort of a full
37:55
está bien así que no estamos creando un bucle completo ahora estamos proporcionando solo una propiedad for o el atributo for a una etiqueta así que en lugar de escribir un 4, tenemos que escribir qué HTML 4.
loop okay so we are not creating a full loop we are now providing just a for property or the for attribute to a label so So instead of writing a 4, we have to write what HTML 4.
38:07
Está bien, así que voy a guardar mi archivo y cuchillo actualizo allí y aquí puedes ver que el error ya se ha ido. Puedo escribir lo que quiera.
Okay, so I'm going to save my file and knife I refresh there and here you can see that error is now gone. I can write anything I want.
38:14
Así que sí, esas fueron algunas reglas sobre JSX que debes tener en cuenta cada vez que trabajes con JSX.
So yeah, that was a few rules about JSX that you have to keep in mind whenever you are working with the JSX.
38:20
En esta serie, aprendimos algunas reglas sobre JSX y vamos a explorar más a lo largo de este curso.
In this series, we learned a few rules about JSX and we are going to be exploring more throughout this course.
38:25
Pero ahora voy a hacer que recuerdes esas reglas.
But now I'm going to just make you recall those rules.
38:29
está bien así que lo primero que quiero que hagas es que quiero que crees un archivo con el nombre de jsx
okay so the first thing that i want you to do is that i want you to create a file with the name of jsx
38:32
rules.jsx dentro de ese archivo crea un componente
rules.jsx inside that file create a component
38:35
o un componente funcional con el nombre de reglas jsx y
or a functional component with the name of jsx rules and
38:38
luego dentro de ese componente de reglas jsx vas a
then inside that jsx rules component you're going to
38:41
crear un div y dentro de ese div primero que todo tienes que escribir h1
be creating a div and inside there div first of all you have to write h1
38:45
con el título de reglas jsx y ahora debajo de eso vas a crear un párrafo libre y un párrafo dirá como jsx debe devolver un
with the title of jsx rules and now underneath that you're going to be creating a free paragraph and one paragraph will say like jsx must return a
38:53
único elemento padre otro párrafo dirá como el elemento jsx
single parent element another paragraph will say like jsx element
38:56
debe estar probablemente cerrado y el tercero dirá como los atributos jsx se escriben usando un camel case como
must must be probably close and the third one will
39:00
en lugar de usar una clase vamos a usar un nombre de clase esto
say like jsx attribute are written using a camel case like
39:03
es el desafío más simple está bien así que dale lo mejor de ti
instead of using a class we're going to be using a class name this
39:06
si puedes hacerlo entonces vuelve y mira la solución y
is the most simplest challenge okay so give it your best
39:10
ahora te voy a dar mi solución ahora déjame crear mi componente con el nombre de reglas jsx.jsx solo crearé mi
shot if you can do it then come back and watch the solution and
39:13
componente funcional justo aquí y ahora dentro de este funcional
now i'm going to give you my solution now let me create my component with the name of jsx rules.jsx i'll just create my
39:19
componente lo primero que tenemos es nuestro div y ahora dentro
functional component right here and now inside this functional
39:22
component the first thing that we have is our div and now inside
39:25
este div tenemos nuestro h1 y escribiré como reglas de jsx
this div we have our h1 and i'll write like jsx rules
39:29
y ahora debajo de este h1 vamos a crear un párrafo que
and now underneath this h1 we are going to be creating a paragraph which
39:32
dirá como jsx debe devolver un único
will say like jsx must return a single
39:35
elemento padre, está bien, eso va a ser el primero
parent element okay that's going to be the first
39:38
uno, también vamos a crear otro párrafo que dirá como jsx
one we're going to be also creating another paragraph which will say like jsx
39:42
el elemento debe cerrarse correctamente y vamos, esto debería ser un y también tenemos un atributo JSX que se escribe usando un camel case así.
element must be properly closed and come on this should be a and also we have a JSX attribute are written using a camel case like so.
39:52
Así que voy a guardar mi archivo. Tenemos que eliminarlos. Y sí, ese es nuestro ejercicio simple. Ahora tenemos que registrar este componente.
So I'm going to save my file. We have to remove them. And yeah, that's our simple exercise. Now we have to register this component.
40:00
dentro de nuestra aplicación, así que solo lo registraré aquí mismo
inside our app so i'll just register that right here
40:03
está bien, así que tenemos nuestra regla jsx, así que voy a guardar mi archivo y
okay so we have our jsx rule so i'm going to save my file and
40:06
aquí puedes ver que ahora estamos obteniendo esas reglas aquí mismo, así que tenemos nuestro jsx
here you can see we are now getting those rules right here so we have our jsx
40:10
reglas, así que sí, ese fue otro desafío en
rules so yeah that was another challenge in
40:13
este curso, ahora hablemos sobre la expresión en jsx, así que
this course now let's talk about expression in jsx so
40:16
con jsx puedes escribir tu expresión dentro de las llaves y la expresión puede ser una variable o propiedad de react o cualquier otra expresión válida de javascript, jsx ejecutará esa expresión y te dará el resultado.
with jsx you can write your expression inside the curly braces and the expression can be a react variable or property or any other valid javascript expression jsx will execute that expression and give you the result.
40:29
Está bien, así que aquí puedes ver que tengo mi componente de aplicación y ahora dentro de este componente de aplicación tengo un párrafo y ahora dentro de este párrafo estoy escribiendo 2 más 2 tal como está, sin proporcionar ninguna llave, nada de eso.
Okay, so here you can see I have my app component and now inside this app component I have a paragraph and now inside this paragraph I'm now writing 2 plus 2 as it is without providing any curly braces, nothing to it.
40:40
Así que nos dará el resultado de 2 más 2 tal como está. ¿Por qué es eso? Porque ReactJS lo tratará como un texto.
So it's going to give us the result of 2 plus 2 as it is. Why is that? Because ReactJS will treat it as a text.
40:47
Pero ahora, si lo envuelves dentro de las llaves, nos dará el resultado de 4. ¿Y por qué es eso?
But now if you wrap that inside the curly braces it's going to give us the result of 4. And why is that?
40:52
Ahora ReactJS lo tratará como una expresión de JavaScript ponderada. Así que ejecutará esa expresión y nos dará el resultado de eso.
Now ReactJS will treated as a weighted JavaScript expression. So it will execute that expression and it's going to give us the result of that.
40:59
Y no solo estamos limitados a escribir 2 más 2. También podemos crear algún tipo de variable y podemos poner nuestros valores dentro de allí.
And we are not just limited to write 2 plus 2. We can also create some sort of a variable and we can put our values inside there.
41:05
Luego podemos usarlo dentro de nuestra interfaz de usuario. También podemos crear una función.
Then we can use the inside our UI. We can even also create a function.
41:08
También podemos incrustar esa función dentro de nuestra interfaz de usuario y también las clases.
We can also embed that function inside our UI and also the classes as well.
41:14
Así que ahora déjame mostrarte todo eso en acción. Ahora hablemos sobre cómo vamos a incrustar contenido dinámico en nuestro JSX.
So now let me just show you all of that in action. Now let's discuss how we are going to be embedding dynamic content in our JSX.
41:20
Así que primero, solo voy a crear mi párrafo dentro de este
So first of all, I'm going to just create my paragraph inside this
41:24
párrafo, solo seleccionaré dos más dos, ahora aquí hay una pregunta para
paragraph i'll just select two plus two now here is a question for
41:27
tú, ¿qué crees que será el resultado de este código? Así que si guardo
you what do you think will be the result of this code so if i save
41:30
mi archivo, quiero que me des la respuesta y
my file i want you to give me the answer and
41:33
el resultado será dos más dos, ¿por qué? porque no
the result will be two plus two why is that because we
41:36
estamos envolviendo este código dentro de las llaves, pero
are not wrapping this code inside the curly brace but
41:40
ahora, si envuelvo eso dentro de las llaves,
now if i wrap that inside the curly brace we
41:43
ahora ingresé nuestra palabra javascript, así que si guardo mi archivo ahora y aquí puedes ver que ahora nos va a dar hacia adelante, ¿por qué es eso?
now entered our javascript word so if i save my file now and here you can see now it's going to give us forward here why is that
41:51
porque ahora estamos ejecutando esta expresión dentro de javascript.
because now we are running this expression inside the javascript
41:54
así que nuestro compilador de react.js compilará este código y
so our react.js compiler will compile this code and it
41:57
pensará que esto es un código javascript, así que lo ejecutará.
will think like this is a javascript code so it will execute this
42:00
código, así que si solo escribo como 2 más 2 es igual
code so if i just write like 2 plus 2 is equal
42:04
a fuera de estas llaves, ahora va a
to outside from this curly braces now it's going to
42:07
darnos como 2 más 2 es igual a 4, está bien, lo cual es
give us like 2 plus 2 is equal to 4 okay which is
42:10
increíble, así que esa es la primera cosa que debes tener en cuenta. A continuación, solo crearé una variable con el nombre de mi nombre y voy a
amazing so that's the first thing that you have to keep in mind next i'll just create a variable with the name of like my name and i'm going to
42:17
almacenar mi nombre dentro de ahí como hosan webdev y ahora debajo
store my name inside there like hosan webdev and now underneath
42:20
de este párrafo voy a crear mi h1 aquí y ahora
this paragraph i'm going to create my h1 right here and now
42:23
supongamos que quiero renderizar dinámicamente mi variable
let's suppose if i want to dynamically render my variable
42:26
nombre dentro de este h1, ¿cómo puedo hacerlo?
name inside this h1 how can i go about doing
42:30
bueno, si solo escribo como mi nombre, si guardo
that well so if i just write like my name if i save
42:33
mi archivo, ahora estoy obteniendo mi nombre aquí, pero yo
my file i'm now getting my name right here but i
42:36
quiero obtener este valor como hosan webdev, así que, ¿cómo puedo hacerlo?
want to get this value like hosan webdev so how can i go about
42:39
para hacer eso, tenemos que envolver esta variable nombre dentro de estas llaves como la llave
doing that to do that we have to wrap this variable name inside these curly braces like the curly
42:45
de apertura y la llave de cierre, así que
opening brace and the curly closing brace so
42:48
si guardo mi archivo, ahora nos va a dar hosainwebdev aquí, está bien, así que así es como vamos a renderizar nuestras variables dinámicamente
if i save my file and now it's going to give us hosainwebdev right here okay so this is how we are going to be rendering our variables dynamically
42:56
dentro de nuestro jsx, no estamos limitados a solo renderizar nuestra expresión y también nuestro nombre de variable, también podemos proporcionar arreglos si así lo deseamos, así que solo crearé como un párrafo, diré como la lista de mis amigos
inside our jsx we are not limited to just render our expression and also our variable name we can also provide arrays if you wanted to so i'll just create like paragraph i'll just say like my friends
43:08
y ahora dentro de esta lista, primero voy a abrir y cerrar mi mundo javascript y ahora, ahora dentro de ahí vamos a crear nuestro arreglo que dirá como Alex.
list and now inside this list i'm gonna first of all open and close my javascript world and now Now inside there we are going to be creating our array which will say like Alex.
43:17
También tenemos a John y también a Wahid y algo así y Jordan.
We also have John and also Wahid and something like that and Jordan.
43:23
Así que si vendo mi archivo, aquí puedes ver que ahora estamos obteniendo como mi lista de amigos.
So if I sell my file and here you can see we are now getting like my friend list.
43:26
Tenemos a Alex, John, Wahid y también a Jordan aquí, lo cual es increíble.
We have Alex, John, Wahid and also Jordan right here which is amazing.
43:30
Ahora voy a crear una función y voy a ejecutar o incrustar esta función dinámicamente dentro de mi JSX.
Now I'm going to create a function and I'm going to execute or embed this function dynamically inside my JSX.
43:37
Así que solo usaré algo como multiplicar. Va a tomar el perímetro de A y también de B.
So I'll just use like multiply. It's going to take the perimeter of A and also B.
43:42
y va a devolver como a por b, está bien y
and it's going to return like a times b okay and
43:45
ahora debajo de este párrafo voy a crear otro párrafo que
now underneath this paragraph i'm going to create yet another paragraph which
43:49
dirá como 2 por 2 es igual a 2 y ahora
will say like 2 times 2 is equals 2 and now we
43:52
vamos a entrar en nuestro mundo de javascript y ahora dentro de este
are going to be entering our javascript world and now inside this
43:55
mundo de javascript vamos a ejecutar nuestra función que es
javascript world we are going to be executing our function which is
43:58
una multiplicación y para el perímetro voy a presionar 2, coma, 2, así que si guardo mi archivo y qué estamos obteniendo, ahora estamos obteniendo como 2 por 2, nos da 4, así que si cambio eso a como 2 por 10.
a multiply and for the perimeter i'm going to press 2 comma 2 so if i save my file and what are we getting we are now getting like 2 times 2 it gives us 4 so if i change that to like 2 times 10.
44:09
Guarda mi archivo. Nos va a dar como 2 por 10, nos dará 20, pero aquí estoy escribiendo como 2 por 2 y ahora nos va a dar 20.
Save my file. It's going to give us like 2 times 10 will give us 20 but here I am writing like 2 times 2 and now it's going to give us 20.
44:18
Así que si solo cambio eso a como 2 por 10 y ahora la etiqueta es totalmente correcta.
So if I just change that to like 2 times 10 and now the label is totally correct.
44:23
Como esto va a ser la etiqueta y este va a ser el valor real que ahora estamos obteniendo de JavaScript. Voy a deshacer eso.
Like this is going to be the label and this is going to be the actual value which we are now getting from the JavaScript. I'm going to undo that.
44:29
Y la última cosa que quiero mostrarte sobre la incrustación es que también podemos incrustar una clase especial en nuestro JSX.
And the final thing that I want to show you about the embedding is that we can also embed a special class into our JSX.
44:36
Así que voy a crear una especial y solo escribiré como clase simple
So I'll create a special and i'll just write like simple class
44:39
o algo así, ahora voy a crear un párrafo, voy a
or something like that now i'm going to create a paragraph i'm going to
44:42
proporcionar como, eh, esta es una especial
provide like uh this is a special
44:46
clase o algo así y dentro de este párrafo lo que
class or something like that and inside this paragraph what
44:49
quiero hacer es que quiero crear mi nombre de clase y solo voy a eliminar
i want to do is that i want to create my class name and i'm going to just remove
44:52
estos códigos de aquí y voy a proporcionar mi llave de apertura y
these codes from here and i'm going to provide my curly brace and
44:55
ahora dentro de estas llaves voy a copiar esta clase simple
now inside these curly braces i'm going to copy this simple class
44:58
nombre y solo lo voy a colocar aquí, así que si guardo mi archivo
name and i'm going to just place it right here so if I save my file
45:01
y ahora mira lo que pasa, así que si selecciono esta clase
and now watch what happens so if I select this class
45:04
aquí, así que qué estamos obteniendo, ahora estamos obteniendo nuestra clase simple
right here so what are we getting we are now getting our simple class
45:07
y ahora esta clase simple está viniendo dinámicamente
and now this simple class is coming dynamically
45:10
de nuestra palabra JavaScript aquí, así que puedo
from our JavaScript word right here so I can
45:14
cambiar eso a cualquier cosa que quiera, así que si guardo allí y aquí puedes ver que nos va a dar cualquier cosa que quiera
totally change that to like anything I want so if I save there and here you can see it's going to give us like anything I want
45:24
Así que sí, esta es la forma en que vamos a crear nuestras cosas usando JavaScript y así es como vamos a incrustar eso en nuestro JSX usando estas llaves.
So yeah, this is how we are going to be creating our stuff by using a JavaScript and this is how we are going to be embedding that to our JSX by using these curly braces.
45:33
Así que lo primero que quiero que hagas es que quiero que crees un archivo con el nombre de greetings.jsx y dentro de ahí tienes que crear tu componente funcional con el nombre de greetings.
In this challenge, you are going to be practicing the dynamic content in React GIS.
45:37
Así que dentro de ese componente, vas a devolver un div que contiene el h1 y ese elemento h1 mostrará dinámicamente el mensaje de saludo.
So the first thing that I want you to do is that I want you to create a file with the name of greetings.jsx and inside there you have to create your functional component with the name of greetings.
45:46
Básicamente tienes que crear una variable con el nombre de hola mundo o hola o gracias o algo así.
So inside that component, you're going to be returning a div that is containing the h1 and that h1 element will dynamically display the greeting message.
45:53
Y tienes que renderizar ese saludo dinámicamente dentro de este h1.
Like basically you have to create a variable with the name of like hello world or hello or gracias or something like that.
45:59
A continuación, crea un elemento de párrafo que muestre dinámicamente la fecha actual.
And you have to render that greetings dynamically inside this h1.
46:04
Así que si puedes hacer esto, está bien, te voy a mostrar la solución.
Next, create a paragraph element that dynamically display the current date.
46:07
pero sí, al menos inténtalo si puedes hacerlo, no importa
So if you can do this one, okay, I'm going to show you the solution.
46:12
de verdad, está bien y sí, aquí hay más instrucciones
but yeah at least give it a shot if you can do it like doesn't
46:15
si te importa eso y a continuación tienes que crear un componente con el nombre de
really matter okay and yeah here are more instruction
46:18
si te importa eso y a continuación tienes que crear un componente con el nombre de
if you care about that and next you have to create a component with the name of
46:21
información del producto y dentro de ese componente de información del producto, uh vas a devolver un div y dentro de ese div usa el objeto del producto, en este caso no solo un producto, sino el objeto del producto
product info and inside that product info component uh you're going to be returning a div and inside there div use the product object in this case not just a product but the product object
46:33
que contiene las siguientes propiedades como nombre que se establecerá en laptop, precio que se establecerá en alrededor de
that contains the following properties like name will be set to laptop price will be set to like
46:37
1200, disponibilidad que se establecerá en disponible, así que
1200 availability will be set to in stock so
46:40
una vez que hagas eso, entonces uh renderiza tu
once you do that then uh render your
46:43
componente en el app.jsx y eso se va a emitir
component to the app.jsx and that's going to be aired
46:47
así que dale lo mejor de ti, si puedes hacerlo, entonces vuelve
so give it your best shot if you can do it then come back
46:50
y mira la solución y te voy a dar mi solución, así que solo crearé mi
and watch the solution and i'm going to give you my solution so i'll just create my
46:53
componente greet.jsx, voy a estar usando mi
greet.jsx component i'm going to be using my
46:56
rfce y lo primero que quiero hacer es saludar, así que usaré algo como greet que dirá hola y debajo de eso, sabes qué, déjame solo
rfce and the first thing that i want to do is that i want to greet so i'll use like greet which will say hello and underneath there how you know what let me just
47:04
mostrar eso aquí mismo, voy a estar usando h1 y yo
show that right here i'm going to be using h1 and i
47:07
simplemente renderizaré mi cuadrícula, uh aquí mismo, así que voy a guardar
will just render my grid uh right here so i'm going to save
47:10
mi archivo, déjame ir y registrarme en mi app y registrar mi
my file let me go ahead and go to my app and register my
47:13
cuadrícula aquí mismo y ahora voy a guardar
grid right here and now i'm going to save
47:16
mi archivo y aquí puedes ver que ahora estamos obteniendo nuestro hola justo aquí lo cual
my file and here you can see we're now getting our hello right here which
47:20
se ve increíble, también tenemos que renderizar el muerto así que voy a
is looking amazing we also have to render the dead so i'll
47:23
simplemente usar como muerto y ahora vamos a usar nuestro nuevo muerto y ahora he renderizado allí justo aquí así que voy a escribir como muerto como una etiqueta y aquí
just use like dead and now let's just use our new dead and now i've rendered there right here so i'm going to just write like dead as a label and here
47:31
vamos a renderizar nuestra fecha y ahora tenemos que acceder al
we are going to be rendering our date and now we have to access the
47:34
método get date en esto así que ahora si guardo mi archivo ahora
get date method on this so now if i save my file now
47:38
nos va a dar como la fecha es 19 así que esa fue la primera parte de este ejercicio ahora vamos a crear otro componente con el nombre de product info punto jsx
it's going to give us like the date is 19 so that was the first portion of this exercise now let's just create another component with the name of product info dot jsx
47:49
jsx ahí vamos, también vamos a crear nuestro componente funcional
jsx there we go we're going to be also creating our functional component
47:52
y este componente funcional tendrá nuestro producto así que solo voy a escribir como producto y va a haber un objeto así que vamos a proporcionar el nombre como una propiedad y eso se va a establecer en un
and this functional component will have our product so i'll just write like product and there's going to be an object so we're going to be providing the name as a property and that's going to be set to a
48:01
portátil, también vamos a proporcionar el precio y el precio se va a
laptop we're going to be also providing the price and price will
48:04
establecer en como 1200 y también la disponibilidad se va a
be set to like 1200 and also the availability will
48:07
establecer en disponibilidad en stock
be set to in stock availability in stock
48:11
bien, así que ahora tenemos que vender nuestro archivo ahora que tenemos que
okay so now we have to sell our file now that we have to
48:14
renderizar el nombre, el precio y la disponibilidad totalmente
render the name price and availability totally
48:17
dinámicamente, así que ¿cómo podemos hacer eso? voy a
dynamically so how can we go about doing that i'm going to
48:20
eliminar este nombre y ahora aquí dentro vamos a usar nuestro h1 déjame solo poner una etiqueta de nombre y ahora vamos a usar un product.name justo aquí
remove this name and now here inside there we're going to be using our h1 let me just put a label of name and now we're going to be using a product.name right here
48:30
cuchillo, guardo mi archivo, oh primero tenemos que registrar esto
knife i save my file oh first of all we have to register this
48:33
componente así que voy a usar como product info y
component so i'm going to be using like product info and
48:36
presiona enter, guarda mi archivo, nos va a dar un portátil ahora
hit enter save my file it's going to give us a laptop now
48:40
voy a entrar allí y lo siguiente que tenemos que hacer es que también tenemos
i'm going to go in there and the next thing that we have to do is that we also have
48:43
que renderizar el precio y también la disponibilidad así que voy a
to render the price and also the availability so i'm going
48:46
duplicar eso dos veces y cambiar la etiqueta así que solo cambiaré eso a precio y también pondré un símbolo de dólar allí y también tenemos que cambiar
to basically duplicate there two times and change the label so i'll just change that to price and also put a dollar symbol there and we also have to change
48:55
el nombre al precio, bien y también
the name to the price okay and also
48:58
tenemos que eliminar este nombre y cambiarlo a disponibilidad así que
we have to remove this name and change there to availability so
49:01
simplemente colocaré esta disponibilidad justo aquí porque no puedo
i'll just place this availability right here because i can't
49:04
deletrear eso, bien, así que solo escribiré como disponibilidad aquí
spell that okay so i'll just write like availability here
49:08
guardar mi archivo y ahora estamos obteniendo el nombre
save my file and now we are getting the name
49:11
de la laptop también el precio y también la disponibilidad que
of the laptop also the price and also the availability which
49:14
ahora está configurada como en stock así que ahora si cambio cualquiera de estos valores así que en lugar de 1200 voy a cambiarlo a 1500 ahora se va a renderizar completamente allí
is now set to in stock so now if i change like any of these values so instead of 1200 i'm going to change there to like 1500 now it's going to totally render there
49:23
dinámicamente y también podemos cambiarlo a una
dynamically and we can also change there to like a
49:26
computadora en su lugar y ahora nos va a dar una computadora
computer instead and now it's going to give us a computer
49:30
ok así que sí ese fue nuestro desafío sobre el contenido dinámico ahora hablemos de
okay so yeah that was our challenge about the dynamic content now let's talk about
49:35
lista en react js así que en react js renderizarás tu
list in react js so in react js you will render your
49:38
lista con algún tipo de bucle el método map de javascript
list with some type of loop the javascript map
49:42
el método de array es generalmente el método preferido para usar en la lista
array method is generally the preferred method to use for the list
49:45
así que aquí puedes ver que tenemos nuestro componente justo aquí y ahora dentro
so here you can see we have our component right here and now inside
49:48
de este componente tenemos nuestro array de números y ahora si quieres iterar sobre cada número dentro de este array y renderizarlo en el DOM, así que vamos a usar primero las llaves
this component we have our numbers array and now if If you want to iterate over through each number inside this array and render there to the DOM, so we are going to be using first of all the curly
50:00
y ahora dentro de estas llaves vamos a obtener nuestros números
and now inside these curly braces we are going to be getting our numbers
50:03
lista y luego podemos usar nuestro método map en allí y
list and then we can use our map method on there and
50:06
ahora dentro de este método map va a tomar una función de callback y vamos a pasar un número y también el índice y ahora dentro de allí vamos a usar el ul y li para renderizar nuestros números en el DOM.
now inside this map method is going to take a callback function and we are going to be passing a number and also the index and now inside there we are going to be using the ul and li to render our numbers to the DOM.
50:17
Así que así es como vamos a hacer todo esto. Ahora déjame mostrarte eso en acción. Ahora hablemos de cómo podemos trabajar con listas.
So this is how we are going to be doing all of this. Now let me show you that in action. Now let's talk about how we can work with list.
50:24
Así que primero que nada tenemos que crear una lista luego vamos a trabajar con eso.
So first of all we have to create a list then we are going to be working with that.
50:27
Voy a crear una lista de números y dentro de estos números pondré como uno dos tres cuatro cinco y ahora tenemos que iterar sobre cada elemento dentro de esa lista y hacer algo con eso.
I'll create a numbers list and inside this numbers I will put like one two three four five and now we have to iterate over through each item inside that list and do something with that.
50:38
Así que en mi caso voy a simplemente iterar sobre cada elemento dentro de esta lista y voy a renderizar eso en el DOM.
So in my case I'm going to just iterate over through each item inside this list and I'm going to render that to the DOM.
50:43
Así que para hacer eso primero vamos a usar algún tipo de un main o sección o algo así para que podamos trabajar con eso.
So to do that first of all we are going to be using like some sort of a main or section or anything like that so that we can work with that.
50:50
Así que luego vamos a entrar en nuestro mundo de JavaScript para que podamos usar nuestro método de array de JavaScript como push, pop, reduce, filter, map y todos esos métodos.
So then we are going to be entering into our JavaScript world so that we can use our JavaScript array method like push, pop, reduce, filter, map and all of that methods.
51:00
En este caso voy a copiar el nombre de este array de números y
In this case I'm going to copy the name of this numbers array and
51:04
ahora si solo uso punto así que aquí puedes ver que tenemos todos nuestros métodos de JavaScript
now if I just use dot so here you can see we have all of our JavaScript
51:07
método de array como tenemos add, concat, copy within,
array method like we have add, concat, copy within,
51:10
entries, every fill, filter, find, find
entries, every fill, filter, find, find
51:14
index, flat, flat map y tenemos muchos de ellos pero en este caso solo estoy interesado en el método map y ahora aquí vamos a
index, flat, flat map and we have a lot of them but in this case I'm only interested in the map method and now here we are going to be
51:21
pasando nuestra función de callback a ella, así que solo usaré como eh
passing our callback function to it so i'll just use like uh
51:24
el número estaría bien y ahora para esta función de callback aquí
number would be fine and now for this callback function here
51:27
puedes ver que quiero que notes que ahora en este caso
you can see i want you to notice that now in this case
51:31
estamos proporcionando un paréntesis, no estamos
we are providing a parentheses we are not
51:34
proporcionando llaves, así que quiero que tengas eso en mente, así que ahora
providing a curly braces so i want you to keep that in mind so now
51:37
estamos proporcionando estos paréntesis y ahora si presiono enter aquí
we are providing these parentheses and now if i hit enter right here i'm
51:40
voy a escribir mi ul y ahora dentro de este ul voy a escribir mi
gonna just write my ul and now inside this ul i'm gonna write my
51:43
li aquí, así que ahora dentro de este li, mucha gente pensará que solo vamos a copiar este número y tenemos que colocarlo aquí y guardar
li right here so now inside this li a lot of people will think that we are going to be just copying this number and we have to just place it right here and save
51:51
archivo y eso se va a emitir, déjame decirlo una vez más, estamos
file and that's going to be aired let me just say that once again we
51:54
iterando sobre cada elemento dentro de este array
are now iterating over through each element inside this array
51:57
ahora estamos renderizando eso en nuestro navegador, pero ahora
we're now rendering that to our browser but now
52:00
mira lo que sucede aquí, puedes ver que ahora estamos obteniendo un número, número
watch what happens here you can see we are now getting a number number
52:03
número y no estamos obteniendo nuestros números correctamente
number and we are not getting our numbers right
52:06
aquí, así que para obtener estos números tenemos que ingresar una vez más
here so to get these numbers we have to once again enter
52:10
nuestra palabra javascript, así que tendré que eliminar eso o sabes qué, solo tenemos que envolverlo con estas llaves aquí. Así que si solo lo envuelvo con estas llaves, guardo mi archivo y ahora estamos obteniendo 1, 2, 3, 4 y 5.
our javascript word so i'm going to have to remove that or you know what we have to just wrap there with these curly braces right here So if I just wrap there with these curly braces, save my file and now we are getting 1, 2, 3, 4 and 5.
52:22
Pero todavía hay un problema. Ahora podrías estar preguntando, ¿cuál es el problema? Si voy a la consola, ¿qué estamos obteniendo? Ahora estamos obteniendo un error.
But there is still a problem. Now you might be asking like what's the problem? If I go into the console, what are we getting? We are now getting an error.
52:30
Cada hijo en una lista debe tener una clave única. ¿Y por qué estamos obteniendo este error?
Each child in a list should have a unique key prop. And why are we getting this error?
52:35
Ahora estamos obteniendo este error porque más adelante en este curso vamos a aprender sobre algo llamado estado.
We are now getting this error because later in this course we are going to be learning about something called a stat.
52:41
Y el archivo de estado nos permite silenciarlo o cambiar estos valores.
And stat file allows us to mute it or change these values.
52:44
como supongamos que quiero eliminar algo de este array
like let's suppose if i want to remove something from this array
52:48
o si quiero agregar un nuevo elemento a este array
or if i want to add a new element to this array
52:51
entonces, ¿cómo puedo hacer eso? Así que para hacer eso, necesitamos
so how can i go about doing that so to do that for that we
52:54
usar un estado, aún no hemos llegado allí, así que no vamos a
are going to be using a state we are not there yet so we are not going to
52:57
discutir un estado en este momento, pero debes tener en cuenta
be discussing a state right now but you have to keep in mind
53:00
que cada vez que quieras cambiar algo dentro de este array
that anytime you want to change something inside this array
53:03
primero que nada tenemos que proporcionar una etiqueta para ese lugar
we have to first of all provide a label for that place
53:07
bueno, supongamos que quiero eliminar o actualizar
okay so like let's suppose if i want to either remove or update
53:10
o algo dentro de este arreglo, primero tendré que
or something inside this array i'm gonna have to first of all
53:13
proporcionar algún tipo de etiqueta única para ello, simplemente
provide some sort of a unique label to it i'll just
53:16
escribiré como uh 10 para este primero y
write like uh 10 for this first one and
53:19
luego 20 para el segundo y 30 para
then 20 for the second one and 30 for
53:22
el siguiente y así sucesivamente, así es como vamos
the next one and so on and so forth so this is how we are going
53:25
a proporcionar una etiqueta única, así que cada vez que eliminemos
to be providing a unique label so anytime we remove
53:29
algo de esta lista, sobre los reactivos sabremos
something from this list over reagents will know
53:32
de dónde eliminamos su cosa específica, así que
from where we remove their specific thing so
53:35
para hacer eso no vamos a proporcionar nuestras cosas únicas aquí para
to do that we are not going to providing our unique things right here for
53:38
cada elemento dentro de nuestro arreglo, sino que vamos a proporcionar
each element inside our array but instead we are going to be providing
53:42
ahí para el padre, así que vamos a usar una clave aquí
there for the parent so we are going to be using a key right
53:45
y esa clave siempre será única, como tú
here and that key will always be unique like you
53:48
tienes que proporcionar algo único para cada elemento dentro
have to provide a unique thing for each element inside
53:51
de este arreglo, así que si proporcionas como uno para este
this array okay so if you provide like one for this one
53:54
y también uno para este, te dará un error como si
and also one for this one it's going to give you an error like it's
53:57
todavía dijera que cada hijo debe ser único, así que ahora voy a copiar eso y lo colocaré aquí y ahora si guardo mi archivo, ahora si solo actualizo eso y aquí puedes ver que ahora estamos obteniendo uno, dos, tres, 345 y no estamos obteniendo ese error.
going to still say each child should be unique okay so now i'm going to copy that and i'm going to place it right here and now if i save my file now if i just refresh that and here you can see we are now getting one two three 345 and we are not getting that error.
54:10
Así es como vamos a iterar sobre cada elemento dentro de nuestro
So this is how we are going to be iterating over through each element inside our
54:13
lista y así es como vamos a proporcionar una clave única o un identificador único para cada elemento dentro de esta lista y así es como vamos a renderizar eso en el DOM.
list and this is how we are going to be providing a unique key or a unique identifier for each element inside this list and this is how we are going to be rendering that to the DOM.
54:23
Ahora voy a eliminar todas esas cosas de aquí y también voy a eliminar este número de aquí y lo voy a reemplazar con este gran arreglo y aquí puedes ver que tenemos nuestro arreglo de información de usuarios y ahora dentro de este arreglo tenemos algunos objetos.
Now I'm going to just remove all of that stuff from here and I'm going to also remove this number from here and I'm going to replace that with this huge array and here you can see we have our users info array and now inside this array we have a few objects.
54:36
Así que tenemos un objeto, dos y muchos de ellos y dentro
So we have an object 1, two and a lot of them and inside
54:39
de este objeto tenemos un nombre de usuario, tenemos el correo electrónico y también
this object we have a username we have the email and also
54:42
la ubicación, así que tenemos el nombre de usuario de un zan, luego tenemos
the location so we have username of a zan then we have
54:45
una especie de correo electrónico de prueba y también tenemos una ubicación y luego
some sort of a test email and we also have a location and then
54:48
tenemos lo mismo para cada objeto dentro de esto
we have the same thing for each object inside this
54:51
arreglo así que ahora quiero iterar sobre cada elemento
array so now i want to iterate over through each element
54:54
dentro de este arreglo y quiero renderizar el nombre de usuario
inside this array and i want to render the username
54:57
correo electrónico y ubicación para cada usuario dentro de esto
email and location for each user inside this
55:01
información del usuario así que ¿cómo puedo hacer eso? Bueno, para hacerlo
user info so how can i go about doing that well to do
55:04
que vamos a estar usando una vez más nuestro método map así que
that we are going to be once again using our map method so
55:07
primero que nada tenemos que entrar en el javascript
first of all we have to go inside to the javascript
55:10
palabra y luego tenemos que usar nuestra información del usuario y
word and then we have to use our user info and
55:13
cuál es la información del usuario, la información del usuario es ese arreglo
what is the user's info user's info is that array
55:16
y ahora vamos a estar iterando sobre ese arreglo, está bien, así que solo usaré el método map y aquí solo pondré un usuario
and now we are going to be iterating over through that array okay so i'll just use like dot map method and here i'll just put a user
55:23
como un parámetro y ahora dentro de ahí vamos a estar usando
as a perimeter and now inside there we're going to be using
55:26
nuestro ul y como dije que tenemos que proporcionar un único
our ul and as i said that we have to provide a unique
55:30
valor de intercambio, así que en este caso solo proporcionaré como math.random
value trade so in this case i'll just provide like math.random
55:33
y ahora nos va a dar un número aleatorio cada vez que renderizamos
and now it's going to give us like a random number each time we render
55:36
nuestro contenido en el navegador, está bien, así que ahora dentro de ahí solo usaré
our content to the browser okay so now inside there i'll just use
55:39
mi li tenemos que entrar en el mundo del javascript una vez
my li we have to go inside to the javascript world once
55:42
más y podemos usar nuestro usuario y luego punto y aquí puedes ver que tenemos nuestro nombre de usuario, ubicación y también el correo electrónico, así que si yo
again and we can use our user and then dot and here you can see we have our username location and also the email so if i
55:50
solo selecciono mi nombre de usuario, guardo mi archivo y si esta es la primera vez que trabajas con react.js, esto puede parecer un poco loco para ti, pero confía en mí, si practicas un poco, llegarás allí.
just select my username, save my file and if this is the first time you are working with react.js this may look a bit crazy to you but trust me if you did a bit of practice you will get there.
56:01
Así que voy a guardar mi archivo y aquí puedes ver que ahora estamos obteniendo nuestros nombres de usuario justo aquí para cada persona.
So I'm going to save my file and here you can see we are now getting our usernames right here for each person.
56:06
Ahora voy a duplicar esta línea de código y en lugar de proporcionar este nombre de usuario, voy a presionar ctrl y espacio y ahora podemos seleccionar la ubicación.
Now I'm going to duplicate this line of code and instead of providing this username I'm going to hit ctrl and space and now we can select the location.
56:13
Voy a duplicar allí una vez más y ahora voy a presionar ctrl
I'm going to duplicate there once again and now I'm going to hit ctrl
56:16
y w una vez más y ahora voy a seleccionar mi correo electrónico, está bien
and w once again and now I'm going to select my email okay
56:20
así que voy a vender mi archivo, ahora déjame volver y esto es
so I'm going to sell my file now let me go back and this is
56:23
cómo se ve todo nuestro código y primero que nada tenemos
how our entire code looks like and first of all we have
56:26
nuestro arreglo dentro de este arreglo tenemos nuestros objetos y dentro de
our array inside this array we have our objects and inside
56:29
dentro de este array tenemos nuestros objetos y dentro
these objects we have our username email and also the location
56:32
de estos objetos tenemos nuestro nombre de usuario, correo electrónico y también la ubicación
and now we are iterating over through each item inside
56:36
y ahora estamos iterando sobre cada elemento dentro
this array and we are now only rendering the username location and also the email and here you can see we are now getting the username, location and also the email.
56:46
Así que también podemos cambiar eso al nombre de usuario, correo electrónico y luego ubicación.
So we can also change that to the username, email and then location.
56:50
Y eso nos va a dar el mismo resultado justo aquí, lo cual es increíble. Pero hay algo opcional que quiero hacer.
And that's going to give us the same result right here, which is amazing. But there is an optional thing that I want to do.
56:56
Si no te importa eso, no tienes que preocuparte por ello. Si no sabes qué es la desestructuración de JavaScript, puedes ir y ver mi video de JavaScript sobre eso.
If you don't care about that, you don't have to worry about that. If you don't know what a JavaScript destructuring is, you can go ahead and watch my JavaScript video about that.
57:04
Tengo un curso completo sobre JavaScript. Así que si tomas ese curso, estarás bien. Así que ahora voy a desestructurar este valor.
I have a complete course on JavaScript. So if you take that course, you would be fine. So now I'm going to destructure this value.
57:11
si puedes desestructurar ahí no tienes que preocuparte por eso ahora
if you can destructure there you don't have to worry about that now
57:14
voy a eliminar estos usuarios de aquí y voy a proporcionar mi llave
i'm going to remove these users from here and i'm going to provide my curly
57:17
de apertura justo aquí y también voy a desestructurar el nombre de usuario
brace right here and i'm going to destructure the username also
57:21
el correo electrónico y también voy a desestructurar la ubicación como
the email and i'm going to also destructure the location as
57:25
también y ahora ya no tengo que usar estos usuarios de nuevo
well and now i no longer have to use these users again
57:28
y de nuevo voy a seleccionar eso presionando ctrl d ctrl
and again i'm going to select that hit ctrl d ctrl
57:31
d y voy a eliminar eso de aquí, está bien, así que ahora si yo
d and i'm going to remove that from here okay so now if i
57:34
guardo mi archivo y ahora si actualizo, todavía estamos
save my file and now if i refresh there still we
57:37
obteniendo ese mismo resultado justo aquí, pero ahora ya no tenemos que
are getting that same result right here but now we no longer have
57:41
proporcionar ese usuario punto de nuevo y de nuevo para todos estos
to provide that user dot again and again for all of these
57:44
propiedades, así que sí, así es como vamos a desestructurar los
properties so yeah this is how we are going to be destructuring the
57:47
propiedades de este arreglo, bienvenido
properties from this array welcome
57:50
a otro desafío, así que en este vas a practicar cómo puedes
to another challenge so in this one you will practice how you can
57:53
renderizar una lista de datos, así que lo primero que quiero que hagas es que
render a list of data so the first thing that i want you to do is that
57:56
crees un archivo de lista de usuarios o jsx y dentro de él crea un componente de lista de usuarios, crea un arreglo de usuarios con el siguiente
create a user list or jsx file and inside there create a user list component create a users array with the following
58:03
objeto como este objeto justo aquí, cada usuario tendrá el
object like this object right here each user will have the
58:06
objeto como este objeto justo aquí, cada usuario tendrá el
id name and also the edge then use a map method
58:09
id, nombre y también la edad, luego usa un método map
to render each user to the dom okay so that's going to
58:12
será la primera parte de este desafío en la siguiente parte vas a crear
be the first portion of this challenge in the next portion you're going to be creating
58:16
un archivo de lista de productos y dentro de ese archivo vas a crear
a product list file and inside that file you're going to be creating
58:19
un componente de lista de productos y dentro de ese componente vas a crear un array de productos y dentro de este array tendrás objetos como estos que representarán
a product list component and inside that component you're going to be creating a products array and inside this array you will have like these objects which will represent
58:28
diferentes objetos así que tenemos id para el objeto el nombre precio
different objects so we have id for the object the name price
58:31
y sí, supongo que eso estará bien y ahora finalmente tienes
and yeah i guess that's going to be fine and now finally you have
58:35
registrar eso dentro del componente de la aplicación así que dale tu
to register that inside the app component so give it your
58:38
mejor intento si puedes hacerlo está completamente bien entonces vuelve y mira
best shot if you can do it that's completely okay then come back and watch
58:41
la solución y ahora te voy a dar mi solución así que lo que voy a
the solution and now i'm going to give you my solution so what i'm going to
58:44
hacer es que voy a crear mi componente user list.jsx
do is that i'm going to create my user list.jsx component
58:48
dentro de ellos voy a usar mi rafce así que lo primero que queremos hacer es crear nuestro array de usuarios así que solo usaré como cons usuarios y eso se establecerá en
inside them i'm going to be using my rafce so the first thing that we want to do is we want to create our users array so i'll just use like cons users and that's going to be set to
58:56
este array y ahora dentro de este array vamos a crear diferentes
this array and now inside this array we're going to be creating different
58:59
objetos para cada objeto o para cada usuario vamos a proporcionar el id y también vamos a proporcionar el nombre en este caso se establecerá en alice y también voy a proporcionar la edad de 25 hoy
objects for each object or for each user we're going to be providing the id and also we're going to be providing the name in this one that's going to be set to alice and i'm going to also provide the edge of 25 today
59:10
así que ahora voy a duplicar eso un par de veces y voy a cambiar el id a 1 a 2 y también a 3 también voy a cambiar el nombre a bob y este a charlie
okay so now i'm going to duplicate that a few times and i'm going to change the id to 1 to 2 and also to 3 i'm going to also change the name to bob and this one to charlie
59:24
cambiar la edad a 30 y también la
change the edge to 30 and also the
59:27
edad a 22 así que ese será mi array de usuarios y ahora dentro de este
edge to 22 so that's going to be my users array and now inside this
59:30
array tenemos algunos usuarios aquí ahora quiero iterar
array we have a few users right here now i want to iterate
59:33
a través de sus usuarios y quiero renderizarlos en el dom
over through their users and i want to render them to the dom
59:36
así que ¿cómo puedo hacer esto? así que solo voy a eliminar esta lista de usuarios y
so how can i go about doing this so i'll just remove this users list and
59:40
dentro de ahí vamos a usar nuestras llaves así que ahora estamos entrando en la palabra javascript así que ahora vamos a usar los usuarios que es nuestro array así que ahora dentro de ahí podemos usar nuestro método map.
inside there we are going to be using our curly braces so we are now entering the javascript word so now we are going to be using the users which is our array so now inside there we can use our map method.
59:50
Así que solo voy a poner un usuario y ahora aquí para cada usuario, vamos a renderizar su div. Primero que nada, este es el div del escritor.
So I'll just put a user and now here for each user, we're going to be rendering their div. First of all, this is writer div.
59:57
Y también voy a cerrar este div
And I'm gonna also close this div
1:00:00
aquí mismo semi archivo y para este div vamos a
right here semi file and for this div we are going to
1:00:03
también proporcionar la clave y la clave que vamos a establecer
be also providing the key and the key which we are going to be setting
1:00:06
será user.dot id y este
will be user dot id and this
1:00:09
id proviene de cada uno de los usuarios aquí así que tenemos nuestro id
id is coming from each of the users right here so we have our id
1:00:12
uno dos y también el tres así que eso está hecho ahora
one two and also the three so that's done now
1:00:15
dentro de este div también vamos a crear nuestro h1 que dirá
inside this div we are going to be also creating our h1 which will
1:00:18
nombre está bien así que para el nombre vamos a usar como user.dot.name voy a duplicar eso y cambiar ahí a edge está bien y también cambiar esto
say name okay so for the name we are going to be using like user dot name i'm going to also duplicate that and change there to edge okay and also change this
1:00:27
etiqueta a edge también así que ahora voy a guardar mi archivo vamos a
label to edge as well so now i'm going to save my file let's just
1:00:30
adelante e ir a nuestra aplicación y registrar nuestra lista de usuarios
go ahead and go to our app and register our users list
1:00:33
aquí así que usaré como lista de usuarios guardar mi archivo
right here so i'll use like users list save my file
1:00:36
y aquí puedes ver que ahora estamos obteniendo cada uno de los usuarios aquí así que
and here you can see we are now getting each of the users right here so
1:00:39
tenemos a nuestra alice bob y también charlie así que
we have our alice bob and also charlie so
1:00:42
esa fue la primera cosa ahora la siguiente cosa que tenemos que hacer es que tenemos que crear nuestro producto
that was the first thing now the next thing that we have to do is that we have to create our product
1:00:45
componente list.jsx dentro de ahí vamos
list.jsx component inside there we are going
1:00:49
a usar nuestro rafce y dentro de ahí vamos a definir nuestros productos aquí y eso se establecerá en un array en este array tendremos algunos
to be using our rafce and inside there let's just define our products here and that's going to be set to array in this array we'll have a few
1:00:56
objetos y cada objeto tendrá el id el
object and each object will have the id the
1:00:59
nombre así que solo escribiré como iphone o tal vez teléfono
name so i'll just write like iphone or maybe phone
1:01:02
estaría bien y también voy a poner el precio de no sé
would be fine and i'm going to also put the price of i don't know
1:01:06
solo un precio arbitrario aleatorio como no sé 600
just a random arbitrary price like i don't know 600
1:01:09
699 o algo así voy
699 or something like that i'm
1:01:12
a duplicar eso unas cuantas veces y cambiar ahí a dos y
going to duplicate there a few times and change there to two and
1:01:15
también cambiar este a tres y también voy a cambiar el nombre de eso a como laptop en lugar de poner un teléfono voy a cambiar ahí a auriculares y vamos a
also change this one to three and i'm going to also change the name of that to like laptop instead of putting a phone i'm going to change there to headphones and let's just also
1:01:24
cambiar el precio a como 1200 y también cambiar el precio a 199.
change the price to like 1200 and also change the price to 199.
1:01:30
Voy a guardar mi archivo y así es como vamos a definir nuestra lista de objetos. Está bien, así que ahora tenemos que iterar a través de ahí.
I'm going to save my file and this is how we're going to be defining our list of objects. Okay so now we have to iterate over through there.
1:01:36
Así que si quieres iterar a través de ahí vamos a usar un método de inicio de producto y nos permitirá iterar sobre cada elemento.
So if you want to iterate over through there we're going to be using a product start method and it's going to allow us to iterate over through each element.
1:01:45
Está bien, así que ahora dentro de ahí vamos a usar nuestro div. Vamos a cerrar ahí así. Guardar mi archivo.
Okay so now inside there we're going to be using our div. Let's just close there like so. Save my file.
1:01:52
También vamos a pasar nuestra clave hoy y la clave será
We're going to be also passing our key today and key will be
1:01:55
proveniente de cada uno de los productos así que vamos a proporcionar como product.id
coming from each of the products so we're going to be providing like product.id
1:01:58
que proviene de este producto y cada uno tendrá diferente
which is coming from this product and each will have different
1:02:01
id, por eso ahora lo estamos proporcionando allí porque va a haber un único
id so that's why we are now providing there because there's going to be a unique
1:02:04
uno, por eso ahora lo estamos proporcionando allí, así que ahora solo voy a
one so that's why we are now providing there so now i'm going to just
1:02:07
usar como uh h1 para el nombre y voy a
use like uh h1 for the name and i'm going
1:02:11
proporcionar como paragraph.name y también voy a cambiar allí a precio y cambiar la etiqueta a precio también, así que solo vamos a
to provide like paragraph.name and i'm going to also change there to price and change the label to price as well so let's just
1:02:18
proporcionar un símbolo de dólar, voy a guardar mi archivo y ahora déjame ir
provide a dollar symbol i'm going to save my file and now let me go
1:02:21
adelante y ir a mi componente de aplicación y
ahead and go to my app component and
1:02:24
registrar mi lista de productos aquí
register my product uh list right here
1:02:27
guardar mi archivo y voy a comentar esta línea y
save my file and i'm going to comment this line out and
1:02:31
aquí puedes ver que ahora estamos obteniendo diferentes productos como tenemos un teléfono, una laptop y
here you can see we're now getting different product like we have a phone laptop and
1:02:34
también los auriculares, oh, estamos proporcionando un símbolo de dólar dos veces, voy a tener que eliminar eso en un área, así que solo lo eliminaré de aquí porque ya lo estamos proporcionando como una cadena, así que voy a guardar mi archivo ahora.
also the headphones oh we are providing a dollar symbol twice i'm going to have to remove that in one area so i'll just remove that from here because we are already providing that as a string so i'm I'm going to save my file now.
1:02:46
Ahora se ve mejor. Así que sí, ese fue nuestro método de mapa, práctica o desafío. Ahora hablemos sobre las props.
Now that's looking better. So yeah, that was our map method, practice or challenge. Now let's talk about the props.
1:02:53
Así que las props o propiedades son argumentos pasados a los componentes de React.
So props or properties are argument passed into React components.
1:02:58
Y las props nos permiten pasar datos del componente padre a un componente hijo.
And props allows us to pass data from the parent component to a child component.
1:03:02
Las props se pasan a un componente a través del atributo HTML. Así que aquí puedes ver que tengo mi componente de aplicación.
Props are passed to a component via the HTML attribute. So here you can see I have my app component.
1:03:08
Y ahora dentro de este componente de aplicación, voy a llamar a mi componente de usuario.
And now inside this app component, I'm going to be calling my user component.
1:03:12
Y ahora supongamos que queremos pasar algún tipo de ruta de imagen desde el componente AMP, que es un componente padre, al componente de usuario, que es un componente hijo.
And now let's suppose if we want to pass some sort of an image path from the AMP component, which is a parent component, to the user component, which is a child component.
1:03:21
Así que solo escribiré una imagen o también puedes escribir un IMG. Puedes darle cualquier nombre que desees.
So I'll just write an image or you can also write an IMG. You can give it any name that you like.
1:03:25
Y luego tienes que escribir un signo igual y luego tienes que especificar la ruta. Bien, así que también podemos especificar el nombre.
And then you have to write an equal to sign and then you have to specify the path. Okay, so we can also specify the name.
1:03:31
También podemos proporcionar la imagen como un número. También podemos proporcionar la bandera isMarried como un booleano.
We can also provide the image as a number. We can also provide the isMarried flag as a boolean.
1:03:37
Y también podemos proporcionar pasatiempos como un array. Así que así es como vamos a pasar nuestros datos del componente padre al componente hijo.
And we can also provide hobbies as an array. So this is how we are going to be passing our data from the parent component to the child component.
1:03:44
Y ahora para recibir esos datos del componente padre dentro del componente hijo. Así es como vamos a hacer eso.
And now to receive that data from the parent component inside the child component. So this is how we are going to be doing that.
1:03:51
Primero que nada, vamos a tomar nuestras props como un parámetro dentro de nuestro componente. Y luego podemos usar su prop.
First of all, we are going to be taking our props as a perimeter inside our component. And then we can use their prop.
1:03:57
Y luego podemos usar la notación de punto para acceder a todos sus datos. Así que puedo usar como prop.image. Así que nos dará la imagen.
And then we can use the dot notation to access all of their data. So I can use like prop.image. So it's going to give us the image.
1:04:03
Y ahora puedo usar prop.name, prop.age, y también prop.isMarried. y también prop.hobbies.
And now I can use prop.name, prop.age, and also prop.isMarried. and also prop.hobbies.
1:04:10
Así que nos dará todos sus datos del componente padre al componente hijo. Así que ahora déjame mostrarte todo en acción.
So it's going to give us all of their data from the parent component to the child component. So now let me show you all of their in action.
1:04:17
Ahora hablemos sobre las props, como vamos a pasar nuestros datos del componente padre al componente hijo.
Now let's talk about the props, like how we are going to be passing our data from the parent component to the child component.
1:04:23
Primero que nada, vamos a tener que crear nuestro componente hijo, y luego dentro de su componente hijo, vamos a obtener nuestra prop.
First of all, we are going to have to create our child component, and then inside their child component, we are going to be getting our prop.
1:04:29
Así que solo crearé mi componente de usuario, y dentro de este componente de usuario, simplemente devolveré mi sección aquí.
So I'll just create my user component, and inside this user component, I'll just return my section right here.
1:04:35
Así que si guardo ahí, ahora tenemos que llamar o registrar este componente dentro de este componente padre.
So if I save there, now we have to call or register this component inside this parent component.
1:04:41
Así que usaré mi componente de usuario aquí y ahora vamos a pasar nuestros datos de este componente padre a este componente hijo.
So I'll just use my user component right here and now we are going to be passing our data from this parent component to this child component.
1:04:48
¿Cómo puedes hacer eso? Para hacerlo, vamos a usar las props y si vienes del fondo de HTML, ya usas props pero ni siquiera sabías que las estabas usando.
So how can you go about doing that? To do that we are going to be using the props and if you are coming from the HTML background you already use props but you didn't even know you are using it.
1:04:59
Ya has usado esta etiqueta de imagen y ahora aquí puedes ver
You've already used this image tag and now here you can see
1:05:02
estas son las props para esta etiqueta de imagen
these are the props for this image tag
1:05:05
como ahora estamos proporcionando una fuente y también estamos proporcionando la alternativa
like we are now providing a source and we are also providing the alternative
1:05:08
texto para estas props de imagen, así que ya usas
text for this image props so you already use
1:05:11
estas props pero no sabías que estabas usando una prop, así que ahora si quieres pegar algún tipo de dato de este componente padre a este componente hijo, vamos a usar una prop.
these props but you didn't know that you were using a prop okay so now if you want to paste some sort of a data from this parent component to this child component so we are going to be using a prop.
1:05:21
Ahora podemos proporcionar cualquier tipo de dato que nos guste. Así que solo lo pondré como nombre y ahora escribiré como HosenWebDev.
Now we can provide any kind of data that we like. So I'll just put it like name and now I'll just write like HosenWebDev.
1:05:29
Y por cierto, esta prop puede ser cualquier cosa y este valor también puede ser cualquier cosa, como puedes proporcionar banana aquí y puedes proporcionar naranja si quisieras.
And by the way, this prop can be anything and this value can be also anything like you can provide banana right here and you can provide like orange if you wanted to.
1:05:38
Eso funcionará exactamente igual. Así que voy a deshacerme de eso a nombre y ahora solo estoy pasando el nombre del componente padre a este componente hijo.
That will work exactly the same. So I'm going to just undo there to name and now I'm just passing name from the parent component to this child component.
1:05:47
Así que ahora si quiero acceder a ese nombre dentro de este componente hijo. Así que tendré que usar mis props aquí.
So now if I want to access that name inside this child component. So I'm going to have to use my props right here.
1:05:54
Así que usaré como props y ahora voy a registrar estas props en la consola. Así que usaré mis props aquí.
So I'll just use like props and now I'm going to log these props to the console. So I'll just use my props right here.
1:05:59
Guarda mi archivo y ahora mira lo que sucede. Así que si solo actualizo eso, ¿qué estoy obteniendo?
Save my file and now watch what happens. So if I just refresh that, what am I getting?
1:06:04
Estoy obteniendo un nombre con el valor de Hosean Webdev. ¿Y de dónde viene eso?
I'm getting a name with the value of Hosean Webdev. And where is that coming from?
1:06:09
Eso viene de esta prop de usuario aquí.
That is coming from this user prop right here.
1:06:12
Así que una vez más, si cambio eso a banana y si
So once again, if I change that to like banana and if
1:06:15
guardo ahí, ahora estoy obteniendo esa banana aquí, así que si solo actualizo
I save there I'm now getting that banana right here so if I just refresh
1:06:19
ahí estoy obteniendo esa banana, así que sí, así es como
there I'm now getting that banana so yeah this is how
1:06:22
vas a pasar tus datos de tu componente padre al hijo
you're going to be passing your data from your parent component to the child
1:06:25
componente y así es como vas a acceder allí, así que
component and this is how you're going to be accessing there so
1:06:28
ahora tenemos que usar eso, voy a quitar eso de aquí y ahora dentro de esta sección usaré mi h1, voy a proporcionar la etiqueta de nombre y aquí tenemos que renderizar eso dentro de nuestro JavaScript.
now we have to use that I'm going to just remove that from here and now inside this section I'll just use my h1 I'm going to provide the label of name and here we have to render that inside over JavaScript
1:06:40
Así que vamos a usar props.name aquí porque este es el nombre de nuestra propiedad.
So we are going to be using like props.name right here because this is the name of our prop.
1:06:45
Si guardo ahí y ahora estoy obteniendo el resultado aquí. Ahora no solo estoy limitado a proporcionar las cadenas.
If I save there and I'm now getting the result right here. Now I'm not only limited to provide the strings.
1:06:50
También puedo proporcionar lo que quiera. Así que solo usaré como edge y edge se establecerá en 18, no 18, 22.
I can also provide like anything I want. So I'll just use like edge and edge will be set to 18, not 18, 22.
1:06:58
Y también voy a proporcionar el valor booleano como está casado y eso se establecerá en falso.
And I'm going to also provide the boolean value like is married and that's going to be set to false.
1:07:02
Así que no podemos ver eso ahora mismo porque ahora estamos renderizando allí en la interfaz de usuario.
So we cannot see that not right now because we are now rendering there to the UI.
1:07:08
así que no veremos el resultado de eso, pero más tarde muy pronto estaremos
so we will not see the result of that but later very soon we're
1:07:11
también discutiendo sobre los valores booleanos para las propiedades
going to be also discussing about the boolean values for the props
1:07:14
también verás eso muy pronto, no te preocupes por eso, también podemos
as well you will see there very soon don't worry about it we can also
1:07:17
proporcionar la lista si quisieras, así que solo usaré como um coding
provide the list if you wanted to so i'll just use like um coding
1:07:21
también voy a proporcionar como uh reading y también
i'm going to also provide like uh reading and also
1:07:24
el dormir, así que si digo oh entonces
the sleeping so if i say oh then so
1:07:28
se va a formatear de esta manera, así que solo lo quitaré de aquí y ahora tenemos que acceder a eso aquí, así que solo lo pondré así es mi nombre y edad y voy a renderizar mi propiedad de edad aquí.
it's going to format it this way so i'll just remove that from here and now we have to access that right here so i'm going to just just put it like this is my name and age and I'm going to render my prop start age right here.
1:07:39
También voy a renderizar mi bandera booleana de está casado, así que solo usaré como está casado y aquí
I'm going to also render my is married Boolean flag so I'll just use like is married and here
1:07:47
Voy a pasar mi propiedad de está casado y debajo de ellos vamos a proporcionar nuestro h4 de pasatiempos y aquí tenemos que renderizar nuestros pasatiempos aquí.
I'm going to pass my prop start is married and underneath them we are going to be providing our h4 of hobbies and here we have to just render our hobbies right here.
1:07:57
Vamos, si puedo escribirlo hoy como propiedad de pasatiempos.
Come on if I can type it today like prop start hobbies.
1:08:00
Así que si guardo mi archivo y aquí puedes ver que ahora estamos obteniendo nuestro
So if I sell my file and here you can see we are now getting our
1:08:03
nombre, edad y también está casado, pero no podemos ver
name age and also is married but we cannot see
1:08:07
el valor de eso, como dije que lo veremos muy pronto, pero
the value of that as i said that we will very soon but
1:08:11
esto es solo un video booleano y no podemos ver eso suficiente
this is just a boolean video and we cannot see that enough
1:08:14
ahora mismo y también tenemos nuestros pasatiempos y los pasatiempos son
right now and we also have our hobbies and hobbies are
1:08:17
programación, lectura y dormir, en algunas situaciones también quisiéramos
coding reading and sleeping in some situation we would also want
1:08:20
proporcionar nuestras imágenes, así que solo pondré otra propiedad para
to provide our images so i'll just put yet another prop for
1:08:23
la imagen y aquí voy a pasar mi propia imagen que
the image and here i'm going to just pass my own image which
1:08:26
proviene de mi repositorio de github, si tienes tu propia imagen, puedes totalmente
is coming from my github repository if you have your own image you can totally
1:08:29
proporcionar allí y ahora también tenemos que renderizar allí aquí, así que
provide there and now we also have to render there right here so
1:08:32
voy a usar mi etiqueta de imagen en lugar de proporcionar este curso
i'm going to be using my image tag instead of providing this course i'm
1:08:35
voy a eliminar eso de aquí y solo voy a renderizarlo dinámicamente
going to remove that from here and i'm going to just render that dynamically
1:08:39
así que solo usaré como prop start image o img
so i'll just use like prop start image or img
1:08:42
y también voy a proporcionar algo de texto para este texto alternativo
and i'm going to also provide some text for this alternative text
1:08:45
así que solo usaré como prop start supongo que nombre
so i'll just use like prop start i guess name
1:08:48
estaría bien así que si los guardo y ahora estoy obteniendo esto
would be fine so if i save them and i'm now getting this
1:08:51
chico increíble pero esto es súper, uh, esto es súper grande así que solo tendré que proporcionar un ancho de 200 estaría bien guardar mi archivo y aquí puedes ver que ahora estoy obteniendo esta tarjeta justo aquí.
amazing guy but this is super uh this is super huge so i'll just have to provide a width of 200 would be fine save my file and here you can see i'm now getting this card right here.
1:09:03
Así que ahora estoy obteniendo mi imagen, el nombre, la edad y todo justo aquí.
So I'm now getting my image, the name, age, and everything right here.
1:09:07
Así que así es como vamos a pasar nuestros datos de este componente padre a este componente hijo.
So this is how we are going to be passing our data from this parent component to this child component.
1:09:12
Y así es como vamos a acceder a sus datos usando las props. Y así es como vamos a renderizar sus datos usando las props.
And this is how we are going to be accessing their data by using the props. And this is how we are going to be rendering their data by using the props.
1:09:19
Ahora hay una cosa que quiero hacer, que se llama la desestructuración de props.
Now there is one thing that I want to do, which is called the prop destructuring.
1:09:24
Pero si no sabes qué es una desestructuración, puedes ir a mi curso de JavaScript y ver qué es una desestructuración, o simplemente puedes
But if you don't know what a destructuring is, you can either go to my JavaScript course and watch what a destructuring is, or you can just
1:09:31
leer sobre eso, puedes preguntar a chat gpt si quieres, pero
read about that you can ask from chat gpt if you wanted to but
1:09:34
tienes que aprender sobre la desestructuración de props porque voy
you have to learn about the prop destructuring so because i'm going
1:09:37
a estar usando una desestructuración de props ahora mismo así que solo voy a eliminar estas props
to be using a prop destructuring right now so i'll just remove these props
1:09:40
aquí y solo voy a desestructurar mi nombre
right here and i'm going to just destructure my name
1:09:44
y también el indicador de casado y también los pasatiempos
edge and also is married flag and also the hobbies
1:09:47
así que ahora ya no tengo que usar estas props de nuevo y
so now i no longer have to use these props again and
1:09:50
de nuevo así que voy a seleccionar uno, presionar ctrl d ctrl d ctrl d ctrl d ctrl d ctrl d y eliminar allí y si guardo mi archivo aquí puedes ver que todo sigue funcionando como lo expandimos.
again so i'm going to select one hit ctrl d ctrl d ctrl d ctrl d ctrl d ctrl d and remove there and if i save my file and here you can see everything is still working the way we expand work.
1:10:02
Está bien, así que ahora estamos desestructurando todas esas propiedades. Y ahora estamos usando eso dentro de nuestro componente. Así que sí, eso fue todo sobre las props.
Okay, so now we are destructuring all of that properties. And now we are using that inside of our component. So yeah, that was it about the props.
1:10:09
Y eso fue todo sobre la desestructuración de props. Tiempo para el ejercicio de props.
And that was it about the props destructuring. Time for the props exercise.
1:10:13
Así que en este ejercicio, vas a crear un archivo products.jsx. Y dentro de allí, vas a definir el componente funcional con el nombre de persona.
So in this exercise, you are going to be creating a products.jsx file. And inside there, you are going to be defining the functional component with the name of person.
1:10:20
Y tomará dos props. Así que va a tomar el nombre de la persona y también va a tomar la edad de la persona.
And it will take two props. So it's going to take the person name. and it's going to also take the person age.
1:10:26
Así que ahora dentro de ese componente persona, vas a usar el h2 que mostrará el nombre de la persona y luego vas a usar un párrafo que mostrará la edad de la persona.
So now inside that person component, you're going to be using the h2 which will display the person name and then you're going to be using a paragraph which will display the person age.
1:10:35
Así que esa va a ser la primera parte de este ejercicio. Ahora
So that's going to be the first portion of this exercise. Now
1:10:38
en la segunda parte, vas a crear un archivo product.jsx y dentro de él, una vez más, vas a definir el componente funcional con el nombre de producto y ahora dentro de él, también tomará dos props.
in the second portion, you're going to be creating a product.jsx file and inside there once again, you're going to be defining the functional component with the name of product and now inside there, it's going to also take two props.
1:10:49
Así que vas a proporcionar el nombre del producto y también el precio del producto.
So you're going to be providing the product name and also the product price.
1:10:54
Así que vas a usar H2 para mostrar el nombre del producto. Vas a usar un párrafo para mostrar el precio del producto.
So you're going to be using H2 to display the product name. You're going to be using a paragraph to display the product price.
1:11:00
Y finalmente, solo tienes que importarlo a tu componente de aplicación. Y eso será todo. Así que dale tu mejor esfuerzo. Si puedes hacerlo, está completamente bien.
And finally, you have to just import that to your app component. And that's going to be it. So give it your best shot. If you can do it, that's completely okay.
1:11:07
Luego vuelve y mira la solución. Y ahora te voy a dar mi solución. Así que solo crearé un componente como person.jsx.
Then come back and watch the solution. And now I'm going to give you my solution. So I'll just create like person.jsx component.
1:11:13
Y voy a usar mi RAFC dentro de él. Y déjame ir a mi aplicación. Registrar mi componente aquí. Así que solo usaré como persona.
And I'm going to be using my RAFC inside there. And let me just go ahead and go to my app. Register my component here. So I'll just use like person.
1:11:21
Importa allí y cierra allí. Ahora quiero proporcionar un aviso a esta persona. ¿Cómo puedo hacerlo?
Import there and close there. Now I want to provide a prompt to this person. So how can I go about doing that?
1:11:27
Voy a proporcionar el nombre y el nombre. Puedes proporcionar básicamente cualquier nombre que prefieras.
I'm going to provide the name and name. You can provide like basically any name that you prefer.
1:11:31
Pero en mi caso, voy a especificar mi propio nombre y también voy a proporcionar mi edad, que se establecerá en 22.
But in my case, I'm going to specify my own name and also I'm going to provide my edge, which will be set to 22.
1:11:37
Así que ahora que hemos proporcionado con éxito estas props aquí, lo siguiente que tenemos que hacer es ir a esta persona y usar esas props.
So now that we successfully provided these props right here, so the next thing that we have to do is that we have to go ahead and go to this person and we have to use those props.
1:11:46
Así que para usar eso, vamos a usar nuestras props. y aquí primero tenemos que usar nuestro h2 no h1 sino h2 y vamos a usar props.name
So to use that, we're going to be using our props. and here first of all we have to use our h2 not h1 but h2 and we're going to be using a props.name
1:11:56
porque ahora solo estamos interesados en este nombre aquí así que
because we are now only interested in this name right here so
1:11:59
así es como vamos a renderizar ese nombre a continuación
that's how we are going to be rendering that name next
1:12:03
también tenemos que crear un párrafo que renderice la prop.edge
we also have to create a paragraph which will render the prop.edge
1:12:07
así que guardo mi archivo y aquí puedes ver que ahora estamos obteniendo el nombre y también la edad aquí así que esa fue la primera parte de este desafío así que lo siguiente que tenemos que hacer
so knife i save my file and here you can see we are now getting the name and also the edge right here so that was the first portion of this challenge so the next thing that we have to do
1:12:17
es que tenemos que crear nuestro componente product.jsx. Voy a usar el RAFCE
is that we have to create our product.jsx component. I'm going to be using the RAFCE
1:12:22
y una vez más tenemos que ir a nuestra aplicación y registrar nuestro componente de producto aquí.
and once again we have to go to our app and register our product component right here.
1:12:27
También tomará dos props así que vamos a proporcionar el nombre y el nombre se establecerá en iPhone y voy a proporcionar el precio de un precio alto.
It's going to also take two props so we're going to be providing the name and name will be set to iPhone and I'm going to provide the price of like a lot of price.
1:12:35
No sé, tal vez creo que eso estará bien. Así que ahora guardemos este archivo y vayamos a nuestro producto y vamos a
I don't know maybe I guess that's going to be fine. So now let's just save this file and go into our product and we are going to be
1:12:42
obtener esas props usando este objeto props y tenemos
getting that props by using this props object and we have
1:12:45
que usar nuestro h2 para renderizar las props. lo que yo
to use our h2 to render the props.what i
1:12:49
olvidé el nombre y también el precio así que solo renderizaré el nombre
forgot the name and also the price so i'll just render the name
1:12:52
y también tenemos que usar nuestro párrafo y
and also we have to use our paragraph and
1:12:55
que dirá props.price está bien
which will say props.price okay
1:12:58
así que ahora si guardo mi archivo y aquí puedes ver que ahora estamos obteniendo hosain y
so now if i save my file and here you can see we are now getting hosain and
1:13:02
también 22 como edad y también estamos obteniendo el nombre de iphone
also 22 as an age and we're also getting the name of iphone
1:13:05
y esa cantidad de precio así que eso es genial y todo, pero lo siguiente que tenemos que hacer es que tenemos que
and that amount of price so that's cool and everything but the next thing that we have to do is that we have to
1:13:11
desestructurar el nombre y el borde y tenemos
destructure the name and the edge and we have
1:13:14
usar el interior de este componente, así que para hacer eso voy a eliminar
to use the inside this component so to do that I'm going to remove
1:13:17
estas props, como, eh sí, solo voy a eliminarlas
these props like uh yeah I'm going to just remove them
1:13:20
y voy a poner el nombre y también el borde que
and I'm going to put the name and also the edge we
1:13:24
ya no tenemos que usar estas props punto una y otra vez, así que voy a seleccionarlo y presionar ctrl d, así que se va a seleccionar allí dos veces y eliminarlo, ahora si yo
no longer have to use these props dot again and again so I'm going to select it and hit ctrl d so it's going to select there twice and remove there now if I
1:13:32
guardo mi archivo y una vez más aquí puedes ver que el resultado es exactamente el mismo y a continuación tenemos que ir
save my file and once again here you can see the result is exactly the same and next we have to go
1:13:38
al producto y eliminar estas props de allí y
into the product and remove this props from there and
1:13:41
vamos a estar proporcionando o desestructurando el nombre y también el
we're going to be providing or destructuring the name and also the
1:13:44
precio, así que ahora voy a seleccionar estas props una vez más y
price okay so now i'm going to select these props once again and
1:13:47
presionar ctrl d y eliminar ese archivo semi y ahora
hit ctrl d and remove that semi file and now
1:13:50
estamos obteniendo exactamente la misma cosa, así que sí, esto
we are getting exactly the same thing so yeah this
1:13:54
es cómo vamos a estar proporcionando una props, así es como vamos a estar desestructurando, así es como vamos a estar usando los componentes internos, ahora en algunas situaciones querríamos pasar nuestros
is how we're going to be providing a props this is how we are going to be destructuring there this is how we are going to be using the inside work components now in some situation we would want to pass our
1:14:03
datos de nuestro componente padre a nuestro componente hijo al
data from our parent component to our child component by
1:14:06
cerrar allí, así que ¿qué quiero decir con eso? Déjame acercar un poco y
closing there so what do i mean by that let me just zoom in a bit and
1:14:10
lo primero que quiero hacer es que quiero crear una carpeta de componentes
the first thing that i want to do is that i want to create a components folder
1:14:13
y proporcionaré mi card.tsx no tsx
and i will provide my card.tsx not tsx
1:14:16
sino jsx dentro de allí, ahora déjame usar mi rfc
but jsx inside there now let me use my rfc
1:14:19
guardo mi archivo y lo que voy a hacer es que voy a llamar a mi componente de tarjeta aquí, pero no voy a llamar a mi componente así, voy a cerrarlos manualmente así
save my file and what i'm going to do is that i'm going to call my card component right here but i'm not going to call my component like so i'm going to close them manually like that
1:14:31
y ahora dentro de allí lo que quiero hacer es que quiero escribir mi h1 que seleccionará
and now inside there what i want to do i want to write my h1 which will select
1:14:34
mi tarjeta y también proporcionaré un párrafo que dirá
my card and i will also provide a paragraph which will say
1:14:37
como este es un contenido para la tarjeta
like this is some content for card
1:14:41
uno, así que ahora déjame guardar mi archivo y ahora déjame volver
one okay so now let me just save my file and now let me go back
1:14:44
así que aquí puedes ver que ahora estamos pasando estos datos a
so here you can see we are now passing this data to
1:14:47
nuestro componente de tarjeta cerrando allí, pero
our card component by closing there but
1:14:50
ahora la pregunta es cómo en el mundo vamos a acceder a sus datos, así que para acceder a sus datos hay algo llamado los hijos que nos permite
now the question is how in the world we are going to be accessing their data so to access their data there is something called the children which allows us
1:14:58
acceder a sus datos desde el componente padre al componente hijo
to access their data from the parent component to the child component
1:15:01
así que usaré props y aquí solo usaré
so i'll use like props and here i'll just use like
1:15:04
props.children, así que si uso
props.children so if i use
1:15:07
eso, ahora déjame usar mi npm run dev, así que
that now let me use my npm run dev so it's
1:15:10
va a iniciar mi servidor, déjame escribir un localhost aquí
going to start my server let me just write a local host right here
1:15:13
y qué estamos obteniendo, ahora estamos obteniendo como mi tarjeta y
and what are we getting we're now getting like my card and
1:15:17
también ese mismo texto de párrafo aquí, está bien, así que también podemos desestructurarlos simplemente eliminando estas props
also that same paragraph text right here okay so we can also destructure them by just removing these props
1:15:23
y desestructurar nuestros hijos, así que ahora ya no tenemos que
and destructure our children so now we no longer have to
1:15:26
especificar estas props, y ahora tenemos que guardar nuestro archivo y
specify these props dot and now we have to save our file and
1:15:29
aquí puedes ver que todavía estamos llegando allí y sí, voy
here you can see we are still getting there and yeah i'm
1:15:32
a duplicar eso como unas cuantas veces, así que eso fue para uno y
going to just duplicate there like a few times so that was for the one and
1:15:35
voy a duplicar eso como dos veces, así que esto va a ser
i'm going to just duplicate there like two times so this is going to be
1:15:39
mi tarjeta dos y luego tarjeta tres y
my card two and then card three and
1:15:42
sí, ahora estamos obteniendo todos sus datos de nuestro componente padre que es este componente de aplicación y ahora estamos pasando eso al componente de tarjeta y así es como vamos a acceder a ellos usando los hijos.
yeah we are now getting all of their data from our parent component which is this app component and we are now passing that to the card component and this is how we are going to be accessing there by using the children.
1:15:53
Ahora hablemos sobre el renderizado condicional. Así que el renderizado condicional nos permite mostrar dinámicamente diferentes componentes de UI o contenido basado en una condición específica.
Now let's talk about the conditional rendering. So conditional rendering allows us to dynamically display different UI component or content based on a specific condition.
1:16:01
Esto nos permite crear experiencias de usuario más interactivas y receptivas.
This enables us to create more interactive and responsive user experiences.
1:16:05
Así que hay algunas formas de renderizar condicionalmente nuestra UI.
So there are a few ways to conditionally render our UI.
1:16:09
La primera forma es simplemente usar la declaración if y else y también tenemos otras formas como usar el ternario y también el operador and.
The first way is to just use the if and else statement and also we have another ways like using the ternary and also the end operator.
1:16:16
Así que ahora hablemos sobre la primera que es la declaración if y else. Así que aquí puedes ver que tenemos dos componentes, como tenemos el componente de contraseña válida y también tenemos el componente de contraseña inválida.
So now let's talk about the first one which is the if and else statement. So here you can see we have two component, like we have the valid password component and we also have the invalid password component.
1:16:25
Ahora vamos a crear otro componente de contraseña y luego lo llamaremos dentro de nuestro componente de aplicación.
Now we are going to be creating yet another password component and then we are going to be calling that inside our app component.
1:16:31
Y ahora dentro de este componente de aplicación, vamos a pasar la prop isValid a él y eso se establecerá en verdadero.
And now inside this app component, we are going to be passing the isValid prop to it and that's going to be set to true.
1:16:37
Ahora recibiremos esa prop dentro del componente de contraseña y luego vamos a proporcionar nuestra verificación.
Now we will receive that prop inside the password component and then we are going to be providing our check.
1:16:43
Así que si nuestra prop isValid es verdadera, vamos a renderizar el componente de contraseña válida.
So if our isValid prop is true, we are going to be rendering the valid password component.
1:16:48
Entonces, si ese no es el caso, vamos a devolver el componente de contraseña inválida.
So if that's not the case, we are going to be returning the invalid password component.
1:16:52
Así que podemos usar eso utilizando la declaración if y else y también podemos refactorizar este código para usar el ternario de JavaScript.
So we can use that by using the if and else statement and we can also refactor this code to use the JavaScript ternary.
1:16:58
Así que para usar eso, aquí puedes ver que voy a comentar todo ese código y ahora voy a usar mi operador ternario.
So to use that, here you can see I'm going to comment all of that code out and now I'm going to be using my ternary operator.
1:17:04
Así que si la propiedad isValid es igual a true, vamos a renderizar nuestro componente de contraseña válida.
So if is valid prop is equal to true, we are going to be rendering our valid password component.
1:17:09
Pero si ese no es el caso, vamos a devolver el componente de propiedad inválida. Aquí hay otro ejemplo.
But if that's not the case, we are going to be returning the invalid prop component. Here's another example.
1:17:15
Tengo un componente de tarjeta y ahora dentro de este componente de tarjeta tengo mis compras y ahora aquí voy a verificar si groceries.length es mayor que cero y luego vamos a mostrar esta interfaz de usuario.
I have a card component and now inside this card component I have my groceries and now here I'm going to be checking if groceries.length is greater than zero and then we are going to be displaying this UI.
1:17:27
Pero si ese no es el caso, como si no tenemos ningún contenido dentro de la lista de compras, entonces no nos va a mostrar nada.
But if that is not the case, like if we don't have any content inside the groceries list, then it's not going to show us anything.
1:17:34
Así que sin perder tiempo, ahora vamos a entrar en la codificación. Ahora hablemos sobre cómo vamos a renderizar nuestra interfaz de usuario basada en algún tipo de condición.
So without wasting any time, now let's get into the coding. Now let's talk about how we are going to be rendering our UI based on some sort of condition.
1:17:41
Así que para hacer eso, voy a crear tres componentes. Así que el primer componente que voy a crear será un componente de contraseña válida que solo devolverá algo como h1 contraseña válida.
So to do that, I'm going to create three components. So the first component I'm going to create will be a valid password component which will only return like h1 valid password.
1:17:50
Voy a duplicar eso y voy a cambiarlo a contraseña inválida y también el nombre del componente a contraseña inválida también.
I'm going to duplicate that and I'm going to change that to invalid password and also the component name to invalid password as well.
1:17:59
Está bien, así que esos van a ser mis primeros dos componentes. Ahora también voy a crear un componente para la contraseña en sí y aquí dentro no vamos a devolver nada.
Okay so that's going to be my first two component. Now I'm going to also create a component for the password itself and here inside there we are not going to be returning anything.
1:18:07
Voy a llamar a este componente mi componente de contraseña aquí mismo
I'm going to call this component my password component right here
1:18:11
dentro de mi componente de aplicación y también le voy a dar el
inside my app component and i'm going to also give it the
1:18:14
prop de isValid y eso se va a establecer en true ahora
prop of is valid and that's going to be set to true now
1:18:17
dentro de mi componente de contraseña también voy a reestructurar esa propiedad
inside my password component i'm going to also restructure that prop
1:18:20
que es la propiedad isValid ahora dentro de este componente de contraseña
which is the is valid prop now inside this password component
1:18:23
voy a verificar si isValid así que
i'm going to be checking if is valid so
1:18:27
en esta situación vamos a devolver el componente de contraseña válida
in this situation we are going to be returning the valid password component
1:18:30
y si ese no es el caso, vamos a devolver el componente de contraseña inválida aquí mismo, así que ahora déjame solo
and if that's not the case we are going to be returning the invalid password component right here so now let me just
1:18:36
decir eso una vez más, primero estamos creando dos componentes como el
say that once again first of all we are creating two components like the
1:18:39
contraseña válida y también la contraseña inválida y también estamos creando un componente de contraseña que está tomando la propiedad de isValid, ahora eso está establecido en true basado en esa propiedad, ahora estamos verificando si eso está establecido en true
valid password and also the invalid password and we are also creating a password component which is taking the prop of is valid now that is set to true based on that prop we are now checking if that is set to true
1:18:52
renderizar este componente si eso no está establecido en true entonces
render this component if that is not set to true then
1:18:55
renderizar este componente, así que ahora en este caso la propiedad isValid está establecida en true, así que nos va a dar el resultado del componente de contraseña válida que es
render this component so now in this case the is valid is set to true so it's going to give us the result of valid password component which is
1:19:03
la contraseña válida y aquí puedes ver que ahora estamos obteniendo la contraseña válida
the valid password and here you can see we are now getting the valid password
1:19:07
componente, ¿por qué es eso? porque isValid es
component why is that because is valid is
1:19:10
ahora se establece en verdadero, así que nos dará el componente de contraseña válido
now set to true so it's going to give us the valid password component
1:19:13
aquí mismo, pero ahora si lo hago falso, así que ahora
right here but now if i make that as false so now
1:19:16
déjame cambiar eso a falso y ahora estamos obteniendo una contraseña inválida
let me just change that to false and now we are getting an invalid password
1:19:19
componente aquí porque lo que es la propiedad válida es
component right here because what is valid prop is
1:19:23
establecido en falso, así que no va a renderizar esta interfaz de usuario, en su lugar va a renderizar esta interfaz de usuario aquí, así que esa fue la primera
set to false so it's not going to render this ui instead it's going to render this ui right here so that was the first
1:19:29
manera en que podemos renderizar nuestros componentes basados en algún tipo de condición
way we can render our components based on some sort of a condition
1:19:33
ahora podemos refactorizar completamente este código para usar un operador ternario
now we can totally refactor this code to use a ternary operator
1:19:36
así que voy a comentar esta línea y sabes qué, también voy a comentar
so i'm going to comment this line out and you know what i'm going to also comment
1:19:39
esa línea y solo devolveré como es válido y
that line out and i'll just return like is valid and
1:19:42
si ese es el caso, vamos a devolver el válido, vamos, válido
if that's the case we're going to be returning the valid come on valid
1:19:46
componente de contraseña y si ese no es el caso, vamos
password component and if that's not the case we're
1:19:49
a devolver el componente de contraseña inválida aquí, así que si digo allá, eso va a funcionar exactamente igual, así que si cambio eso a verdadero, nos dará el componente de contraseña válido.
going to be returning the invalid password component right here so if i say over there that's going to work exactly the same so if i change that to true and it's going to give us that valid the password component.
1:20:00
regresar, ahora también puedo refactorizar un poco más si quisiera, así que puedo eliminar completamente este código, también puedo eliminar esta declaración de retorno y también voy a eliminar estas llaves de aquí
return now i can also refactor there a bit more if i wanted to so i can totally remove this coding i can also remove this return statement and i'm going to also remove these curly braces from here
1:20:09
archivo semi y así es como vamos a ser condicionalmente
semi file and this is how we are going to be conditionally
1:20:12
renderizando nuestra interfaz de usuario, ahora déjame darte un ejemplo más usando
rendering or ui now let me give you one more example by
1:20:15
el operador y, así que voy a eliminar todo ese código de aquí y
using the end operator so i'm going to just remove all of that coding from here and
1:20:18
ahora voy a crear un componente separado con el nombre de tarjeta, así que solo le daré el nombre de tarjeta y lo voy a eliminar de aquí, y así es como vamos a crear
now i'm going to create a separate component with the name of card so i'll just give it the name of card and i'm going to remove that from here and this is how we are going to be creating
1:20:26
el componente y también voy a llamar a este componente aquí dentro de mi aplicación, así que solo lo eliminaré y renderizaré
component and I'm going to also call this component right
1:20:29
mi componente de tarjeta aquí, así que si guardo eso y
here inside my app so I'll just remove that and render
1:20:32
ahora estamos obteniendo nuestra tarjeta aquí, que se ve increíble ahora
my card component right here so if I save that and
1:20:35
dentro de este componente de tarjeta voy a poner mis elementos aquí
we are now getting our card right here which is looking amazing now
1:20:38
así que const elementos y tendremos algunos elementos aquí
inside this card component I'm going to put my items right
1:20:41
dentro de este componente y ahora déjame colocar este elemento aquí
here so const items and we will have a few items right
1:20:45
así que tenemos algunos elementos dentro de esta lista, así que lo que voy a hacer es que voy a eliminar esta tarjeta de aquí y voy a
here inside this component and now let me just place this item right
1:20:48
simplemente escribir mi h1 tarjeta y también voy a pasar mi tarjeta
here so we have a few items inside this list so what I'm going to do is that I'm going to just remove this card from here and I'm going to
1:20:55
solo escribiré mi h1 cart y también pasaré mi tarjeta
just write my h1 cart and i'm going to also pass my card
1:20:58
emoji justo aquí debajo de eso estoy
emoji right in here now underneath that i'm
1:21:02
voy a renderizar condicionalmente mi interfaz de usuario así que solo revisaré como elementos
going to conditionally render my ui so i'll just check like items
1:21:05
longitud así que si la longitud de los elementos es mayor que
dot length so if the items dot length is greater than
1:21:08
cero y vamos a estar renderizando nuestro h2 así que
zero and we are going to be rendering our h2 so
1:21:11
solo usaré mi h2 aquí y voy a decir como tienes
i'll just use my h2 right here and i'm going to say like you have
1:21:14
um longitud de elementos estamos
um items dot length we're
1:21:17
verificando la longitud de nuestros elementos y luego los elementos en
going to be checking the length of our items and then items in
1:21:20
tu carrito así que si guardo mi archivo y
your cart so if i save my file and
1:21:23
aquí puedes ver que nos dará como tienes cuatro elementos dentro
here you can see it's going to give us like you have four items inside
1:21:26
tu tarjeta así que si solo elimino como uno de ellos voy a
your card so if i just remove like one of them i'm going to just
1:21:30
eliminar de la misma manera archivo ahora nos dará como tienes tres elementos
remove the same way file now it's going to give us like you have three items
1:21:33
dentro de tu tarjeta y ahora si elimino completamente
inside your card and now if i completely remove
1:21:36
cada cosa de esta tarjeta así que ahora esta condición es
every single thing from this card so now this condition is
1:21:39
falsa como items.length ya no es mayor que cero es igual a cero así que no vamos a obtener este resultado aquí así que si digo allí y solo nos dará la tarjeta
false like items.length is no longer greater than zero it is equal to zero so we're not going to be getting this result right here so if i say over there and it's going to only give us the card
1:21:50
que proviene de este h1 pero no nos dará esto
which is coming from this h1 but it's not going to give us this
1:21:53
resultado como puedes ver aquí así que si solo deshago eso y
result as you can see right here so if i just undo that and
1:21:56
déjame solo obtener ese banco enviar mi archivo y ahora estamos obteniendo como tienes
let me just get that bank send my file and now we are getting like you have
1:21:59
cuatro elementos dentro de tu tarjeta ahora debajo de eso
four items inside your card now underneath that
1:22:03
voy a renderizar mis elementos aquí así que solo usaré
i'm going to just render my items right here so i'll just use
1:22:06
como ul y ahora dentro de este ul voy a proporcionar mi h4 y solo proporcionemos como productos o algo así ahora debajo de este h4 voy a entrar en mi
like ul and now inside this ul i'm going to provide my h4 and let's just provide like products or something like that now underneath this h4 i'm going to go into my
1:22:16
JavaScript una vez más y voy a estar usando items.map
JavaScript once again and I'm going to be using items.map
1:22:19
método y aquí vamos a estar pasando nuestro elemento específico y
method and here we are going to be passing our specific item and
1:22:22
ahora dentro de allí vamos a estar pasando nuestro li y que solo
now inside there we are going to be passing our li and which will just
1:22:26
di como el artículo justo aquí y nos vamos
say like item right here and we are going
1:22:29
también vamos a pasar una clave a eso, así que para la clave solo usaré como clave
to be also passing a key to that so for the key I'll just use like key
1:22:32
mat.random y ahora si guardo mi archivo y
mat.random and now if I save my file and
1:22:35
aquí puedes ver que ahora estamos obteniendo nuestro artículo justo aquí como tenemos un banco de energía de auriculares inalámbricos, un nuevo SSD, apúrate y cosas así
here you can see we are now getting our item right here like we have a wireless earbuds power bank new ssd hurry and stuff like
1:22:41
pero si elimino cada cosa
there but if i remove every single thing
1:22:45
desde aquí, archivo semi, solo estamos obteniendo estos productos, no
from here semi file we are only getting these products we
1:22:48
estamos obteniendo nuestro artículo, eso es porque estamos
are not getting our item that's because we are
1:22:51
no renderizando nada aquí porque nuestra tarjeta está totalmente vacía y
not rendering anything right here because our card is totally empty and
1:22:55
tampoco estamos obteniendo nada, eso es porque esta condición
we are also not getting anything that's because this condition
1:22:58
es falsa, así que si esta condición es falsa, no vamos a obtener
is false so if this condition is false we are not going to be getting
1:23:01
esta interfaz de usuario, es hora de abordar el desafío de renderizado condicional, así que
this ui time to tackle the conditional rendering challenge so
1:23:04
lo primero que quiero que hagas es que quiero que crees un weather.jsx
the first thing that i want you to do is that i want you to create a weather.jsx
1:23:08
archivo y dentro de ese archivo vas a crear un componente funcional
file and inside that file you're going to be creating a functional component
1:23:11
con el nombre de weather y tomará la propiedad de temperatura
with the name of weather and it will take the prop of temperature
1:23:14
y luego quiero que uses la declaración if, else if y else para renderizar condicionalmente diferentes mensajes según el valor de temperatura que vamos a especificar en unos segundos.
and then I want you to use the if else if and else statement to conditionally render different messages based on the temperature value which we are going to be specifying in a few seconds.
1:23:24
Así que si la temperatura está por debajo de 15, muestra que hace frío afuera
So if the temperature is below 15 display it's cold outside
1:23:27
y si la temperatura está entre 15 y 25, entonces muestra que hace buen tiempo afuera, y si la temperatura está por encima de 25, entonces muestra que hace calor afuera.
and if the temperature is between 15 and 25 then display it's nice outside and if the temperature is above 25 then display like it's hot outside.
1:23:37
Así que esa va a ser la primera parte de este desafío. Ahora, en el segundo desafío que tenemos que hacer es que tenemos que crear un componente de estado de usuario y dentro de ese componente también tomará dos propiedades booleanas.
So that's going to be the first portion of this challenge. Now in the second challenge that we have to do is that we have to create a user status component and inside that component it will also take two boolean prop.
1:23:47
La primera será 'logged in' y la segunda será 'is admin'.
The first one will be logged in and the second one will be is admin.
1:23:52
Así que usa el operador AND para mostrar el mensaje para el administrador y también para el usuario normal.
So use the end operator to display the message for admin and also for the normal user as well.
1:23:59
Así que si el inicio de sesión y también el 'is admin', ambas propiedades son verdaderas, lo que significa que la persona es administrador, entonces quiero que
So if the log in and also the is admin both of these props are true which means like the person is admin so then I want you
1:24:06
muestren algo como 'bienvenido administrador', así que si no es el caso
display like welcome admin so if that's not the case
1:24:10
y si solo el inicio de sesión es verdadero, entonces muestra algo como
and if only the login is true then display like
1:24:13
'bienvenido usuario', así que esa va a ser la segunda parte, ahora para
welcome user so that's going to be the second portion now for
1:24:16
la final, tienes que crear un archivo greetings.jsx
the final one you have to create a greetings.jsx file
1:24:19
dentro del archivo vas a crear un componente funcional con el
inside the file you're going to be creating a functional component with the
1:24:22
nombre de saludos y también tomará, eh, cómo lo llamamos
name of greetings and it will also take uh what do we call
1:24:25
la propiedad del momento del día que puedes proporcionar como mañana, tarde o noche o algo así como día, entonces quiero que uses el ternario
the prop of time of the day you can provide like morning or afternoon or evening or something like day then i want you to use the ternary
1:24:32
operador, así que si el momento del día es igual a mañana, entonces
operator so if the time of the day is equal to morning then
1:24:36
muestra buenos días, así que si el momento del día es igual a la tarde
display good morning so if the time of the day is equal to afternoon
1:24:40
entonces muestra buenas tardes y finalmente solo tienes que
then display good afternoon and finally you have to just
1:24:43
importar todo ese componente dentro del app.jsx
import all of that component inside the app.jsx
1:24:46
y revisa el resultado de allí, así que dale tu
and check out the result of there so give it your
1:24:49
mejor intento, si puedes hacerlo, está completamente bien, entonces vuelve y
best shot if you can do it that's completely okay then come back and
1:24:52
mira la solución y ahora te voy a dar mi solución, así que lo que voy a hacer es definir mi componente weather.jsx y vamos a usar nuestro RAFC dentro de allí.
watch the solution and now i'm going to give you my solution so what i'm going to do is that i'm going to define my weather.jsx component and and we are going to be using our RAFC inside there.
1:25:02
Podemos definir como let temp y temp será igual a 226 para el primero. Está bien. Y ahora aquí lo primero que tenemos que hacer.
We can define like let temp and temp will be equals 226 for the first one. Okay. And now here the first thing that we have to do.
1:25:09
O sabes qué? Ni siquiera tenemos que proporcionar todo eso. Simplemente eliminemos eso de aquí. Vamos a usar nuestra declaración if else y else.
Or you know what? We don't even have to provide all of that. Let's just remove that from here. We're going to be using our if elsef and else statement.
1:25:16
Así que simplemente proporcionemos la condición como temp. Así que si la temperatura es menor que 15.
So let's just provide for the condition like temp. So if the temperature is less than 15.
1:25:21
Así que en esta situación, vamos a renderizar lo que llamamos. Hace frío afuera.
So in this situation, we're going to be rendering what we call it. It's cold outside.
1:25:27
Está bien, y si ese no es el caso, ¿qué tenemos que hacer? Tenemos que verificar la temperatura.
OK, and if that's not the case, so what do we have to do? We have to check for the temperature.
1:25:33
Si la temperatura es mayor o igual a 15 y la temperatura, vamos, la temperatura es menor o igual a 25.
If temperature is greater than or equal to 15 and temperature, come on, temperature is less than or equal to 25.
1:25:41
Así que en esta situación, vamos a renderizar este H1 una vez más. Y dirá como que hace buen tiempo afuera.
So in this situation, we're going to be rendering this H1 one more time. And it will say like it's nice outside.
1:25:48
está bien y finalmente si eso no es igual a nada
okay and finally if that is not equal to anything
1:25:52
así que solo vamos a devolver, pero sabes qué, también
so we are going to be just returning but you know what we also
1:25:55
tenemos que especificar eso else if una vez más y
have to specify that else if one more time and
1:25:58
para esta condición vamos a proporcionar como si la temperatura es mayor
for this condition we're going to be providing like if temperature is greater
1:26:02
que 25, así que en esta situación vamos a devolver
than 25 so in this situation we're going to be returning
1:26:05
sobre h1 una vez más y diremos como que hace
over h1 one more time and we will say like it's
1:26:08
calor afuera, está bien, así que ahora voy a guardar mi archivo y luego tenemos que registrar este componente dentro de nuestro archivo f.tsx, así que solo usaré
hot outside okay so now i'm going to save my file and then we have to register this component inside our f.tsx file so i'll just use
1:26:16
como weather tsx canción o jsx para ser precisos, así que voy a guardar mi archivo y revisar esto, así que nos dará como que hace calor afuera, pero ahora si cambio allí a como no sé, tal vez 15
like weather tsx song or jsx to be precise so i'm going to save my file and check this out so it's going to give us like it's hot outside but now if i change there to like i don't know maybe 15
1:26:29
y ahora si guardo mi archivo, así que aquí puedes ver que nos dará como que hace buen tiempo afuera.
and now if i save my file so here you can see it's going to give us like it's nice outside
1:26:34
y ahora si cambio eso a como no sé, tal vez, uh tres
and now if i change there to like i don't know maybe uh three
1:26:37
sería bueno, así que si cambio eso a tres, nos va a dar como que hace frío afuera, así que esa fue la primera parte de esto
would be fine so if i change that to three so it's going to give us like it's cold outside so that was the first portion of this
1:26:44
desafío y ahora lo siguiente que tenemos que hacer es que tenemos que crear
challenge and now the next thing that we have to do is that we have to create
1:26:47
nuestro usuario user status.jsx
our user user status.jsx
1:26:51
componente, así que voy a usar mi RAFCE dentro de ahí
component so I'm going to be using my RAFCE inside there
1:26:54
y también voy a ir a mi aplicación y solo vamos a comentar esta línea y voy a renderizar mi componente de estado de usuario
and also I'm going to go into my app and let's just comment this line out and I'm going to render my user status component
1:27:01
y va a tomar dos props, así que va a tomar como logged
and it's going to take two props so it's going to take like logged
1:27:05
en y voy a establecer eso en verdadero y luego es admin y también voy a establecer eso en falso, voy a guardar mi archivo y ahora
in and I'm going to set there to true and then is admin and I'm going to also set there to false I'm going to save my file and now
1:27:12
déjame ir y usar esas props dentro de este componente, así que
let me go ahead and use those props inside this component so
1:27:16
vamos a tomar las props y solo vamos a proporcionar nuestro
we are going to be just taking the props and let's just provide our
1:27:19
chequeo, así que voy a eliminar eso de aquí y vamos a estar verificando
check so i'm going to remove that from here and we're going to be checking
1:27:22
ahí si prop.logged en l-o-d-g-e-d
there if prop.logged in l-o-d-g-e-d
1:27:26
conectado y props.isadmin
logged in and props.isadmin
1:27:30
así que en esa situación vamos a estar retornando como h1 que
so in that situation we're going to be returning like h1 which
1:27:33
dirá como bienvenido admin porque, uh, si el usuario ya está conectado y si el usuario también es admin, así que vamos a estar mostrando como bienvenido
will say like welcome admin because uh if the user already logged in and if the user is also in admin so we're going to be showing like welcome
1:27:41
admin, así que si ese no es el caso, solo vamos a
admin so if that's not the case so we are going to be only
1:27:44
mostrar como h1 que dirá como bienvenido
showing like h1 which will say like welcome
1:27:48
normal o bienvenido
normal or welcome
1:27:51
usuario, así que voy a guardar este archivo ahora mismo y
user okay so i'm going to save this file right now and
1:27:55
ya nos registramos ahí mismo, así que aquí puedes ver que nos va a dar como bienvenido
we already registered there right here so here you can see it's going to give us like welcome
1:27:58
usuario y ¿por qué es eso? porque conectado está
user and why is that because logged in is
1:28:01
establecido en verdadero, pero es admin está establecido en falso, así que por eso ahora estamos obteniendo como bienvenido usuario, pero si cambio eso en lugar de un falso, lo voy a cambiar a verdadero y guardar mi archivo.
set to true but is admin is set to false so that's why we are now getting like welcome user but if i change that instead of a false i'm going to change that to true and save my file.
1:28:11
Ahora nos va a dar bienvenido admin aquí mismo. Así que esa fue la segunda parte de nuestro desafío.
Now it's going to give us welcome admin right here. So that was the second portion of our challenge.
1:28:16
Y ahora para el tercero y último, vamos a estar creando nuestro componente greeting.jsx.
And now for the third and final one, we are going to be creating our greeting.jsx component.
1:28:21
Solo vamos a usar nuestro rafce. Guardar mi archivo y registrarme ahí mismo dentro de mi aplicación.
Let's just use our rafce.save my file and register there right here inside my app.
1:28:28
Así que solo usaré saludos y cerraré allí. También tomará la hora del día adecuada y lo estableceré en la mañana.
So I'll just use like greetings and close there. It's going to also take the proper time of day and I'm going to set it to morning.
1:28:36
Y vamos a ir a nuestro componente dentro de este componente, vamos a recibir nuestras props una vez más
And let's just go ahead and go to our component inside this component we are going to be receiving our props once again
1:28:43
y en lugar de proporcionar esta declaración de retorno, vamos a usar nuestro ternario
and instead of providing this return statement we're going to be using our ternary
1:28:46
así que voy a usar como si props.timeofday
operator so i'm going to be using like if props.timeofday
1:28:50
es igual a la mañana, así que
is triple equals to morning so
1:28:53
en esta situación vamos a renderizar nuestro h1 esto
in this situation we are going to be rendering our h1 this
1:28:56
está bien en nuestro h1, maldita sea, ¿qué demonios estoy haciendo y
is right to our h1 god damn what the hell am i doing and
1:29:00
que dirá como buenos días y si eso es
which will say like good morning and if that's
1:29:03
no el caso, vamos, si eso es
not the case come on if that's
1:29:06
no el caso, así que vamos a renderizar h1 una vez más
not the case so we going to be rendering h1 one more time
1:29:09
y que dirá como eh buenas tardes
and which will say like uh good afternoon afternoon
1:29:13
y voy a guardar mi archivo y también tenemos
and i'm going to save my file and we also have
1:29:16
que regresar allí, así que vamos a revisar esto aquí
to return there so let's just check this out here
1:29:19
puedes ver que nos va a dar buenos días, eso es porque ahora estamos proporcionando
you can see it's going to give us good morning that's because we are now providing
1:29:22
la hora del día es la mañana, pero
the time of the day is morning but
1:29:26
si cambio eso a como eh tarde, ven
if i change that to like uh afternoon come
1:29:29
en la tarde y guarda mi archivo, así que es
on afternoon and sell my file so it's
1:29:32
va a darnos como buenas tardes, así que déjame ir allí y
going to give us like good afternoon so let me go there and
1:29:35
también podemos desestructurar nuestras props, así que podemos simplemente desestructurar
we can also destructure our prompts so we can just uh destructure
1:29:38
como la hora del día, copia allí y nosotros
like time of day copy there and we
1:29:42
ya no tenemos que proporcionar nuestro prompt dart, así que simplemente
no longer have to provide our prompt dart so let's just
1:29:45
guarda allí y todavía nos dará ese mismo resultado, ¿verdad?
save there and it's going to still give us that same result right
1:29:48
aquí, así que sí, ese fue nuestro desafío sobre
here so yeah that was our challenge about
1:29:51
eh, maldita sea, ese fue nuestro desafío
uh god damn it that was our challenge
1:29:54
sobre el renderizado condicional en react.js allí
about the conditional rendering in react.js there
1:29:57
hay muchas formas de estilizar nuestro componente, pero en esta sección específica
are a lot of ways to style our component but in this specific
1:30:01
vamos a aprender solo sobre lo básico, pero más adelante
section we are going to be only learning about the basics but later
1:30:04
en este curso también vamos a aprender sobre las bibliotecas populares como
in this course we are going to be also learning about the popular libraries like
1:30:07
redux y desu y telman css shardson
redix and desu y telman css shardson
1:30:10
ui y cosas así, pero por ahora solo vamos a aprender sobre
ui and stuff like that but for now we are going to be only learning about
1:30:14
los fundamentos del estilo, así que lo que voy a hacer es
the basics of styling so what i'm going to do is i'm going
1:30:17
crear mi sección y dentro de esta sección voy a escribir mi estilo en línea para h1 y si guardo mi archivo, aquí puedes ver que ahora estamos
to just create my section and inside this section i'm going to just write my h1 inline style and if i save my file and here you can see we are now
1:30:24
obteniendo nuestro estilo en línea aquí, lo cual se ve increíble, así que
getting our inline style right here which is looking amazing so
1:30:27
si quiero cambiar el color de eso o si quiero proporcionar algún tipo de un
if i want to change the color of that or if i want to provide some sort of a
1:30:30
estilo para eso, así que solo puedo usar un atributo de estilo
styling for that so i can just use a style attribute
1:30:33
y igual a y luego llaves dobles
and equal to and then double curly
1:30:36
no una sola, sino llaves dobles, debes
brace not a single but double curly braces you
1:30:39
tener eso en mente, primero que nada vas a abrir
have to keep that in mind first of all you're going to be opening
1:30:42
tus llaves, vas a abrir llaves dobles y
your curly braces you're going to be opening double curly braces and
1:30:45
luego vas a cerrar llaves dobles y ahora dentro de ahí puedes escribir todos tus estilos aquí que ya has aprendido
then you are going to be closing double curly braces and now inside there you can write like all of your c's are styling right here which you've already learned
1:30:53
en mis cursos de html y css, así que solo escribiré
in my html and css courses so i'll just write like
1:30:56
color y solo escribiré como um negro, uh no
color and i'm going to just write like um black uh not
1:31:00
negro, sino rojo, así que si guardo ahí
black but uh red so if i save there
1:31:03
y aquí puedes ver que ahora estamos obteniendo nuestro color rojo aquí, lo cual se ve increíble
and here you can see we are now getting our red color right here which is looking amazing
1:31:07
y ahora también voy a proporcionar un color de fondo, pero hay
and now i'm going to also provide a background color to it but there are
1:31:10
algunas cosas que debes tener en cuenta, en css escribimos
a few things that you have to keep in mind in css we write
1:31:13
nuestro color de fondo así, primero que nada escribimos un fondo
our background color like this first of all we write a background
1:31:16
y luego guion y luego color, pero esto no es un
and then dash and then color but this is not a
1:31:19
css, actualmente no estás trabajando con el css, estás trabajando con
css you are not currently working with the css you are working with
1:31:23
react.js, así que debes tener en cuenta que vas a
the react.js so you have to keep in mind that you're going
1:31:26
escribir tu css en una línea como un fondo
to be writing your css in one line like a background
1:31:29
color, pero esto no es preciso aquí puedes ver
color but this is not accurate here you can see
1:31:32
también estamos recibiendo esta sugerencia como el color de fondo es
we are also getting this suggestion like background color is
1:31:36
un camel case, así que si hago clic en eso, cada vez que tenemos algún
a camel case so if i click on that anytime we have some
1:31:39
tipo de propiedad que tiene dos nombres como fondo y también el color, así que no vamos a proporcionar espacios, no vamos a proporcionar
sort of a property which have two names like background and also the color so we are not going to be providing spaces we are not going to be providing
1:31:46
guiones y tampoco se nos permite escribir eso en minúsculas
dashes and we are also not allowed to write that in lowercase
1:31:50
o en mayúsculas totales, tenemos que escribir eso como
or in totally uppercase we have to write that as
1:31:53
una sola palabra y también tenemos que escribir eso como un camel
a one word and also we have to write that as a camel
1:31:56
case, así que ahora voy a poner un valor para
case just like this and now i'm going to just put a value for
1:31:59
eso, así que solo usaré como trato y también voy a proporcionar un poco de
that so i'll just use like deal and i'm going to also provide a bit of
1:32:02
relleno para ello, así que el relleno será 2rem o algo así y
padding to it so padding will be 2rem or something like that and
1:32:05
sí, voy a guardar mi archivo y aquí puedes ver que ahora estamos obteniendo
yeah i'm going to save my file and here you can see we are now getting
1:32:09
nuestro estilo justo aquí, voy a cambiar el color de eso a
our styling right here i'm going to just change the color of that to
1:32:12
como blanco y ahora se ve mejor, así que así es como vamos a
like white and now that's looking better so this is how we are going to
1:32:15
proporcionar el estilo de palabra en línea, así que primero tienes que
be providing word styling inline so first of all you
1:32:18
freír un atributo de estilo y luego doble llave de apertura
have fried a style attribute and then double curly brace
1:32:21
y doble llave de cierre y
is opening and double curly brace is closing and
1:32:24
también tienes que tener en cuenta esta regla, así que esa fue
you also have to keep this rule in mind so that was
1:32:28
la primera forma, ahora también podemos extraer todo ese estilo
the first way now we can also extract all of that styling
1:32:31
de aquí y podemos poner algún tipo de objeto y
from here and we can put in some sort of an object and
1:32:34
luego podemos referenciar ese objeto dentro del estilo, así que voy a
then we can reference that object inside the style so i'm
1:32:37
ir a la parte superior y aquí solo voy a crear mi variable
gonna go to the top and here i'll just create my variable
1:32:41
con el nombre de estilos y solo voy a colocar mi estilo
with the name of like styles and i'm gonna just place my styling
1:32:44
justo aquí, pero primero tenemos que envolver eso dentro de esto
right here but first of all we have to wrap that inside this
1:32:47
llaves como un objeto y luego tenemos que colocar nuestro estilo
curly braces like as an object and then we have to place our styling
1:32:50
ahí voy a guardar mi archivo y voy a copiar la variable
there i'm going to save my file and i'm going to copy the variable
1:32:54
nombre de ahí y solo tenemos que colocar eso aquí pero en este
name from there and we have to just place that right here but in this
1:32:57
caso no vamos a escribir llaves dobles
case we are not going to be writing double curly braces
1:33:00
vamos a trabajar solo con llaves simples
we are going to be only working with the single curly braces
1:33:03
así que ahí está nuestra palabra javascript justo aquí ahora dentro de esto
so there's our javascript word right here now inside this
1:33:06
palabra javascript que ahora estamos renderizando o estilizando
javascript word we are now rendering or styling
1:33:10
totalmente de forma dinámica, así que si guardo mi archivo y aquí
totally dynamically so if i save my file and here
1:33:13
puedes ver que si solo actualizo, eso seguirá funcionando exactamente igual
you can see if i just refresh there that's going to still work exactly the
1:33:16
así que puedo cambiar el color de eso a como uh carmesí
same so i can just change the color of that to like uh crimson
1:33:19
o algo así y aquí puedes ver que seguirá funcionando aquí
or something like that and here you can see it's going to still work right here
1:33:22
así que esa fue la segunda forma de estilizar nuestro componente ahora
so that was the second way to style our component now
1:33:25
déjame mostrarte una forma más, así que voy a eliminar todo su contenido de aquí
let me show you one more way so i'm going to just remove all of their content from here
1:33:29
y también este h1, así que si guardo mi archivo y ahora
and also this h1 so if i save my file and now
1:33:32
voy a entrar allí, voy a eliminar esta carpeta de componentes de
i'm going to go in there i'm going to remove this component folder from
1:33:35
aquí y voy a crear mi archivo que será index.css
here and i'm going to create my file which will will be index.css
1:33:38
archivo está bien y ahora dentro de este archivo index.css
file okay and now inside this index.css file
1:33:41
vamos a colocar todo nuestro css como el cuerpo se establecerá
we're going to be placing all of our css like body will be set
1:33:44
a este color y también estamos proporcionando un display flex y
to this color and also we are providing a display flex and
1:33:47
todas esas cosas que ya has aprendido en mi curso de css
all of that kind of stuff which you've already learned in my css
1:33:50
así que aquí puedes ver que ahora estamos proporcionando todo nuestro estilo ahora
course so here you can see we are now providing all of our styling now
1:33:53
voy a entrar en mi componente app.jsx y dentro
i'm going to go into my app.jsx component and inside
1:33:56
de eso ahora si quiero usar todo ese estilo, lo primero que tenemos
that now if i want to use all of that styling the first thing that we
1:33:59
que hacer es que tenemos que importarlo en este componente, así que solo voy a usar como import, luego tenemos que escribir una cadena y
have to do is that we have to import that in this component so i'm going to be just using like import then we have to write a string and
1:34:06
luego tenemos que subir un nivel, solo tenemos que escribir index.css
then we have to go one level up above we have to just write index.css
1:34:10
así que si guardo mi archivo y ahora si mantengo ctrl y hago clic
so if i save my file and now if i hold ctrl and click
1:34:13
ahí nos llevará a este index.css
on there it's going to bring us to this index.css
1:34:16
archivo aquí, así que ahora dentro de esta sección solo
file right here so now inside this section i'll just
1:34:20
usaré mi h1 y solo escribiré como un archivo separado
use my h1 and i'll just write like separate file
1:34:24
para estilos o algo así si guardo ahí y ahora estamos obteniendo este resultado aquí, así que ahora todos nuestros estilos se han aplicado con éxito a este componente, así que puedo comentar esta línea
for styling or something like this if i save there and now we are getting this result right here so now all of our styling are now successfully applied to this component so i can totally comment this line out
1:34:34
y ahora no nos dará ningún estilo y puedo descomentar totalmente
and now it's not going to give us any styling and i can totally uncomment
1:34:37
ahí y aquí puedes ver que ahora estamos obteniendo todos los cuatro estilos, así que
there and here you can see we are now getting all the four styling so
1:34:41
sí, así es como vamos a estilizar nuestro componente usando un
yeah this is how we are going to be styling our component by using an
1:34:44
objeto en línea y separado y también index.css
inline and separate object and also index.css
1:34:47
archivo y ahora hablemos sobre los íconos, como cómo vamos a
file and now let's talk about the icons like how we are
1:34:50
agregar íconos en nuestro proyecto para
going to be adding icons in our project to
1:34:53
hacer eso hay muchas bibliotecas de íconos para react.js
do that there are a lot of icons libraries for react.js
1:34:57
pero esta es un poco popular y esta es una
but this one is a bit popular one and this is a
1:35:00
biblioteca de íconos de react.js, así que primero tenemos que
react.js icon library so first of all we have
1:35:03
instalar esta biblioteca dentro de nuestro proyecto, luego podremos
to install this library inside our project then we will be
1:35:06
usar eso, así que ahora voy a ir a mis íconos de react y
able to use that so now i'm going to go into my react icons and
1:35:09
aquí puedes ver que tenemos como muchos, muchos
here you can see we have like a lot a lot
1:35:12
íconos aquí, así que para instalar eso vamos a
of icons right here so to install that we are going to
1:35:15
usar este comando, así que voy a copiar ahí, ahora voy a abrir mi terminal aquí y solo cerrar cada
be using this command so i'm going to just copy there now i'm going to open my terminal right here and just close every single
1:35:22
cosa, voy a colocar mi comando aquí que es npm
thing i'm going to just place my command right here which is npm
1:35:25
instalar react íconos -- así que si no
install react icons dash dash so if you don't
1:35:29
quieres proporcionar este -- así que ni siquiera tienes que hacer eso, está bien
want to provide this dash dash so you don't even have to do that okay
1:35:32
así que voy a presionar enter aquí, así que se instalará eso dentro de este
so i'm going to just hit enter right here so it's going to install that inside this
1:35:35
proyecto y aquí puedes ver que ahora está instalado con éxito y
project and here you can see that's now successfully installed and
1:35:38
como mencioné al principio de este video, si instalamos
as i mentioned in the beginning of this video that if we install
1:35:41
cualquier biblioteca o paquete de terceros, eso estará disponible dentro de este módulo de nodo, así que puedo buscar totalmente el ícono de react, así que sabes, si solo busco los íconos
any third-party libraries or packages that's going to be available inside this node module so i can totally search for the react uh icon so you know if i just search for the icons
1:35:52
y aquí puedes ver que tenemos nuestros íconos de react justo aquí, así que
and here you can see we have our react icons right here so
1:35:55
si abro eso aquí puedes ver que tenemos muchos íconos
if i open that here you can see we have like a lot of icons
1:35:59
así que así es como vamos a agregar eso a nuestro proyecto y
so this is how we are going to be adding there to our project and
1:36:02
ahora hablemos sobre cómo vamos a usarlo dentro de nuestro proyecto, así que
now let's talk about how we are going to be using the inside of our project so
1:36:05
para usar eso, lo primero que tenemos que hacer es importarlo
to use that the first thing that we have to do is that we have to import that
1:36:08
el ícono específico que deseas usar, así que voy a
specific icon which you want to use so i'll
1:36:11
simplemente buscar un ícono específico, así que voy a ir a la página de inicio
just go ahead and search for a specific icon so i'm going to go to the home
1:36:14
hay muchos íconos, voy a buscar
there are a lot of icons i'm going to search for
1:36:18
el carrito y aquí puedes ver que nos va a dar muchos íconos
the cart and here you can see it's going to give us a lot of cards
1:36:21
justo aquí, supongamos que quiero usar este ícono, voy a hacer clic allí ahora
right here let's suppose if i want to use this card i'm going to click on there now
1:36:24
puedo copiarlo totalmente y aquí puedes
i can totally copy there and here you can
1:36:28
ver que así es como vamos a importar eso y ahora podemos usarlo totalmente
see this is how we are going to be importing there and now we can totally use
1:36:31
eso usando este ícono, así que voy a copiarlo desde aquí ahora
that by using this icon so i'm going to copy that from here now
1:36:35
déjame colocarlo aquí mismo, guardar mi archivo y ahora si voy allí, actualizar, tenemos que ejecutar nuestro terminal, así que npm run dev
let me just place there right in here save my file and now if i go there refresh there we have to run our terminal so npm run dev
1:36:45
ahora si actualizo eso, aquí puedes ver que ahora estamos obteniendo nuestro ícono, puedo buscar algo
now if i refresh that so here you can see we're now getting our icon i can search for something
1:36:50
más como no sé, computadora o algo así
else like i don't know computer or something
1:36:53
nos va a dar esta computadora, puedo copiarlo totalmente
it's going to give us this computer i can totally copy there
1:36:57
voy a ir a la parte superior
i'm going to go to the top
1:37:00
y voy a colocarlo justo aquí, voy a copiar
and i'm going to just place it right here i'm going to copy
1:37:03
desde allí, ahora déjame colocar esto aquí
it from there now let me just place the here
1:37:06
y cerrar la verificación del archivo semicolon
and close the semi file check
1:37:10
lo sacamos y ahora estamos obteniendo nuestra computadora justo aquí, así que sí, eso fue todo sobre el estilo y también sobre los íconos, bienvenidos a En este desafío, quiero que crees un archivo stylecard.jsx.
it out and we are now getting our computer right here so yeah that was it about the styling and also about the icons welcome to In this challenge, I want you to create a stylecard.jsx file.
1:37:21
Dentro de eso, vas a definir el componente funcional con el nombre de stylecard. Usa el estilo en línea.
Inside there, you are going to be defining the functional component with the name of stylecard. Use the inline style.
1:37:27
Aquí la palabra clave es usar el estilo en línea para estilizar tu componente.
Here the keyword is use the inline style to style your component.
1:37:31
Al usar el estilo en línea, tienes que cambiar el color de fondo a azul claro.
By using the inline style, you have to change the background color to light blue.
1:37:35
También proporciona un espaciado de 20 píxeles, un radio de borde de 10 píxeles y también cambia el color del texto a azul oscuro.
Also provide a pairing of 20 pixels, a border radius of 10 pixels, and also change the color of the text to dark blue.
1:37:44
Así que esa va a ser la primera parte de este desafío. Y ahora, para la segunda parte, vamos a crear nuestra tarjeta de perfil.
So that's going to be the first portion of this challenge. And now for the second portion, we are going to be creating our profile card.
1:37:50
Y ahora, dentro de este componente de tarjeta de perfil, vamos a definir nuestro estilo utilizando el objeto.
And now inside this profile card component, we are going to be defining our style by using the object.
1:37:55
Y aquí la palabra clave es el objeto. Así que dentro de ese objeto, vamos a definir nuestro estilo.
And here the keyword is the object. So inside that object, we are going to be defining our style.
1:38:01
Como el color de fondo se establecerá en gris claro. El espaciado se establecerá en 15 píxeles. El radio del borde se establecerá en 8 píxeles.
Like the background color will be set to light gray. The pairing will be set to 15 pixels. Board radius will be set to 8 pixels.
1:38:07
Y el color del texto se establecerá en negro total. Bien, así que aplica esos estilos utilizando el comando.
And text color will be set to totally black. Okay, so apply those styling by using command.
1:38:13
css en línea y también utilizando el objeto, está bien.
inline css and also by using the object okay
1:38:17
y luego, finalmente, para la última parte, vas a instalar los
and then finally for the final portion you're going to be installing the
1:38:20
iconos de react utilizando este comando y luego tú
react icons by using this command and then you
1:38:23
tienes que renderizar este icono fabr que se va a emitir.
have to render this fabr icon that's going to be aired
1:38:26
también puedes proporcionar el tamaño allí como 30 píxeles.
you can also provide the size to there like 30 pixel
1:38:29
y también puedes cambiar el color y sí, finalmente, tienes que renderizar dentro de tu componente de aplicación o registrar dentro de tu componente de aplicación para que puedas ver el resultado, así que ahora déjame simplemente crear mi componente aquí mismo.
and you can also change the color and yeah finally you have to render the inside your app component or register the inside your app component so you can see the result so now let me just go ahead and create my component right here.
1:38:42
Así que comenzaré definiendo el componente de estilo card.jsx. Esto es usar tu RAFCE.
So I'll start by defining the style card.jsx component. This is use your RAFCE.
1:38:48
Regresa y ve a mi componente de aplicación y dentro de allí vamos a registrar tu tarjeta de estilo así.
Go back and go to my app component and inside there we're going to be registering your style card like so.
1:38:55
Y dentro de esta tarjeta de estilo, la primera cosa que quiero hacer es mostrar todos estos estilos.
And inside this style card the first thing that I want to do is that I want to show all of these stylings.
1:39:01
Así que establece el color de fondo en azul claro y también pon un radio de relleno y cambia el color de allí.
So set the background color to light blue and also put a padding radius and change the color of there.
1:39:08
Así que voy a quitar estas cosas de aquí y proporcionar un estilo y usar mis dobles llaves dentro de allí.
So I'm going to remove this stuff from here and provide a style and use my double curly braces inside there.
1:39:15
Una vez que tengamos que cambiar el color de fondo, así que usaré como color de fondo y para el color de fondo vamos a proporcionar como azul claro y también tenemos que proporcionar el relleno y el relleno se establecerá en 20 píxeles.
Once we have to change the background color so I'll use like background color and for the background color we're going to be providing like light blue and also we have to provide the padding and padding will be set to 20 pixel.
1:39:27
Vamos a proporcionar también el radio del borde, no el borde derecho, sino r-a-d-i-u-s.
We're going to be all come on we're going to be also providing the border radius not border right but r-a-d-i-u-s
1:39:35
el radio del borde se establecerá en 10 píxeles y también vamos a proporcionar el color y el color se establecerá en azul oscuro.
border radius will be set to 10 pixels and we are going to be also providing the color and the color will be set to dark blue.
1:39:42
Así que voy a guardar mi archivo. También voy a proporcionar mi h1 que dirá algo como tarjeta de estilo.
So I am going to save my file. I am going to also provide my h1 which will say like style card.
1:39:50
También vamos a proporcionar un párrafo que dirá lorem 20 o tal vez lorem 30 estaría bien.
We are going to be also providing a paragraph which will say lorem 20 or maybe lorem 30 would be fine.
1:39:55
Así que si guardo mi archivo y ahora déjame verificar esto. Así que ahora estamos obteniendo este estilo combinado.
So if I save my file and now let me check this out. So we are now getting this style combined.
1:40:00
utilizando el estilo en línea. Así que eso se ve increíble. También voy a ir a mi carpeta de componentes una vez más.
by using the inline style. So that's looking amazing. I'm going to also go ahead and go to my components folder one more time.
1:40:07
Y vamos a definir nuestro profile card.jsx dentro de allí.
And we're going to be defining our profile card.jsx inside there.
1:40:12
Voy a usar mi RAFCE, ir a mi componente de aplicación y comentar esta línea. Oh, ya sabes, no voy a comentar esta línea.
I'm going to use my RAFCE, go to my app component and comment this line. Oh, you know, I'm not going to comment this line out.
1:40:19
Voy a estar usando una tarjeta de perfil y renderizar allí justo aquí dentro de este componente.
I'm going to be using a profile card and render there right here inside this component.
1:40:25
Ahora para este vamos a definir estos estilos. Primero tenemos que cambiar el color de fondo a gris claro.
Now for this one we are going to be defining these styles to it. First we have to change the background color to light gray.
1:40:30
También tenemos que proporcionar un espaciado, un radio de borde y también nuestro color de texto se establecerá en negro total.
We also have to provide a pairing, border radius and also our text color will be set to totally black.
1:40:36
Así que lo que voy a hacer es definir todo ese estilo usando mi objeto de estilo.
So what I am going to do is that I am going to define all of that styling by using my style object.
1:40:41
Así que usaré estilos y dentro de ahí vamos a proporcionar nuestro color de fondo. Simplemente proporcionemos nuestro gris claro allí.
So I will use like styles and inside there we are going to be providing our background color. Let's just provide our light gray inside there.
1:40:48
También vamos a proporcionar un espaciado que se establecerá en 15 píxeles.
We are going to be also providing a pairing which will be set to 15 pixels.
1:40:52
y el radio de borde se establecerá en agregar píxeles y simplemente proporcionemos un color y ese es el color predeterminado que se establecerá en negro
and the border radius will be set to add pixel and let's just provide a color and that's the default color which will be set to black
1:41:04
y ahora tenemos que usar el estilo dentro de nuestra tarjeta. ¿Cómo puedo hacer eso?
and now we have to use the styling inside our card. So how can I go about doing that?
1:41:09
Bueno, solo tenemos que agregar un estilo y una llave de apertura, no dos, sino solo una llave de apertura y tenemos que renderizar qué estilos dentro de ahí.
Well we just have to add a style and one curly braces not twice but only one curly braces and we have to render what styles inside there.
1:41:18
Voy a eliminar esta tarjeta de perfil y proporcionar mi H1 que dirá hola mundo.
I'm going to remove this profile card and provide my H1 which will say hello world.
1:41:23
Y ahora debajo de eso, simplemente proporcionemos nuestro párrafo que dirá algo como lorem de 30.
And now underneath that, let's just provide our paragraph which will say like lorem of 30.
1:41:28
Así que voy a guardar mi archivo y ahora estamos obteniendo una tarjeta gris y también esta tarjeta. Así que ambas cosas están completamente listas.
So I'm going to save my file and now we are getting a gray card and also this card. So both of these stuff are now totally done.
1:41:35
Lo siguiente que tenemos que hacer es instalar los íconos de react.
The next thing that we have to do is that we have to install the react icons.
1:41:39
Así que voy a detener mi servidor y voy a usar npm i o también puedes usar npm install si lo deseas.
So I'm going to stop my server and I'm going to be using npm i or you can also use npm install if you wanted to.
1:41:46
pero voy a usar npm i y luego react icons
but I'm going to use like npm i and then react icons
1:41:49
ahora están instalados con éxito así que voy a ejecutar mi servidor una vez
now they're successfully installed so I'm going to run my server once
1:41:52
de nuevo y entrar en mi carpeta de componentes y
again and go into my components folder and
1:41:56
definir otro componente que dirá como icon component.jsx
define another component which will say like icon component.jsx
1:42:01
así que usaré rafc dentro de ahí y aquí
so I'll use like rafc inside there and here
1:42:04
lo primero que tenemos que hacer es importar el componente fa o el componente fa br, así que vamos a obtenerlo de los íconos de react y lo vamos a obtener de FA.
the first thing that we have to do is that we have to import the fa component or fa br component so we are going to be grabbing there from the react icons and we are going to be grabbing there from the FA.
1:42:16
Así que solo usaré FA beer y lo voy a renderizar justo aquí dentro de este componente.
So I'll just use like FA beer and I'm going to render that right here inside this component.
1:42:22
Así que usaré FA beer y solo renderizaré eso aquí.
So I'll use like FA beer and just render that here.
1:42:27
Guarda mi archivo y ahora estamos obteniendo, oh no estamos obteniendo allí. Déjame refrescar allí. Deberíamos estar obteniendo allí.
Save my file and now we are getting, oh we are not getting there. Let me just refresh there. We should be getting there.
1:42:35
Oh no estamos. Oh, eso es porque no renderizamos nuestro componente aquí.
Oh we are not. Oh that's because we did not render our component here.
1:42:38
Así que voy a usar un componente de icono como icono
So I'm going to use like icon component icon
1:42:42
componente ahí vamos y guarda mi archivo y
component there we go and save my file and
1:42:45
ahora estamos obteniendo este icono de cerveza aquí como puedes
now we are getting this beer icon right here as you can
1:42:48
ver ahora déjame duplicar esta línea de código y estoy
see now let me just duplicate this line of code and I'm
1:42:51
también cambiando el tamaño de eso a como 30 guarda mi
going to also change the size of that to like 30 save my
1:42:54
archivo así que nos va a dar una cerveza un poco más grande ahora en este caso
file so it's going to give us like a bit bigger beer now in this case
1:42:57
también puedo cambiar el color de eso para proporcionar un atributo de color así que solo usaré como oro y guarda mi archivo y aquí puedes ver que ahora estamos obteniendo una cerveza dorada así que sí, eso fue todo sobre el desafío de estilo.
I can also change the color of that to provide a color attribute to it so I'll just use like gold and save my file and here you can see we are now getting a gold beer so yeah that was it about for the styling challenge.
1:43:09
Ahora hablemos sobre cómo vamos a agregar eventos a nuestros elementos.
Now let's talk about how we are going to be adding events to our elements.
1:43:13
Así que para hacer eso, primero vamos a crear nuestro componente de botón y
So to do that first of all we are going to be creating our button component and
1:43:18
ahora dentro de este componente de botón solo vamos a devolver un botón simple que solo dirá clic y ahora voy a renderizarlos dentro de mi aplicación.
now inside this button component we are going to be only returning just a simple button which will just say click and now I'm going to render them inside my app.
1:43:26
Así que solo usaré mi botón y guardaré mi archivo y aquí puedes ver que ahora estamos obteniendo nuestro botón de clic aquí que no está
So I'll just use my button and save my file and here you can see we are now getting our click button right here which is not
1:43:32
haciendo nada por ahora así que ahora si quieres adjuntar
doing anything for now so now if you want to attach
1:43:35
un controlador de eventos para este botón, lo primero que tenemos que hacer es que tenemos que escribir el on y aquí puedes ver que tenemos
an event handler for this button the first thing that we
1:43:38
muchos eventos como on a board on a board capture on
have to do is that we have to write the on and here you can see we have
1:43:41
animación en y hay muchos
a lot of events like on a board on a board capture on
1:43:45
uh eventos aquí en blood y cosas así, así que lo que
animation in and there are a lot of
1:43:48
uh eventos justo aquí sobre sangre y cosas así, así que qué
uh events right here on blood and stuff like that so what
1:43:51
voy a hacer es que voy a escribir mi propio controlador de eventos de clic y voy a pegar algún tipo de función justo aquí, así que ahora dentro de esta función
i'm going to do is that i'm going to just write my own click event handler and i'm going to just paste some sort of a function right here so now inside this function
1:43:58
puedo simplemente registrar en la consola como uh hiciste clic
i can just log to the console like uh you clicked
1:44:01
en mí y ahora voy a guardar mi archivo y ahora si
me and now i'm going to save my file and now if
1:44:04
abro mi consola justo aquí, ahora voy a hacer clic en este botón
i open my console right here now i'm going to click on this button
1:44:07
y nos va a dar como hiciste clic en mí justo aquí, ¿por qué es
and it's going to give us like you click me right here why is
1:44:10
eso? porque ahora estamos adjuntando este controlador de eventos y simplemente estamos registrando
that because now we are attaching this event handler and we are just logging
1:44:14
en la consola como hiciste clic en mí, también podemos extraer esta lógica a una función separada, así que voy a extraer eso de aquí y ahora solo podemos crear una función separada como const
to the console like you clicked me we can also extract this logic to a separate function so i'm going to extract that from here and now we can just only create a separate function like const
1:44:23
y clic y ahora podemos simplemente registrar en la consola algo
and click and now we can just log to the console something
1:44:27
como math punto redondear y luego math punto aleatorio y vamos a dividirlos por 10 o multiplicarlos por 10.
like math dot round and then math dot random and let's just divide them by 10 or multiply there by by 10.
1:44:37
así que si los guardo ahora voy a copiar ahí y vamos a pasar la referencia de esa función
so if i save them now i'm going to copy there and we are going to be passing the reference of that function
1:44:42
a este controlador de eventos al hacer clic así que si guardo ahí ahora si actualizo eso y cada vez que haga clic en este botón nos dará un número aleatorio entre uno y diez, está bien, así que sí, esto ahora está funcionando.
to this on click event handler so if i save there now if i refresh that and anytime i click on this button it's going to give us a random number between one through ten okay so yeah this is is now working.
1:44:53
Ese fue el primer ejemplo. Ahora déjame darte un ejemplo más. Así que para hacer eso, vamos a crear otro componente más.
That was the first example. Now let me give you one more example. So to do that, we are going to be creating yet another component.
1:45:00
Oh, sabes qué, déjame simplemente quitar ese componente de aquí y voy a crear mi
Oh you know what let me just remove that component from here and I'm going to create my
1:45:03
componente de copia y ahora dentro de ahí solo vamos a devolver solo el párrafo que dirá vamos, solo devolvamos un párrafo que tendrá como lorem de 20 y voy a guardar este archivo aquí.
copy component and now inside there we are going to be just returning only the paragraph and which will just say come on let's just return a paragraph which will just have like lorem of 20 and I'm going to save this file right here.
1:45:15
Ahora voy a adjuntar mi propio controlador de eventos de copia aquí y también vamos a crear esta función como controlador de copia
Now I'm going to attach my own copy event handler right here and we are going to be also creating this function like copy handler
1:45:22
en un segundo así que voy a copiar ahí y ahora déjame crear esta función dentro
in a second so i'm going to copy there and now let me just create this function inside
1:45:26
de este componente de copia así que solo usaré como const copia
this copy component so i'll just use like const copy
1:45:29
controlador y ahora dentro de ahí solo registraré en la consola
handler and now inside there i'll just log to the console
1:45:32
como deja de robar mi contenido así que
like stop stealing my content so
1:45:36
si guardo ahí y ahora si solo actualizo ahí estamos obteniendo algún tipo de error, eso es porque en lugar de ese botón tendré que proporcionar el copyright aquí, solo lo quitaré y cambiaré eso a
if i save there and now if i just refresh there we are getting some sort of error that's because instead of that button i'm going to have to provide the copyright here i'll just remove there and change there to
1:45:47
esa función de copia, componente de copia, vende mi archivo. Y ahora si solo los actualizo y aquí puedes ver que ahora estamos obteniendo nuestro texto.
that copy function, copy component, sell my file. And now if I just refresh them and here you can see we are now getting our text.
1:45:53
Pero si selecciono alguna porción de este texto, hago clic derecho ahí y copio, me dará esa advertencia como deja de robar mi contenido, lo cual se ve increíble.
But if I just select some portion of this text, right click on there and copy there, it's going to give us that warning like stop stealing my content, which is looking amazing.
1:46:02
Así que así es como vamos a trabajar con el controlador de eventos de copia. Ahora déjame darte un último ejemplo y supongo que eso será aquí.
So this is how we are going to be working with the on copy event handler. Now let me give you one more final example and I guess that's going to be here.
1:46:09
Así que solo quitaré ese componente de aquí. También voy a quitar esta copia de aquí y ahora déjame darte el movimiento.
So I'll just remove that component from here. I'm going to also remove this copy from here and now let me give you the move.
1:46:16
así que no película sino solo componente de movimiento y ahora
so not movie but just move component and now
1:46:19
dentro de ellos vamos a devolver una vez más
inside them we are going to be returning once again
1:46:22
o párrafo y ese párrafo tendrá el contenido
or paragraph and that paragraph will have the content
1:46:26
de como lorem 20 y ahora voy a adjuntar
of like lorem 20 and now i'm going to be attaching
1:46:29
mi propio movimiento del mouse, está bien, así que cuando alguien pase el mouse o se desplace sobre este texto, vamos a disparar algún tipo de evento, así que para hacer eso voy a proporcionar mi movimiento
my own mouse move okay so when somebody mouse over or hover over this text so we are going to be firing some sort of an event so to do that i'm going to just provide my move
1:46:40
función de controlador que vamos a crear en un segundo, ahora déjame crear esa función aquí mismo.
handler function which we're going to be creating in a second now let me just create that function right here.
1:46:46
Así que podemos crear eso usando esta palabra reservada de función o podemos crear eso usando la función de flecha.
So we can either create that by using this function reserved keyword or we can create that by using the arrow function.
1:46:51
Así que no tomará ningún perímetro y vamos
So it's not going to take any perimeter and we are
1:46:54
a alertar y solo diré como evento de movimiento del mouse disparado y ahora debajo de eso solo podemos registrar en la consola como evento de movimiento del mouse disparado.
going to be alerting and I'll just say like mouse move event fired and now underneath that we can just log to the console like mouse move event fired.
1:47:05
Esa misma cosa. Así que si guardo mi archivo y ahora si solo lo actualizo, pero primero tendrás que registrarlo dentro de nuestra aplicación.
That same thing. So if I save my file and now if I just refresh that but first of all you are going to also have to register that inside our app.
1:47:12
Así que vamos a registrarlo aquí mismo. Así que si guardo mi archivo y miro lo que sucede.
So let's just register there right here. So if I save my file and watch what happens.
1:47:18
Así que cada vez que paso el mouse por ahí, primero estoy recibiendo como un evento de movimiento del mouse activado.
So whenever I hover my mouse over to there, first of all I'm getting like mouse move event fired.
1:47:24
Si hago clic en Aceptar, también estamos recibiendo en la consola como un evento de movimiento del mouse activado.
If I click on OK, we are also getting in the console like mouse move event fired.
1:47:28
Así es como vamos a estar adjuntando diferentes tipos de eventos a nuestros elementos específicos.
So this is how we are going to be attaching different kind of events to our specific elements.
1:47:33
En esta sección voy a introducir dos temas a la vez. Primero vamos a aprender sobre el estado y luego vamos a saltar al hook.
In this section I'm going to be introducing two topics at once. First we are going to be learning about the stat and then we are going to be jumping into the hook.
1:47:40
Así que ahora hablemos sobre qué es un estado y por qué deberías preocuparte por eso.
So now let's talk about what is a stat and why you should even care about that.
1:47:44
Así que el estado es una forma de almacenar y gestionar los datos que pueden cambiar con el tiempo y afectar cómo se renderiza el componente.
So stat is a way to store and manage the data that can change over time and affect how the component renders.
1:47:50
Definimos el estado utilizando algo llamado el hook useState, que te permite establecer el valor inicial y proporcionar una forma de actualizar ese estado.
We define stat by using something called the use stat hook which allow you to set the initial value and provide a way to update that stat.
1:47:58
Así que esa fue solo una rápida definición de lo que es un estado, pero ahora aquí hay una palabra clave: el hook useState.
So that was just a quick definition of what a stat is but now here is a keyword the use stat hook.
1:48:03
Así que ahora, ¿qué es un hook y por qué deberías preocuparte por ellos? Los hooks son una nueva adición en React 16.8.
So now what is a hook and why you should even care about them. So hooks are a new addition in React 16.8.
1:48:10
Te permiten usar estado en otras características de React.js sin escribir componentes basados en clases.
They let you use state in other React.js features without writing a class-based components.
1:48:15
Así que en el pasado, no hace mucho tiempo, estábamos usando componentes basados en clases en todas partes.
So back in the day, not that long ago, we were using a class-based component like everywhere.
1:48:21
Hoy en día, solo usamos componentes basados en funciones y nadie usa un componente basado en clases.
Nowadays, we only use functional-based component and nobody use a class-based component.
1:48:26
Así que los hooks fueron introducidos en la versión 16 de React.js y te permiten gestionar tu estado dentro del componente funcional.
So hooks were introduced in the React.js 16 version and they allow you to manage your state inside the functional component.
1:48:34
Así que esa es la única teoría que tienes que tener en cuenta sobre los hooks. Y hay muchos hooks que vamos a cubrir a lo largo de esta serie.
So that's the only theory that you have to keep in mind about the hooks. And there are a lot of hooks which we are going to be covering throughout this series.
1:48:41
Pero ahora en esta sección, vamos a aprender sobre qué es un estado usado y cómo funciona. Así que ahora hablemos sobre qué es un estado usado.
But now in this section, we are going to be learning about what a used state is and how it works. So now let's talk about what is a used state.
1:48:48
Así que el hook useState nos permite rastrear el estado en el componente funcional.
So used state hook allows us to track the state in the functional component.
1:48:52
En cambio, generalmente se refiere a los datos o las propiedades que necesitan ser rastreadas en nuestra aplicación.
Instead, generally refer to the data or the properties that need to be tracking in our application.
1:48:58
Así que esa es la única cosa que tienes que tener en cuenta sobre el estado usado. Así que cómo se verá la sintaxis.
So that's the only thing that you have to keep in mind about the used state. So how the syntax will look like.
1:49:03
Así que aquí puedes ver que primero vamos a usar nuestro hook useState
So here you can see first of all we are going to be using our use state hook
1:49:06
y luego vamos a usar la desestructuración de arreglos y
and then we are going to be using the array t structuring and
1:49:10
primero tenemos un dato que vamos a proporcionar dentro de nuestro useState y luego tenemos una función que nos permite cambiar ese dato dentro de nuestro useState.
first of all we have a data which we are going to be providing inside our use state and then we have a function which allows us to change that data inside our use state.
1:49:19
Está bien, así que sabes que eso es mucha teoría, ahora déjame escribir algo de código y luego sabrás de qué estoy hablando.
Okay so you know what that's a lot of theory now let me just write some code and then you will get to know what I'm talking about.
1:49:25
ahora hablemos sobre el estado y el hook useState, así que para hacer eso primero
now let's talk about the stat and the use stat hook so to do that first
1:49:28
en primer lugar, tenemos que importar el use stat en nuestro
of all we have to import the use stat in our
1:49:31
proyecto, así que así es como vamos a importar allí y ahora vamos a usar
project so this is how we are going to be importing there and now let's use
1:49:34
el use stat hook dentro de nuestro proyecto, así que voy a usar como const
the use stat hook inside our project so i'm going to be using like const
1:49:37
contador y eso va a ser igual al use stat y el valor inicial se establecerá en cero, está bien, y ahora solo voy a registrar este contador en la consola, así que si guardo mi archivo y aquí puedes ver que ahora estamos obteniendo dos cosas
counter and that's going to be equals to the use stat and the initial value will be set to zero okay and now i'm going to just log this counter to the console so if i save my file and here you can see we are now getting two things
1:49:49
La primera cosa que estamos obteniendo es el valor inicial que especificamos dentro de este uso directo aquí.
The first thing that we are getting is the initial value which we specified inside this use straightforward here.
1:49:55
Y la segunda cosa que estamos obteniendo es una función que nos permitirá cambiar este valor inicial.
And the second thing that we are getting is a function which will allows us to change this initial value.
1:50:01
Así que si especifico como mi propio nombre como HosenWebDev y voy a guardar allí y si solo actualizo allí, ¿qué estoy obteniendo?
So if I specify like my own name like HosenWebDev and I'm going to save there and if I just refresh there what am I getting?
1:50:08
Estoy obteniendo HosenWebDev como mi nombre, que es el valor inicial para mi estado y también estoy obteniendo esta función que me permitirá cambiar este valor.
I'm getting HosenWebDev as my name which is the initial value for my state and I'm also getting this function which will allow me to change this value.
1:50:16
Así que tienes que tener eso en mente. Así que la mejor y la convención donde usar este use state es desestructurando allí usando la desestructuración de arreglos.
So you have to keep that in mind. So the best and the convention where to use this use state is to destructure there by using the array destructuring.
1:50:24
¿Por qué es eso? Porque esto no es un objeto. Esto es un arreglo.
Why is that? Because this is not an object. This is array.
1:50:28
Así que en esta situación, vamos a usar la desestructuración de arreglos para desestructurar nuestro valor inicial y también esta función.
So in this situation, we are going to be using the array destructuring to destructure our initial value and also this function.
1:50:35
Así que vamos a desestructurar este valor inicial para usarlo en algún lugar y también vamos a desestructurar esta función para cambiar el valor de este estado.
So we are going to be destructuring this initial value to use this somewhere and we are going to be also destructuring this function to change the value of this state.
1:50:43
Así que lo que voy a hacer es que voy a eliminar este contador y voy a usar la sintaxis de desestructuración de arreglos aquí mismo.
So what I'm going to do is that I'm going to just remove this counter and I'm going to be using the array destructuring syntax right here.
1:50:49
Así que ahora aquí puedes pasar cualquier cosa que quieras, pero
So now here you can pass anything that you want but
1:50:52
en mi caso, solo le voy a dar el nombre de como contador y luego tenemos que
in my case i'm going to just give it the name of like count and then we have to
1:50:55
proporcionar la coma y también vamos a desestructurar eso
provide the comma and we're going to be also destructuring that
1:50:58
la función también, así que para desestructurar eso, la convención
function as well so to destructure that the convention
1:51:01
es usar el set y luego proporcionar el nombre para
is to use the set and then provide the name for
1:51:05
tu valor inicial y así que ahora en este caso especificamos este
your initial value and so now in this case we specify this
1:51:08
contador, así que vamos a pasar nuestro contador aquí, así que si estuvieras pasando algún tipo de manzana tal vez, así que vamos a pasar
count so we are going to be passing our count right here so if you were like passing some sort of a apple maybe so we're going to be passing
1:51:16
como set manzana, así que esto es solo una convención
like set apple so this is just a convention
1:51:19
si quieres seguirlo, puedes hacerlo, pero no tienes que hacerlo
if you want to follow there you totally can but you don't have to
1:51:22
esto debería ser una manzana, ahí vamos
this should be an apple there we go
1:51:25
así que ahora estoy trabajando con mi contador, así que solo voy a
okay so now i'm working with my account so i'm going to just
1:51:28
espaciar mi contador aquí y luego la convención que voy a seguir
space my account right here and then the convention i'm going to follow
1:51:31
será el conteo establecido, ahí vamos y
will be the set count there we go and
1:51:35
el valor inicial que voy a especificar solo será cero aquí dentro y ahora, si guardo, lo siguiente que quiero hacer es renderizar lo que tengo actualmente dentro de este estado.
the initial value i'm going to specify only zero right here inside there and now if i save there the next thing that i want to do is that i want to render what i currently have inside this stat.
1:51:45
Así que voy a escribir mi h1 y aquí solo pasaré mi variable de conteo que ahora estamos desestructurando de nuestro estado usado.
So I'm going to just write my h1 and here I'll just pass my count variable which we are now destructuring from our used stat.
1:51:52
Así que si guardo y como pueden ver aquí, ahora estamos obteniendo el cero que se ve increíble.
So if I save there and as you can see right here we are now getting the zero which is looking amazing.
1:51:57
Así que si cambio eso a, no sé, tal vez 100 y guardo, ahora estamos obteniendo este 100 aquí. Así que eso es increíble.
So if I change that to like I don't know maybe 100 and save there and now we are getting this 100 right here. So that's amazing.
1:52:03
Ahora, lo siguiente que tenemos que hacer es que de alguna manera tenemos que cambiar el valor de este estado inicial.
Now the next thing that we have to do is that we have to somehow change the value of this initial stat.
1:52:09
Así que inicialmente especificamos el valor de cero allí. Pero ahora quieres cambiar eso a, no sé, tal vez uno o 100 o algo así.
So initially we specify the value of zero to there. But now you want to change that to like, I don't know, maybe one or 100 or something like that.
1:52:17
Así que para hacer eso, vamos a crear nuestro botón. Así que solo crearé mi botón aquí.
So to do that, we are going to be creating our button. So I'll just create my button right here.
1:52:21
Y voy a pegar como un más aquí o simplemente puedo decir más. Pero sabes qué, ese símbolo de más estará bien.
And I'm going to just paste like plus right here or I can just say plus. But you know what, that plus symbol will be fine.
1:52:27
Y voy a adjuntar el controlador de eventos allí, que será el de clic.
And I'm going to be attaching the event handler on there, which will be the on click.
1:52:31
Así que cuando alguien haga clic en ese botón, vamos a ejecutar esta función, que es la función de incremento. Así que voy a copiar el nombre de esta función.
So when somebody clicks on that button, so we're going to be firing this function, which is the increment function. So I'm going to copy the name of this function.
1:52:38
y ahora déjame crear esta función aquí, así que solo usaré como const
and now let me just create this function right here so i'll just use like cons
1:52:41
incrementar y esta función solo tomará este set
increment and this function will only take this set
1:52:44
conteo y recuerda que este set conteo es una función que
count and remember this set count is a function which
1:52:47
nos permite cambiar el valor de nuestro contador
allows us to change the value of our counter
1:52:50
o nuestro estado inicial, así que voy a ejecutar esta función aquí y ahora cómo vamos a cambiar el valor de nuestra función
or our initial state okay so i'm going to just execute this function right here and now how we are going to be changing the value of our function
1:52:58
así que si solo escribo como conteo más uno y si guardo mi archivo y aquí pueden ver que ahora estamos
so if i just write like count plus one and if i save my file and here you can see we are now
1:53:03
obteniendo nuestro botón y ahora si hago clic allí, cada vez que haga clic
getting our button and now if i click on there anytime i click
1:53:06
allí, va a incrementar mi contador en uno, así que
on there it's going to increment my counter by one so
1:53:09
déjame refrescar, uno, dos, tres y así
let me just refresh there one two three and so
1:53:12
en adelante, así que ahora también puedo duplicar
on and so forth okay so now i can also duplicate
1:53:16
esta línea de código y solo voy a cambiar allí a menos y estoy
this line of code and i'm going to just change there to minus and i'm
1:53:19
también voy a crear una función para los decrementos o decrementar y
going to also create a function for the decrements or decrement and
1:53:23
voy a copiar el nombre de su función, voy a duplicar esta línea de código, voy a colocar el nombre de mi función y en lugar
i'm going to copy their function name i'm going to duplicate this line of code i'm going to place the name of my function and instead
1:53:30
de un más, voy a cambiar eso a menos, así que si guardo allí ahora
of a plus i'm going to change that to minus so if i save there now
1:53:33
tenemos lo que es un botón de decremento, así que si hago clic ahí, cada vez que haga clic ahí, va a decrementar mi contador en uno
we have what a decrement uh button as well so if i click on there anytime i click on there it's going to decrement my counter by one
1:53:39
ahora sé que mucha gente me preguntará, como huzan, ¿podemos cambiar
now i know a lot of people will ask me like huzan can we change
1:53:42
el valor de este conteo sin usar este conjunto
the value of this count without using this set
1:53:45
conteo, así que sabes qué, déjame hacer eso, voy a quitar eso de aquí y
count so you know what let me just do that i'm going to remove that from here and
1:53:48
ahora déjame usar mi conteo más uno en lugar de proporcionar
now let me just use my count plus one instead of providing
1:53:52
ese conjunto de conteo y cosas, así que solo usaré como conteo menos uno y ahora voy a guardar mi archivo, así que si guardo mi archivo y actualizo
that uh set count and stuff so i'll just use like count minus one and now i'm going to save my file so if i save my file and refresh
1:53:58
ahí, ahora si hago clic ahí, aquí puedes ver detrás
there now if i click on there here you can see behind
1:54:01
la escena, este contador está actualizando la interfaz de usuario
the scene this counter is updating the ui is
1:54:05
no se está actualizando, ¿por qué? porque el método de establecer conteo
not updating why is there because the set count method
1:54:08
nos permite cambiar el valor de nuestro estado y cada vez que
allows us to change the value of our state and anytime
1:54:11
cambiamos el valor de nuestro estado, nuestro componente
we change the value of our state our component
1:54:14
se volverá a renderizar, quiero que tengas eso en mente cada vez que cambiamos el valor de nuestra función o no una función, sino un estado usando el conjunto
will re-render i want you to keep that in mind anytime we change the value of our function or not a function but a state by using the set
1:54:23
el método de conteo o cualquier método de conjunto va a volver a renderizar
count method or any set method is going to re-render
1:54:26
nuestra aplicación, pero ahora en este caso no lo hará
our application but now in this case it will not
1:54:29
volver a renderizar nuestra aplicación, aún cambiará el valor
re-render our application it will still change the value
1:54:32
de nuestro estado, pero no volverá a renderizar nuestra aplicación, está bien
of our state but it will not re-render our application okay
1:54:36
así que esto no está permitido, esto es un gran no-no en
so this is not allowed this is a big no-no in
1:54:39
react.js, no puedes cambiar el estado de tu aplicación sin
react.js you cannot change the state of your application without
1:54:43
usar el método de establecer, como tienes que usar ahí, así que voy a copiar ahí y ahora déjame envolver ahí así, está bien, así que también voy a usar mi contador establecido aquí y cerremos ahí de esta manera.
using the set method like you have to use there so i'm going to copy there and now let me just wrap there like so okay so i'm going to also use my set counter right here and let's just close there like this way.
1:54:54
Así que voy a vender mi archivo. Y una vez más, si hago clic en este botón, va a incrementar ahí.
So I'm going to sell my file. And once again, if I click on this button, it's going to increment there.
1:54:59
Y este va a decrementar o decrementar ahí. Ahora déjame darte un ejemplo más de cómo vamos a actualizar nuestro arreglo de contenido.
And this one will decrement or decrement there. Now let me give you one more example of how we are going to be updating our array of content.
1:55:07
Así que una vez más, vamos a importar nuestro hilo de uso. Y luego vamos a crear nuestro hilo. Así que solo usaré como hilo de uso.
So once again, we are going to be importing our use thread. And then we are going to be creating our thread. So I'll just use like use thread.
1:55:14
En el video inicial, voy a especificar el arreglo aquí. Así que para el primero, vamos a proporcionar a Alex.
In the initial video, I'm going to specify array right here. So for the first one, we are going to be providing Alex.
1:55:19
Y también voy a proporcionar a John como mis amigos. Y voy a almacenar eso dentro de mis variables.
And I'm going to also provide John as my friends. And I'm going to store that inside my variables.
1:55:24
también voy a estar usando mi desestructuración de arreglos, así que solo usaré como amigos
i'm going to be also using my array destructuring so i'll just use like friends
1:55:28
y también establecer amigos aquí, esto es solo una convención
and also set friends right here this is just a convention
1:55:31
si quieres seguir, eres más que bienvenido a seguir allí
if you want to follow there you are more than welcome to follow there
1:55:34
pero si no quieres seguir allí, no tienes que hacerlo, ahora dentro
but if you don't want to follow there you don't have to now inside
1:55:37
esta sección voy a estar usando a mis amigos, ahora simplemente iteremos
this section i'm going to be using my friends now let's just iterate
1:55:40
a través de cada amigo y vamos a estar proporcionando a nuestro amigo
over through each friend and we're going to be providing our friend
1:55:43
aquí o simplemente si estaría bien y ahora dentro
right here or just if would be fine and now inside
1:55:47
ahí vamos a estar usando nuestro li, déjame usar mi vivo correctamente
there we're going to be using our li let me just use my live right
1:55:50
aquí y vamos a estar renderizando a nuestro amigo, está bien
here and we are going to be rendering our friend okay
1:55:53
así que para la clave voy a pegar como math start random y
so for the key i'm going to paste like math start random and
1:55:57
eso va a estar bien, así que si guardo mi archivo y aquí puedes ver que ahora estamos obteniendo
that's going to be fine so if i save my file and here you can see we are now getting
1:56:00
alex y también john, que se ve increíble, así que
alex and also john which is looking amazing so
1:56:03
ahora lo siguiente que quiero hacer es que quiero agregar un nuevo elemento
now the next thing that i want to do is that i want to add a new element
1:56:06
o agregar un nuevo amigo a esta lista, así que ¿cómo puedo ir
or add a new friend to this list so how can i go
1:56:09
acerca de hacer eso? Para hacerlos, voy a crear un botón aquí y ahora simplemente le daré el nombre de agregar nuevo amigo o algo que estaría bien, vamos f re y ahí vamos
about doing that to do them i'm going to just create a button right here and now i'll just give the name of like add new friend or something that would be fine come on f re and there we go
1:56:21
y voy a estar adjuntando el controlador de eventos que será un clic para agregar
and i'm going to be attaching the event handler which will be one click add
1:56:25
un amigo estaría bien, así que voy a copiar
one friend would be fine so i'm going to copy
1:56:28
ahí y ahora déjame agregar ese amigo usando esta función
there and now let me just add that friend by using this function
1:56:31
así que simplemente usaré mi agregar un amigo y aquí
so i'll just use my add one friend and here
1:56:35
vamos a estar creando nuestra función de flecha y ahora en
we are going to be creating our arrow function and now in
1:56:38
este caso para mutar este arreglo o cambiar algo dentro
this case to mutate this array or to change something inside
1:56:41
este arreglo, vamos a estar usando nuestro set friend, así que simplemente voy a llamar
this array we're going to be using our set friend so i'm going to just call
1:56:44
a esta función aquí y ahora dentro, primero que nada estamos
this function right here and now inside there first of all we are
1:56:47
yendo a obtener a todos los amigos que actualmente tenemos, no
going to be getting like all of the friends which we currently have we
1:56:51
queremos cambiar los datos existentes dentro de este arreglo, pero queremos
don't want to change the existing data inside this array but we
1:56:54
agregar otro nuevo amigo, así que así es como vamos a estar clonando los datos existentes dentro de nuestro estado
want to add yet another new friend so this is how we
1:56:57
vamos a clonar los datos existentes dentro de nuestro estado
are going to be cloning the existing data inside our state
1:57:00
o nuestro arreglo y luego vamos a agregar uno nuevo así que
or our array and then we're going to be adding a new one so
1:57:03
simplemente pegaré como yo mismo como va en uh desarrollo web
i'll just paste like my own self like goes in uh web dev
1:57:06
y ahora si guardo mi archivo y aquí puedes ver que ahora estamos obteniendo como
and now if i save my file and here you can see we are now getting like
1:57:09
el botón de agregar nuevo amigo y si hago clic allí también va a agregar
add new friend button and if i click on there so it's going to also add
1:57:13
aquí mismo así que así es como vamos a actualizar o mutar nuestro arreglo ahora déjame mostrarte cómo vamos a eliminar a una persona específica
there right here so this is how we are going to be updating or mutating or array now let me show you how we are going to be removing a specific person
1:57:20
de esta lista así que para hacer eso voy a crear
from this list so to do that i'm going to just create
1:57:23
aquí otro botón que dirá como uh eliminar
here another button which will say like uh remove
1:57:26
un amigo o algo así y también voy a pegar
one friend or something and i'm going to also paste
1:57:29
el manejador de eventos on click allí que dirá como eliminar amigo
the on click event handler on there which will say like remove friend
1:57:33
así que voy a copiar allí y déjame crear esa función aquí mismo
okay so i'm going to copy there and let me create that function right here
1:57:36
así que voy a crear mi función de eliminar y simplemente usemos
so i'm going to be creating my remove function and let's just use
1:57:39
nuestro set friend una vez más entonces ahora aquí estamos
our set friend one more time then now here we're
1:57:42
vamos a usar nuestros amigos y ahora vamos a usar un método de filtro
going to be using our friends and now we're going to be using a filter method
1:57:45
porque queremos filtrar a esa persona específica y
because we want to filter out that specific person and
1:57:49
entonces queremos simplemente eliminar allí así que solo colocaré como mi función de callback justo
then we want to just remove there so i'll just place like my callback function right
1:57:52
aquí así que si ese amigo específico es
here so if that specific friend is
1:57:55
diferente de john solo queremos eliminar
not equal to john we only want to remove
1:57:58
a ese john así que no queremos eliminar nada más solo
that john so we don't want to remove anything else we only
1:58:01
queremos eliminar a este john así que si guardo mi archivo y ahora
want to remove this john so if i save my file and now
1:58:04
aquí puedes ver que tenemos como alex y también john así que si
here you can see we have like alex and also john so if
1:58:07
agrego allí ahora va a eliminar a este john de
i add there now it's going to remove this john from
1:58:10
esta lista así que si hago clic allí y aquí puedes ver que va a eliminar
this list so if i click on there and here you can see it's going to remove
1:58:14
su john así que esta es la segunda forma ahora déjame mostrarte
their john so this is the second way now let me show you
1:58:17
la forma final que es cómo vamos a actualizar a un amigo específico así que
the final way which is how we are going to be updating a specific friend so
1:58:20
sí, déjame mostrarte, voy a crear un botón
yeah let me just show you them i'm going to create a button
1:58:23
y que dirá algo como, vamos a actualizar
and which will say like um come on update
1:58:27
un amigo y también voy a adjuntar mi
one friend and i'm going to also attach my
1:58:30
manejador de eventos que dirá algo como actualizar uno o
event handler on there which will say like update one or
1:58:33
actualizar un amigo estaría bien, voy a copiar ahí y
update one friend would be fine i'm going to copy there and
1:58:37
vamos a crear esa función aquí mismo, todavía vamos a usar
let's just create that function right here we're going to be still using
1:58:40
nuestros amigos establecidos y ahora aquí tenemos que especificar nuestros
our set friends and now here we have to specify our
1:58:43
amigos.map porque queremos iterar sobre todos los amigos que tenemos
friends.map because we want to to iterate over through all of the friends that we
1:58:46
actualmente y ahora solo tenemos que usar como si amigo
currently have and now we just have to use like if friend
1:58:50
es igual a Alex, así que en ese caso queremos
is equals to Alex so in that case we
1:58:53
cambiar su nombre a como Alex Smith o algo así
just want to change his name to like Alex Smith or something
1:58:56
así, pero si ese no es el caso, solo queremos proporcionar
like that but if that's not the case we only want to provide
1:58:59
ese nombre específico, así que aquí estamos usando un ternario
that specific name okay so here we are using a ternary
1:59:02
como si nuestro amigo es igual a Alex, así que solo queremos cambiar su nombre a Alex Smith, pero si ese no es el caso, solo queremos devolver todos los
operator like if our friend is equal to Alex so we just want to change his name to Alex Smith but if that's not the case we just want to return all of the overall
1:59:11
amigos, así que ahora voy a guardar mi archivo y
friends okay so now i'm going to save my file and
1:59:14
aquí puedes ver que tenemos a Alex y también tenemos a Huzana Webdev, así que
here you can see we have like alex and we also have like huzana webdev so
1:59:18
si solo actualizo, agregaré a mí mismo y ahora quiero
if i just refresh there add my own self and now i want
1:59:21
que notes a este Alex, así que si hago clic en actualizar un amigo
you to notice this alex so if i click on update one friend
1:59:24
cambiará el nombre de este Alex a Alex Smith, así que
so it's going to change the name of this alex to alex smith so
1:59:27
así es como vamos a usar un estado con un arreglo de contenido
this is how we are going to be using a use state with array of content
1:59:30
ahora eso fue sobre el número, también aprendimos sobre cómo
now that was about the number we also learned about how
1:59:33
vamos a actualizar el arreglo, pero ahora hablemos sobre cómo vamos a
we are going to be updating the array but now let's talk about how we are going to
1:59:36
actualizar el objeto, así que solo usaré como importar y luego usar
be updating the object so i'll just use like import and then use
1:59:39
estado, voy a importar aquí y ahora déjame usar
state i'm going import the right here and now let me just use
1:59:42
como const película o solo película estaría bien y luego
like const movie or just movie would be fine and then
1:59:46
configurar película está bien, así que vamos a usar o usado
set movie okay so we are going to be using or used
1:59:49
no transición maldita sea, usa estado y aquí vamos a especificar nuestro objeto y para el objeto vamos a especificar como el título de la película que será una de mis películas favoritas
not transition god damn it use state and here we are going to be specifying our object and for the object we are going to be specifying like the title of the movie which will be one of my favorite movie
2:00:00
equalizer 3 y luego
equalizer 3 and then
2:00:03
también vamos a proporcionar nuestras calificaciones para eso, así que las calificaciones se establecerán
we're going to be also providing our ratings for that so ratings will be set
2:00:06
a 7, voy a guardar mi archivo, así que así es como vamos a estar inicialmente
to 7 i'm going to save my file so this is how we are going to be initially
2:00:09
proporcionando nuestro contenido estado hacia adelante y
providing our content forward state and
2:00:12
ahora déjame renderizar eso justo aquí en la interfaz de usuario, así que
now let me render that right here to the ui so
2:00:15
solo usaré como h1 y aquí vamos a estar usando como
i'll just use like h1 and here we're going to be using like
2:00:19
título de la película y luego también vamos a estar usando párrafo de calificación de la película, así que si guardo allí, aquí puedes ver que ahora estamos obteniendo el título de la película
movie dot title and then we are going to be also using paragraph of movie dot rating so if i save there so here you can see we are now getting the movie title
2:00:30
y también estamos obteniendo la calificación, así que solo cambiaré eso a calificaciones
and we are also getting the rating so i'll just change there to ratings
2:00:33
ahí vamos y cambia este a
there we go and change this one to
2:00:36
el título, ahora se ve mejor, así que
the title now that's looking better so
2:00:40
ahora lo siguiente que quiero hacer es crear un botón que actualizará
now the next thing that i want to do is i want to create a button which will update
2:00:43
la calificación de esta película, así que solo escribiré como cambiar calificación
the rating of this movie so i'll just write like change rating
2:00:46
mi propio controlador de eventos de clic que dirá manejar clic
word my own click event handler which will say handle click
2:00:50
voy a copiar allí y aquí vamos a estar creando esa función justo aquí cons manejar clic y ahora dentro de esta función, vamos a actualizar solo las calificaciones, nada más que solo las calificaciones.
i'm going to copy there and here we are going to be creating that function right here cons handle click and And now inside this function, we are going to be updating only the ratings, nothing else but only the ratings.
2:01:02
Así que para hacer eso, primero vamos a hacer una copia de nuestro estado. Así que para hacer una copia de nuestro estado, podemos usar como copiar película.
So to do that, first of all, we are going to be making a copy of our stat. So to make a copy of our stat, we can use like copy movie.
2:01:10
Y ahora aquí dentro, podemos usar punto punto punto y película. Como queremos tomar el título y también las calificaciones.
And now here inside there, we can use dot dot dot and movie. Like we want to take the title and also the ratings.
2:01:16
Así es como vamos a hacer una copia de nuestra película. Luego podemos especificar la coma y qué cosa quieres cambiar.
This is how we are going to be making a copy of our movie. Then we can specify the comma and what thing you want to change.
2:01:23
Así que solo escribiré como calificaciones y luego queremos cambiar eso a cinco. Así es como vamos a hacer una copia de nuestra película.
So I'll just write like ratings and then we want to change there to five. So this is how we are going to be making a copy of our movie.
2:01:30
Y así es como podemos cambiar una cosa específica dentro de esa película o dentro de ese objeto.
And this is how we can change a specific thing inside that movie or inside that object.
2:01:36
OK, y ahora vamos a estar usando nuestro establecer película, que es la función que nos permite cambiar este estado.
OK, and now we are going to be using our set movie, which is the function which allows us to change this state.
2:01:42
Y voy a especificar mi copia de película justo aquí. Si guardo mi archivo y aquí puedes ver que si hago clic en este botón, va a cambiar las calificaciones a cinco justo aquí, lo cual es increíble.
And I'm going to specify my copy movie right here. If I save my file and here you can see if I click on this button, so it's going to change the ratings to five right here, which is amazing.
2:01:52
pero esta es la forma más larga de hacer las cosas pero
but this is the longer way of doing things but
2:01:55
podemos refactorizar completamente este código para usar una forma abreviada, así que
we can totally refactor this code to use a shorthand so
2:01:58
voy a comentar esta línea y voy a
i'm going to just comment this line out and i'm going
2:02:01
cortar eso de aquí y en su lugar vamos a usar el
to just cut that from here and instead we are going to be using the
2:02:04
objeto que voy a usar punto punto película y luego coma
object i'm going to use dot dot movie and then comma
2:02:07
calificaciones y voy a especificar cinco aquí así que
ratings and i'm going to just specify five right here so
2:02:10
esta es solo una forma más corta de escribir todo eso así que
this is just a shorter way of writing all of that stuff so
2:02:14
voy a actualizar eso y hacer clic en cambiar calificación así que
i'm going to just refresh that and click on the change rating so
2:02:17
también va a cambiar las calificaciones a cinco y vamos a eliminar
it's going to also change the ratings to five and let's just remove
2:02:20
eso de aquí y ahora se ve mejor, también podemos eliminar estas llaves
that from here and now that's looking better we can also remove these curly
2:02:23
curvas que no necesitamos, eso se ve genial y
braces we don't need that that's looking cool and
2:02:26
sí, eso se ve mejor, así que así es como vamos
yeah that's looking better so that was how we
2:02:29
a usar el use stat con objeto, pero en algunas situaciones
are going to be using the use stat with object but in some situation
2:02:33
tendríamos un array de objetos, así que ¿cómo puedes hacer
we would have like array of objects so how can you go about
2:02:36
eso? Vamos a usar nuestro use stat primero
doing that we're going to be using our use stat first
2:02:39
de todo y dentro de ahí vamos a pasar el array
of all and inside there we're going to be passing the array
2:02:42
de objetos, así que dentro de cada objeto vamos a pasar el id que se establecerá en uno y el título será como no sé
of objects so inside each object we're going to be passing the id which will be set to one and title will be like i don't know
2:02:49
algún tipo de nombre de película como spider-man y voy a
some sort of a movie name like spider-man and i'm going
2:02:52
también especificar las calificaciones allí y la calificación se establecerá
to also specify the ratings to there and rating will be set
2:02:55
en tres, voy a duplicar allí y cambiar la calificación a seis y
to three i'm going to duplicate there and change the rating to six and
2:02:59
cambiar el título de la película a superman y
change the movie title to superman and
2:03:02
también el id se establecerá en dos, así que ahora en este caso tenemos
also the id will be set to two so now in this case we
2:03:06
un array de objetos aquí
have array of objects right here
2:03:09
y ahora si quieres modificar allí, ¿cómo puedes hacerlo? Así que para hacerlo, primero tenemos que almacenar allí en algún tipo de estado, así que solo usaré
and now if you want to modify there how can you go about doing that so to do there first of all we have to store there in some sort of a state so i'll just use
2:03:17
como películas y luego establecer películas y eso va
like movies and then set movies and that's going
2:03:20
a ser igual a esta función use state aquí, así que si guardo
to be equals to this use state function right here so if i save
2:03:23
lo siguiente que tenemos que hacer es que tenemos que iterar sobre cada elemento
that the next thing that we have to do is that we have to iterate over through each element
2:03:27
dentro de este array y tenemos que renderizar eso y
inside this array and we have to render that and
2:03:30
voy a entrar en mi sección y dentro de esto
i'm going to just go into my section and inside this
2:03:33
en la sección usaré mi movies.map y solo voy a pasar mi m para la película como para cada una de las películas y ahora dentro de ahí vamos a estar usando sobre li y solo usarlos manualmente
section i'll use my movies.map and i'm going to only pass my m for the movie like for each of the movie and now inside there we are going to be using over li and just use them manually
2:03:45
y voy a pasar mi movie.title o
and I'm going to pass my movie.title or
2:03:48
no película, sino solo m.title estaría bien y también voy a proporcionar la clave y eso será como math.random y proporcionar mi clave aleatoria a eso.
not movie but just m.title would be fine and I'm going to also provide the key and that will be like math.random and provide my random key to it.
2:03:58
Ahora debajo de eso vamos a crear un botón que dirá como cambiar nombre y también vamos a adjuntar el controlador de eventos allí que dirá como manejar clic.
Now underneath there we're going to be creating a button which will say like change name and we're going to be also attaching the event handler on there which will say like handle click.
2:04:08
Voy a copiar de aquí y vamos a crear esa función justo aquí.
I'm going to copy there from here and let's just create that function right here.
2:04:12
Así que solo usaré como Y en este caso, una vez más, vamos a estar usando el set movies. Y nos permitirá cambiar nuestro estado.
So I'll just use like And in this case, once again, we are going to be using the set movies. And it's going to allow us to change our state.
2:04:19
Y aquí vamos a pasar nuestras películas. Y voy a usar el método map para iterar sobre cada película.
And here we are going to be passing our movies. And I'm going to be using the map method to iterate over through each movie.
2:04:25
Y solo usemos nuestro M para cada una de las películas. Así que si M.id es igual a 1.
And let's just use our M for each of the movie. So if M.id is equals to 1.
2:04:31
Así que en esta situación, solo queremos cambiar la película. Primero que nada, vamos a hacer una copia de todas las películas.
So in this situation, we just want to change the movie. First of all, we are going to be making a copy of all of the movies.
2:04:36
Y luego solo queremos cambiar el título a John Wick.
And then we only want to change the title to John Wick.
2:04:43
4 o tal vez 5 estaría bien. Y ahora fuera de ahí, ¿qué estoy haciendo?
4 or maybe 5 would be fine. And now outside from there, what am I doing?
2:04:49
Está bien, así que ahora fuera de ahí, vamos a cerrar nuestro operador ternario y solo proporcionar m aquí.
Okay, so now outside from there, we are going to be closing our ternary operator and just provide m right here.
2:04:54
Así que ahora déjame explicar este código. Primero que nada, ahora estamos iterando sobre cada película
So now let me just explain this code. First of all, we are now iterating over through each movie
2:05:00
Y ahora estamos almacenando allí en M. Y ahora estamos verificando si el ID de la película es igual a 1. Solo estamos verificando la primera película.
And we are now storing there in M. And now we are checking if the movie ID is equals to 1. We are only checking the first movie.
2:05:07
Así que si ese es el caso, ¿qué tenemos que hacer? Tenemos que hacer una copia de nuestras películas de estado completas.
So if that's the case, what do we have to do? We have to make a copy of our entire stat movies.
2:05:12
Y solo queremos cambiar el nombre de la primera película a John Wick Capítulo 5. Así que si ese no es el caso, solo queremos devolver todas las películas.
And we only want to change the name of the first movie to John Wick Chapter 5. So if that's not the case, we just want to return all of the movies.
2:05:20
Eso es exactamente lo que estamos haciendo ahora mismo. Si guardo mi archivo, y déjame refrescar allí.
That's exactly what we are doing right now. If I save my file, and let me just refresh there.
2:05:24
Y si hago clic en cambiar nombre, va a cambiar allí a John Wick Capítulo 5.
And if I click on the change name, it's going to change there to John Wick Chapter 5.
2:05:30
Así que sí, así es como vamos a iterar sobre toda la lista de array de estado.
So yeah, this is how we are going to be iterating over through the entire list array of state.
2:05:35
Y ahora así es como vamos a mutar ese estado o cambiar ese estado o actualizar ese estado. Así que eso está bien y todo.
And now this is how we are going to be mutating that state or changing that state or updating that state. So that's cool and everything.
2:05:43
Pero ahora en alguna situación, querríamos compartir nuestro estado en otro componente. ¿Cómo puedes hacerlo?
But now in some situation, we would want to share our state into other component. So how can you go about doing that?
2:05:49
Primero que nada, vamos a importar lo que es estado. y luego solo voy a crear algún tipo de estado como contar y también el set count y eso va a ser igual a el uso de estado y el valor inicial se establecerá en cero.
First of all, we're going to be importing what you state. and then I'm going to just create some sort of a stat like count and also the set count and that's going to be equals to the use stat and the initial value will be set to zero.
2:06:01
Ahora voy a continuar y crear algunos componentes así que solo crearé mi carpeta de componentes y tenemos nuestro component1.jsx y también tenemos nuestro component2.jsx.
Now I'm going to go ahead and create a few components so I'll just create my components folder and we have our component1.jsx and we also have our component2.jsx.
2:06:14
Ahora dentro de este component1 voy a usar mi rafce
Now inside this component1 I'm going to be using my rafce
2:06:17
guardar este archivo y dentro del componente 2 vamos
save this file and inside the component 2 we
2:06:20
a usar nuestro rafce 2 y ahora voy a
are going to be using our rafce 2 and now i'm
2:06:24
ir a mi componente de aplicación y tenemos que importar nuestro
going to go into my app component and we have to import our
2:06:27
componente vamos componente 1
component come on component 1
2:06:30
y también tenemos que importar nuestro componente 2
and we also have to import our component 2
2:06:34
también aquí voy a guardar este archivo y ahora dentro de esta sección voy a llamar a mi componente 1 primero que nada y simplemente ejecutemos ahí y
as well right here i'm going to save this file and now inside this section i'm going to call my component 1 first of all and let's just execute there and
2:06:43
también voy a llamar a mi componente vamos componente
i'm going to also call my component come on component
2:06:46
componente dos y
component two and
2:06:49
también voy a ejecutar eso ahora quiero compartir este
i'm going to also execute that now i want to share this
2:06:53
estado en estos componentes así que ¿cómo puedo hacer eso?
state into these components so how can i go about doing
2:06:56
bueno, para hacer eso vamos a usar nuestro sistema de props
that well to do that we are going to be using our prop system
2:06:59
así que podemos simplemente decir como count y count será ese count o ese valor inicial de este estado así que ahora estamos pasando nuestro estado desde el
so we can just say like count and count will be that count or that initial value of this state so we are now passing our state from the
2:07:08
componente de aplicación desde el componente padre al componente
app component from the parent component to the component
2:07:11
uno y también al componente dos como un componente hijo
one and also to the component two as a children component
2:07:14
bien, así que también voy a pasar mi propio clic
okay so i'm going to also pass my own click
2:07:18
en el manejador de clics como un nombre de función y
on click handler as a function name and
2:07:22
aquí también vamos a pasar qué función dentro de esto así que
here we're going to be also passing what function inside this so
2:07:25
puedo simplemente decir como set count y aquí voy a pasar como count más uno voy a guardar este archivo y ahora puedo copiar todo eso de aquí y ahora puedo pasar eso justo aquí
i can just say like set count and here i'm going to just passing like count plus one i'm going to save this file and now i can totally copy all of that stuff from here and now i can totally pass that right here
2:07:37
Así que voy a guardar mi archivo. Déjame decir eso una vez más, estamos
So I'm going to save my file. Let me just say that once again, we
2:07:40
definiendo nuestro estado dentro del componente de aplicación y ahora lo estamos compartiendo con el componente uno y también el componente dos usando este sistema de props.
are defining our state inside the app component and we are now sharing there with the component one and also the component two by using this prop system.
2:07:50
Bien, así que ahora dentro de mi componente uno, ahora podemos desestructurar allí y podemos usar nuestro estado del componente de aplicación dentro del componente uno.
Okay, so now inside my component one, we can now totally destructure there and we can totally use our state from the app component inside the component one.
2:07:59
y para hacer eso voy a primero desestructurar mi componente así que
and to do that i'm going to first of all destructure my component so
2:08:02
simplemente usaré como count y también el propio uh clic
i'll just use like count and also the own uh click
2:08:06
manejador justo aquí que es un nombre de función y
handler right here which is a function name and
2:08:09
ahora dentro de este componente un div voy a simplemente eliminar eso y
now inside this component one div i'm going to just remove that and
2:08:12
simplemente escribir mi párrafo y decir como cuenta soy
just write my paragraph and say like count i'm
2:08:16
voy a renderizar mi cuenta dentro de ahí también voy a proporcionar mi botón y
going to render my account inside there i'm going to also provide my button and
2:08:19
que solo dirá como incrementar y
which will just say like increment and
2:08:22
voy a pasar mi propio controlador de eventos de clic allí
i'm going to pass my own click event handler on there
2:08:25
y luego voy a pasar mi manejar clic correcto
and then i'm going to pass my handle click right
2:08:29
aquí voy a copiar allí ir a la parte superior y
here i'm going to copy there go to the top and
2:08:32
aquí tenemos que usar nuestro manejar clic cuando alguien
here we have to just use our handle click when somebody
2:08:35
los usemos vamos a estar disparando esta función bien así que simplemente ejecutemos
use them we are going to be firing this function okay so let's just execute
2:08:38
este mismo archivo y déjame mostrarte así que
this same way file and let me just show you so
2:08:41
aquí puedes ver que ahora estamos obteniendo esto de nuestro párrafo y si hago clic
here you can see we are now getting this from our paragraph and if i click
2:08:45
en esto va a actualizar mi cuenta desde aquí del componente
on this it's going to just update my account for here from the component
2:08:48
b desde el componente hijo ahora estamos actualizando el componente padre así que eso fue
b from the child component we are now updating the parent component so that was
2:08:54
primera forma ahora voy a entrar en mi segundo componente o un componente dos o sabes que voy a simplemente copiar estas cosas de aquí voy a colocar aquí dentro de este componente uno
first way now i'm going to go into my second component or a component two or you know what i'm going to just copy this stuff from here i'm going to place the here inside this component one
2:09:05
voy a poner mi párrafo y renderizar mi cuenta dentro
i'll put my paragraph and render my count inside
2:09:08
ahí vamos a simplemente traer el botón y aumentar aquí
there let's just pull over button and increment here
2:09:12
también y simplemente usemos nuestro propio controlador de eventos de clic
as well and let's just use our own click event handler
2:09:15
manejar evento de clic copiar allí ir a la parte superior
handle click event copy there go to the top
2:09:19
y usar mi const manejar clic y
and use my const handle click and
2:09:22
vamos a estar pasando sobre manejar o en
we are going to be passing over on handle or on
2:09:26
controlador de acuerdo así que voy a guardar mi archivo y
handler okay so i'm going to save my file and
2:09:29
ahora aquí puedes ver que tenemos dos componentes y se están actualizando
now here you can see we have two components and they are updating
2:09:33
entre sí así que si hago clic allí va a actualizar allí correcto
each other so if i click on there and it's going to update there right
2:09:36
aquí así que ¿por qué es eso ahora nuestro estado está disponible
here so why is that now our state is available
2:09:39
dentro del componente padre y ahora estamos actualizando
inside the parent component and we are now updating
2:09:42
ahí desde el componente hijo, así que este es el resultado que estamos
there from the child component so this is the result that we are
2:09:45
obteniendo, así que si hago clic en el incremento, va a incrementar ahí, ¿verdad?
getting so if i click on the increment it's going going to increment there right
2:09:49
aquí, así que esta es la forma en que vamos a compartir nuestro estado usando el
here so this is how we are going to be sharing our state by using the
2:09:52
prop, sé que aprendimos mucho sobre el uso del estado, pero
prop i know we learned a lot about the use state but
2:09:56
aún hay una cosa final de la que quiero hablar, que es cómo
still there is one final thing i want to talk about which is scar how
2:09:59
vamos a estar pasando una función de flecha o simplemente una función como
we are going to be pensing an arrow function or just a function as
2:10:02
el valor inicial para lo que es el uso del estado, pero aún hay una cosa final de la que quiero hablar, que es cómo vamos a estar pasando una función de flecha o simplemente una función como el valor inicial para el uso del estado, así que lo que voy a hacer es
the initial value for what use state but still there is one final thing i want to talk about which is scar how we're going to be passing an arrow function or just a function as the initial value forward use state so what i'm going to do is
2:10:06
que voy a definir mi carpeta de componentes y
that i'm going to define my components folder and
2:10:09
voy a crear un componente con el nombre de example 1.tsx
i'm going to create a component with the name of example 1.tsx
2:10:12
no un tss, sino solo un jsx y voy a estar usando un rafce y sí, voy a renderizar este componente aquí como ejemplo uno y solo lo voy a renderizar ahí.
not a tss but just a jsx and i'm going to be using a rafce and yeah i'm going to render this component right here like example example one and i'm going to just render there.
2:10:24
Guarda mi archivo. Mira esto y aquí puedes ver que ahora estamos obteniendo nuestro ejemplo uno aquí.
Save my file. Check this out and here you can see we are now getting our example one right here.
2:10:28
Vamos a eliminar el CSS independiente y ahora vamos a empezar a trabajar en esto. Así que lo primero que quiero hacer es crear mi estado.
Let's just remove the standalone CSS and now let's start working on this. So the first thing that I want to do is that I want to create my state.
2:10:34
Así que solo crearé un estado con el nombre de count y también set count.
So I'll just create a state with the name of count and also set count.
2:10:38
Va a ser igual a este uso del estado y para el valor inicial ahora vamos a estar pasando una función de callback.
It's going to be equal to this use state and for the initial value now we are going to be passing a callback function.
2:10:44
Está bien, así. Así que esta función de callback solo se ejecutará cuando nuestro componente se renderice por primera vez.
Okay just like that. So this callback function will only run when our component first renders.
2:10:50
Así que cualquier lógica que ponga dentro de esta función de callback
So like any logic I put inside this callback function will
2:10:54
solo se ejecutará en el primer renderizado, así que lo que voy a hacer
only run on the first render so what i'm going to do
2:10:57
es que voy a especificar mi conteo inicial, así que usaré algo como inicial
is that i'm going to specify my initial count so i'll use like initial
2:11:00
count y va a ser igual a algún tipo de valor 10
count and it's going to be equals to some sort of a 10 value
2:11:03
y también voy a devolver este conteo inicial de esta función de flecha
and i'm going to also return this initial count from this arrow
2:11:06
así que ahora déjame guardar, luego tenemos que renderizar
function so now let me just save there next we have to render
2:11:09
ahí, así que voy a eliminar eso de esta interfaz de usuario y voy a escribir
there so i'm going to just remove there from this ui and i'm going to write
2:11:12
mi h1 que dirá count y aquí tenemos que renderizar nuestro conteo, luego también tenemos que crear un botón que nos permita incrementar nuestro contador, está bien, así que
my h1 which will say count and here we have to render our count next we also have to create a button which allows us to increment our counter okay so i'll
2:11:21
usaré algo como on click y aquí vamos a pasar esta función de incremento, así que solo usaré algo como const increment y dentro de esta función solo vamos a usar el set count
use like on click and here we're going to be passing this increment function so i'll just use like const increment and inside this function we're going to be only using the set count
2:11:32
y proporcionar mi valor de conteo anterior a eso y luego
and provide my previous count value to that and next
2:11:35
vamos, ¿qué demonios estoy haciendo? A continuación, solo tenemos que usar nuestro
come on what the hell am i doing next we have to just use our
2:11:38
conteo anterior y sumar solo uno a eso. Ahora voy a guardar mi archivo y tan pronto como guarde mi archivo y actualice, aquí puedes ver que nos dará un valor de 10 como el
previous count and plus only one to that now i'm going to save my file and as soon as i save my file and refresh there and here you can see it's going to give us 10 value as the
2:11:47
valor inicial para este conteo aquí mismo, así que ahora puedo totalmente
initial value for this count right here so now i can totally
2:11:50
incrementar y puedo hacer lo que quiera hacer con eso
increment there and i can do whatever i want to do with that
2:11:53
así que sí, ese fue el ejemplo número uno. Ahora déjame darte
so yeah that was the example number one now let me give you
2:11:56
un ejemplo más que será el ejemplo 2.tsx
one more example which will be example 2.tsx
2:12:00
jss, ¿qué demonios estoy diciendo? Vamos a usar lo que rafc
jss what the hell am i saying let's use what rafc
2:12:04
dentro también quiero renderizar eso dentro de mi
inside there also i want to render that inside my
2:12:07
componente de aplicación, así que voy a comentar esta línea y voy a renderizar mi
app component so i'm going to comment this line out and i'm going to render my
2:12:10
componente a un componente
component to a component
2:12:13
ok, componente dos
okay component two
2:12:17
o ejemplo dos, no un componente, así que usaré como ejemplo
or example two not a component so i'll use like example
2:12:20
dos y cerrar el archivo semi, verifica esto
two and close the semi file check this
2:12:23
así que aquí puedes ver que ahora estamos obteniendo más ejemplo dos, así que ahora el primero
out so here you can see we are now getting more example two so now the first
2:12:26
cosa que quiero hacer es que quiero crear mi número aleatorio, así que usaré como número aleatorio y también establecer número aleatorio que va a ser
thing that i want to do is that i want to create my random number so i'll use like random number and also set random number that's going to be
2:12:34
igual a esto, usar estado una vez más y para el
equals to this use stat once again and for the
2:12:37
valor inicial, vamos a pasar esta función de callback correcta
initial value we're going to be passing this callback function right
2:12:40
aquí, así que ahora dentro de esta función de callback usaré como
here okay so now inside this callback function i'll just use like
2:12:43
math.floor y aquí también voy a proporcionar como math.random
math.flow and here i'm going to also provide like math.random
2:12:47
y luego multiplicar por 100 estaría bien, así que
and then times 100 would be fine so
2:12:50
ahora, si envío mi archivo, oh, debería ser solo igual a signo
now if i send my file oh it should be just equal to sign
2:12:53
ok, así que nos dará una función aleatoria cada vez que este componente se renderiza por primera vez, así que solo lo quitaré de aquí y voy a escribir mi h1 que
okay so it's going to give us a random function whenever this component first renders so i'll just remove that from here and i'm going to write my h1 which
2:13:01
dirá como número aleatorio y luego voy a
will say like random number and then i'm
2:13:04
renderizar mi número aleatorio, ok, así que
going to render my random number okay like so so
2:13:08
ahora, si vendo mi archivo y aquí puedes ver que nos dará un cero, dejemos
now if i sell my file and here you can see it's going to give us a zero let
2:13:11
déjame actualizar esto, nos va a dar 72, actualiza una vez más, así que cada vez que lo actualizo, nos va a dar un número aleatorio
me just refresh this it's going to give us 72 refresh there once again so anytime i refresh it it's going to give us a random number
2:13:17
ahora debajo de este h1, crearé un botón que dirá algo como generar
now underneath this h1 i'll create a button which will say like generate
2:13:20
un nuevo número o generar un nuevo número aleatorio o algo así y cuando alguien haga clic en este botón, van a
um new number or generate a new random number or something like that and when somebody clicks on this button they're going
2:13:28
disparar esta función que es generar un nuevo aleatorio
to be firing this function which is a generate new random
2:13:31
número, ahora déjame copiar ahí y crearé esto
number now let me copy there and I'll create this
2:13:34
función aquí, va a ser una función de flecha y solo presionaré como nuevo número y ese nuevo número será igual a mat.plower y también tenemos que especificar mat.random
function right here it's going to be an arrow function and I'll just press like new number and that new number will be equals to mat.plower and also we have to specify mat.random
2:13:45
veces 100 una vez más, como 100, así que finalmente vamos a establecer ahí dos
times 100 one more time like 100 like so and finally we're going to be setting there two
2:13:52
o estado aleatorio, así que aquí tenemos que especificar nuestro
or random state so here we have to specify our
2:13:55
nuevo número en knife está en algún lugar del archivo y cada vez que actualizo
new number in knife is somewhere file and whenever i refresh
2:13:58
mi página, nos va a dar un número aleatorio diferente, así que puedo
my page it's going to give us a different random number so i can
2:14:01
también hacer clic allí, así que ahora también nos va a dar un número aleatorio diferente
also click on there so now it's going to also give us a different random number
2:14:05
así que eso también está hecho, ahora déjame darte el ejemplo final
so that's also done now let me give you the final example
2:14:08
como el ejemplo 3.jsx, usaré mi rfc dentro de ahí, como rfc, guardaré mi archivo, iré a mi
like example 3.jsx i'll use my rfc inside there like rfc save my file go into my
2:14:17
aplicación y renderizaré este componente ahora mismo, como el ejemplo
app and render this component right now like example
2:14:20
tres y cerrar eso, así que lo primero que quiero
three and close that so the first thing that i want
2:14:23
hacer es definir mi estado, así que solo expandiré como nombre y estableceré
to do is i want to define my state so i'll just spread like name and set
2:14:26
nombre y va a ser igual al uso del estado, así que vamos a
name and it's going to be equals to the use state so let's
2:14:29
simplemente usar nuestro uso del estado y para el valor inicial, uh
just use our use state and for the initial value uh
2:14:32
vamos a presionar una función de flecha, así que primero tenemos que guardar algún tipo de nombre en nuestro almacenamiento local, así que solo usaré como variable con el nombre de como número guardado o
we are going to be pressing an arrow function so first of all we have to save some sort of a name to our local storage so i'll just use like variable with name of like saved number or
2:14:42
nombre guardado para ser precisos y eso va a ser igual al
saved name to be precise and that's going to be equals to the
2:14:45
almacenamiento local y aquí queremos usar como obtener elemento y
local storage and here we want to use like get item and
2:14:48
vamos a obtener nuestro elemento de nuestro almacenamiento local si lo tenemos, pero si no lo tenemos, simplemente usemos como nombre guardado, si tenemos el nombre guardado, así que solo queremos pasar allí y queremos obtenerlo de nuestro almacenamiento local.
we're going to be getting our item from our local storage if we have that but if we don't have that let's just use like save name if we have the save name so we just want to pass there and we want to get there from our local storage.
2:15:01
Y si ese no es el caso, solo queremos establecer el valor inicial en una cadena vacía.
And if that's not the case, we just want to set the initial value to empty string.
2:15:06
Ahora déjame ir a la interfaz de usuario y cambiar eso a mi H1 o sí, H1 estaría bien.
Now let me go to the UI and change that to my H1 or yeah, H1 would be fine.
2:15:12
Y aquí solo diré como tu nombre y aquí tenemos que renderizar nuestro nombre así, este nombre aquí. Así que ahora necesito este H1.
And here I'll just say like your name and here we have to render our name like this name right here. So now I need this H1.
2:15:18
Voy a crear un campo de entrada con el tipo de texto. y
I'll create an input field with the type of text. and
2:15:21
también voy a proporcionar el valor y el valor vendrá del estado que
i'm going to also provide the value and the value will be coming from the state which
2:15:25
es un nombre y cuando alguien intenta cambiar algo dentro
is a name and when somebody tried to change something inside
2:15:28
esto vamos a activar esta función de manejo de cambios y
this we're going to be firing this handle change function and
2:15:31
ahora también voy a proporcionar el marcador de posición que dirá como ingresa tu nombre
now i'm going to also provide the placeholder which will say like enter your name
2:15:34
bien y finalmente déjame crear un botón que dirá
okay and finally let me create a button which will say
2:15:38
como borrar nombre y cada vez que alguien haga clic en
like clear name and whenever somebody clicks on
2:15:41
este botón vamos a activar esta función de manejo de borrar que vamos a crear en un o sabes, déjame crear eso primero, vamos a crear esto
this button we're going to be firing this handle clear function which we're going to be creating in a or you know let me just create that first of all we're going to be creating this
2:15:48
función de manejo de cambios luego vamos a crear esa función de borrar
handle change function then we're going to be creating that clear
2:15:51
así que lo que voy a hacer es que voy a encontrar esta función de manejo
function so what i'm going to do is that i'm going to find this handle
2:15:55
de cambios, va a tomar un evento y aquí dentro
change function it's going to take an event and here inside
2:15:58
este evento vamos a establecer el nombre en el evento punto
this event we're going to be setting the name to event dot
2:16:01
valor ahora también voy a usar el efecto de uso
target dot value now i'm going to also use the use effect
2:16:04
así que cada vez que nuestro componente se renderiza por primera vez, así que
so whenever our component first renders so
2:16:07
en esa situación solo queremos establecer nuestro elemento que será un nombre y queremos proporcionar nuestro json punto
in that situation we just want to set our item which will be a name and we want to provide our json dot
2:16:14
cadena si estoy dentro de allí y proporcionar un nuevo nombre allí, está bien
string if i inside there and provide a new name to there okay
2:16:17
así que también proporcionaré un arreglo de dependencias y para el arreglo de dependencias vamos
so i'll also provide a dependency array and for the dependency array we
2:16:20
a proporcionar un nombre y ahora finalmente déjame también crear esta
are going to be providing a name and now finally let me also create this
2:16:23
función de manejo de borrar y luego dentro
handle clear function and then inside
2:16:26
esta función de borrar no vamos a hacer nada loco, pero solo voy a
this clear function we're not going to be doing anything crazy but i will just
2:16:29
escribir como establecer nombre y el valor inicial será cadena vacía, está bien, así que aquí puedes ver que tenemos nuestro nombre y cosas, así que ahora déjame abrir mi consola e ir a mi aplicación
write like set name and the initial value will be empty string okay so here you can see we have our name and stuff so now let me open my console go into my application
2:16:41
oh Dios mío, esto es súper blanco, no sé por qué, pero sí
oh my god this is super white i don't know why but yeah
2:16:44
déjame hacer clic derecho allí y forzar eso
let me just right click on there and force that
2:16:47
a nuestro oscuro, maldita sea, esto es súper blanco, así que
to our dark god damn it this is super white so
2:16:50
déjame ir al almacenamiento local y aquí lo que sea que yo
let me just go into local storage and here whatever i
2:16:53
déjame ir a almacenamiento local y aquí lo que escriba ahí se va a poner justo aquí
type inside there it's going to be putting it right here
2:16:56
pero de esa manera también estarás almacenado dentro de mi almacenamiento local, así que cada vez que actualice aquí y allá, puedes ver que aún estarás aquí, así que ahora cada vez que haga clic en este nombre claro, se va a borrar esto
but that way you will be also stored inside my local storage so whenever i refresh there and here you can see that well you will still be here so now whenever i click on this clear name so it's going to clear this out
2:17:08
Así que el objetivo de esta sección era que también podemos especificar una función de flecha o simplemente una función para nuestro hilo de uso.
So the whole point of this section was that we can also specify an arrow function or just a function to our use thread.
2:17:15
Bienvenido al desafío de uso de hilo. Así que lo primero que quiero que hagas es crear el archivo counter.jsx.
Welcome to the use thread challenge. So the first thing that I want you to do is that I want you to create the counter.jsx file.
2:17:21
Y dentro de ese archivo, tendrás que crear el componente contador. Y usar el hilo de uso para gestionar un hilo de contador simple.
And inside that file, you're going to have to create the counter component. And use the use thread to manage a simple counter thread.
2:17:27
Así que primero tendrás que inicializar el hilo proporcionando un valor cero allí. Luego crea un botón para incrementar tu contador en uno.
So first you will have to initialize the thread by providing a zero value to there. Then create a button to increment your counter by one.
2:17:34
Muestra el valor de ese contador para que podamos ver el resultado. Así que esta va a ser la primera parte de este desafío.
Display the value of that counter so that we can see the result. So this is going to be the first portion of this challenge.
2:17:39
Así que en la siguiente parte, tendrás que crear el archivo to-do list.jsx. Y luego tendrás que crear un componente con el nombre de lista de tareas.
So in the next portion, you're going to have to create the to-do list.jsx file. And then you have to create a component with the name of to-do list.
2:17:46
Luego usa el useStat una vez más para gestionar un estado simple o un arreglo de tareas dentro de ese estado. Inicializa el estado con un arreglo vacío.
Then use the useStat once again to manage a simple stat or array of to-dos inside that stat. Initialize the stat with empty array.
2:17:54
Luego crea un formulario para agregar un nuevo elemento de tarea en esa lista. Luego muestra el valor de esa lista de tareas. Y esa va a ser la segunda parte.
Then create a form to add a new to-do item in that list. Then display the value of that to-do list. And that's going to be the second portion.
2:18:01
Así que ahora para la tercera, tendrás que crear tu archivo profile.jsx. y dentro de eso vas a definir el componente de perfil.
So now for the third one, you're going to have to create your profile.jsx file. and inside that you're going to be defining the profile component.
2:18:08
Una vez más, vas a usar el hilo de uso para gestionar el objeto con la información del perfil del usuario.
Once again you're going to be using the use thread to manage the object with the user profile information.
2:18:13
Así que inicializa el hilo con un objeto que contenga el nombre y la edad y proporciona el campo de entrada para actualizar el nombre y también la edad.
So initialize the thread with object containing the name and age and provide the input field to update the name and also the age.
2:18:19
Luego finalmente muestra la información actualizada dentro de ese componente.
Then finally display the updated information inside that component.
2:18:23
Así que ahora para el cuarto paso tendrás que usar el hilo de uso una vez más y crear un archivo shopping list.jsx
So now for the fourth step you're going to have to use the use thread once again and create a shopping list.jsx
2:18:29
también el componente de lista de compras y usar el
file also the shopping list component and use the
2:18:32
hilo de uso para gestionar el arreglo de objetos donde cada objeto
use thread to manage the array of object where each object
2:18:36
representa un artículo de compra, por ejemplo, como el nombre y
represents a shopping item for example like the name and
2:18:39
también la cantidad, así que inicializa el hilo con el arreglo vacío y
also the quantity so initialize the thread with the empty array and
2:18:42
también crea un formulario para agregar un nuevo elemento a ese arreglo y
also create a form to add a new item to that array and
2:18:45
luego finalmente muestra la lista de artículos de compra, así que sí
then finally display the list of shopping items okay so yeah
2:18:48
así es como vas a importar allí para tu componente de aplicación, así que pueden ver todo, así que dale tu mejor esfuerzo, si puedes hacerlo, está completamente bien, luego vuelve y mira la solución, ahora te voy a dar mi solución
this is how you're going to be importing there for your app component so you guys can see everything so give it your best shot if you can do it that's completely okay then come back and watch the solution now i'm going to give you my solution
2:19:00
déjame crear mi archivo counter.jsx y
let me create my counter.jsx file and
2:19:03
voy a usar el rafce, guardar mi archivo, ir a mi aplicación y
i'm going to be using the rafce save my file go to my app and
2:19:06
registrar allí justo aquí, esto es correcto
register there right here this is right
2:19:09
sobre el mostrador presiona enter y solo cierra esto
over counter hit enter and just close this
2:19:12
voy a guardar mi archivo también voy a ejecutar mi servidor que estoy
i'm going to save my file i'm going to also run my server which i'm
2:19:16
ya haciendo así que déjame hacer eso una vez más y
already doing so let me just do that once again and
2:19:19
ahora estamos obteniendo nuestro contador que se ve increíble así que lo primero que quiero hacer es que quiero hacer un inicio así que solo usaré como usar stand y tan pronto como lo haga
now we are getting our counter which is looking amazing so the first thing that i want to do is that i want to make a start so i'll just use like use stand and as soon as i do
2:19:27
esto así que va a importar desde el react.js para el
this so it's going to import there from the react.js for the
2:19:30
valor inicial voy a especificar cero allí y voy a estar usando
initial value i'm going to specify zero to there and i'm going to be using
2:19:33
la desestructuración de arreglos para desestructurar el conteo y también el conjunto de conteo de allí ahora vamos a estar usando el conteo para mostrar el valor inicial
the array destructuring to destructure the count and also the set count out of there now we are going to be using the count to show the initial value
2:19:42
así que solo usaré como párrafo y yo
so i'll just use like paragraph and i
2:19:45
diré como hiciste clic y déjame renderizar mi conteo aquí conteo veces ahí vamos y también voy a proporcionar un botón que nos permitirá
will say like you clicked and let me just render my count right here count times there we go and also i'm going to provide a button which will allow us to
2:19:54
cambiar tu estado así que solo pondré el nombre de incrementar como una etiqueta y cada vez que alguien
change your state so I'll just put the name of increment as a label and whenever somebody
2:20:00
haga clic en ese botón vamos a activar esta función que
clicks on that button we are going to be firing this function which will
2:20:03
nos permite cambiar nuestros datos así que vamos a estar usando el conjunto de conteo
allows us to change our data so we are going to be using the set count
2:20:06
y ahora vamos a proporcionar el valor actualizado así que solo escribiré
and now we are going to be providing the updated value so i'll just write
2:20:09
como conteo más uno ahora déjame guardar mi archivo y
like count plus one now let me just save my file and
2:20:12
si hago clic en este incremento así que solo va a incrementar mi contador
if i click on this increment so it's going to just increment my counter
2:20:15
por uno está bien así que eso es genial pero también podemos decrementar
by one okay so that's cool but we can also decrement
2:20:19
nuestro contador así que déjame cambiar eso a decrementar y
our counter so let me just change that to decrement and
2:20:22
en lugar de proporcionar un más voy a cambiar eso a menos así que ahora voy a guardar
instead of providing a plus i'm going to change that to minus so now i'm going to save
2:20:25
mi archivo y ahora si hago clic en este decrementar así que va a decrementar mi contador por uno así que sí esa fue la primera parte de este
my file and now if i click on this decrement so it's going to decrement my counter by one so yeah that was the first portion of this
2:20:32
ejercicio ahora vamos a crear una lista de tareas así que voy a
exercise now we are going to be creating a to-do list so i'll
2:20:35
simplemente crear un componente o un archivo con el nombre de lista de tareas para
just create a component or a file with the name of to-do list to
2:20:39
lista de tareas.jsx voy a
do list.jsx i'll
2:20:42
usar mi rafc dentro de allí guardar mi archivo ir a mi aplicación y
use my rafc inside there save my file go to my app and
2:20:46
registrar allí mismo así que usaré como lista de tareas venir
register there right here so i'll use like to-do list come
2:20:50
así y cerrar cerrar mi archivo y
on like so and close close my file and
2:20:53
aquí puedes ver que ahora estamos obteniendo más lista de tareas que se ve increíble así que
here you can see we're now getting more to-do list which is looking amazing so
2:20:56
lo primero que queremos hacer es inicializar nuestro estado así que
the first thing that we want to do is that you want to initialize our state so
2:20:59
usaré como usar estado una vez más uh usar
i'll use like use state one more time uh use
2:21:02
estado ahí vamos y para el valor inicial vamos a estar
state there we go and for the initial value we're going to be
2:21:05
especificando un array vacío dentro de ahí ahora déjame
specifying empty array inside there now let me just
2:21:08
desestructurar mis tareas y también establecer tareas
destructure my to-dos and also set to-dos
2:21:11
fuera de ahí y ahora debajo de eso también vamos a manejar
out of there and now underneath that we're going to be also handling
2:21:14
nuestro formulario así que para la entrada del formulario vamos a crear un
our form so for form input we're going to be creating a
2:21:17
estado para el valor de entrada y luego establecer entrada
state for there like input value and then set input
2:21:21
vamos con el valor de entrada también
come on input value as well
2:21:24
y eso va a ser igual a usar estado y el valor inicial
and that's going to be equals to the use state and the initial value
2:21:27
se establecerá como una cadena vacía ahora vamos a entrar en la interfaz de usuario así que estoy
will be set to empty string now let's get into the ui so i'm
2:21:30
a punto de eliminar eso de aquí y voy a crear mi h1 que
going to remove that from here and i'm going to create my h1 which
2:21:34
simplemente seleccionará la lista de tareas y ahora debajo de este h1
will just select to do list and now underneath this h1
2:21:37
vamos a crear un formulario y no vamos a proporcionar ningún
we are going to be creating a form and we're not going to be providing any
2:21:40
acción para eso así que solo usaré como en enviar cuando alguien envíe
action to that so i'll just use like on submit when somebody submit
2:21:43
ahí vamos a disparar una función que se llama manejar enviar
there we're going to be firing a function which is called the handle submit
2:21:46
que vamos a crear en unos segundos y ahora dentro
which we are going to be creating in a few seconds and now inside
2:21:49
de este formulario vamos a definir nuestro campo de entrada para el valor
this form we are going to we're defining our input field for the value
2:21:53
especificaré el valor de entrada que
i'll specify the input value that
2:21:56
el estado que ya hemos definido aquí así que voy a copiar eso
state which we've already defined right here so i'm going to copy that
2:21:59
y ahora déjame colocar esto aquí así y
and now let me just place the here like so and
2:22:03
también voy a proporcionar el marcador de posición que seleccionará agregar un nuevo
i'm going to also provide the placeholder which will select add a new
2:22:06
para hacer voy a guardar mi archivo ahora y
to do i'm going to save my file right now and
2:22:09
no estamos obteniendo nada eso es porque no registramos este componente en ningún lugar así que voy a proceder a registrarlo oh ya hicimos eso pero ¿por qué no estamos
we are not getting anything that's because we did not register this component anywhere so i'm going to go ahead and register that oh we already did that but why aren't
2:22:18
no estamos obteniendo nada oh sabes qué, hemos
we're getting anything oh you know what uh we've
2:22:21
proporcionado esta función pero no creamos esta función así que
provided this function but we did not create this function so
2:22:24
por eso ahora estamos obteniendo ese error debajo de este campo de entrada, vamos
that's why we are now getting that error underneath this input field we're going
2:22:27
a definir nuestro botón que dirá algo como agregar tarea y
to be defining our button which will say like add to do and
2:22:30
el tipo se establecerá en enviar, así que nos permitirá enviar nuestro
the type will be set to submit so it's going to allow us to submit our
2:22:34
formulario, así que ahora debajo de este formulario también necesitaríamos
form so now underneath this form we would also need
2:22:37
renderizar o hacer, así que para eso voy a usar un ul y para este ul vamos a definir nuestras tareas y ahora déjame iterar sobre todo eso para hacer, así que solo escribiré algo como tarea
to render or to do so for that i'm going to be using a ul and for this ul we're going to be defining our to do's and now let me just iterate over through all of that to do so i'll just write like to do
2:22:47
y también el índice justo aquí, está bien, y dentro entonces
and also the index right here okay and inside then
2:22:51
vamos a definir nuestro li y aquí vamos a simplemente
we're going to be defining our li and here we are going to be just
2:22:54
proporcionar qué hacer para que podamos ver qué hacer, también
providing what to do so that we can see what to do you will
2:22:57
proporcionarás la clave y eso se establecerá en ese índice que estamos
also provide the key and that's going to be set to that index which we
2:23:00
agarrando, no podemos ver nada, eso es porque tenemos que
are grabbing we cannot see anything that's because like we have
2:23:03
crear esta función, así que voy a copiar allí y déjame crear esta función aquí mismo, así que solo usaré como cons handle submit, va a tomar el evento
to create this function so i'm going to copy there and let me just create this function right here so i'll just use like cons handle submit it's going to take the event
2:23:11
objeto, también voy a proporcionar mis llaves y
object i'm going to also provide my curly braces and
2:23:14
déjame usar como e punto prevent, vamos p-r-e-v-e-n-t
let me just use like e dot prevent come on p-r-e-v-e-n-t
2:23:18
prevenir el comportamiento predeterminado de allí
prevent default to prevent the default behavior of there
2:23:21
y también vamos a estar primero verificando el valor de entrada
and we are going to be also first of all checking the input value
2:23:24
y simplemente proporcionemos nuestro método trim allí, como si tienes
and let's just provide our trim method on there like if you have
2:23:28
espacios vacíos, así que simplemente elimínalos totalmente ahora
empty spaces so just totally remove them now
2:23:31
vamos a obtener nuestro set de tareas como este y vamos a cambiar el valor de esto, así que cómo lo vamos a hacer
we are going to be getting our set to dos like this one and we are going to be changing the value of this so how are we going to be doing
2:23:37
para hacer eso, lo primero que tenemos que hacer es hacer una
there to do that the first thing that we have to do is that we have to make the
2:23:40
copia del elemento existente que está disponible dentro
copy of the existing item which are available inside
2:23:44
de esta tarea, así que cómo lo vamos a hacer, lo adivinaste
this to do so how are we going to be doing there you guessed it
2:23:47
vamos a usar punto punto punto y las tareas a continuación
we are going to be using dot dot dot and to do's next
2:23:50
tenemos que proporcionar nuestro valor actualizado, así que para ese valor actualizado
we have to provide our updated value so for that updated value
2:23:54
vamos a usar como valor de entrada y ahora debajo de eso también vamos a vaciar nuestro campo de entrada, así que solo usaré como establecer el valor de entrada y establecerlo como una cadena vacía
we are going to be using like input value and now underneath there we are going to be also emptying out or input field so i'll just use like set input value and set that to empty string
2:24:04
ahora que eso está hecho, si guardo mi archivo, lo siguiente que tenemos que hacer es
now that's done so if i save my file the next thing that we have to do is
2:24:07
que también tenemos que vincular otra función aquí a esta entrada
that we also have to bind another function right here to this input
2:24:11
campo, así que cuando alguien cambie esto, usaré como en
field so when somebody change this i'll use like on
2:24:14
cambio, vamos a activar esta función que será un manejador
change we're going to be firing this function which will be a handle
2:24:17
cambio, así que voy a copiar eso y ahora déjame definir
change so i'm going to copy that and now let me define
2:24:20
mi función aquí, así que solo vamos a crear nuestro manejador de cambio, va a
my function right here so let's just create our handle change it's
2:24:23
tomar el objeto de evento una vez más, solo vamos a proporcionar nuestro signo igual allí y ahora vamos a usar como establecer el campo de entrada, no tanto, vamos a definir nuestro valor de entrada establecido
going to take the event object one more time let's just provide our equal to sign there and now we are going to be using like set input field not that much we're going to be defining our set input value
2:24:34
y va a tomar ese event.target.value como cualquier cosa que especifiquemos dentro de este campo de entrada. Así que va a tomar eso.
and it's going to take that event.target.value like anything we specify inside this input field. So it's going to take that.
2:24:41
Va a aparecer aquí en el valor de entrada. Así que ahora voy a guardar mi archivo y ahora déjame escribir como no sé, como pasear al perro.
It's going to show up right here to the input value. So now I'm going to save my file and now let me write like I don't know like walk the dog.
2:24:48
Oh Dios mío, pasear al perro. Déjame hacer clic en agregar a la lista de tareas. Así que va a agregar eso aquí.
Oh my god walk the dog. Let me click on the add to do. So it's going to add that right here.
2:24:54
También puedes escribir como no sé y hacer clic en esto. Va a agregar eso aquí a esta lista de tareas.
You can also write like I don't know and click on this. It's going to add that right here to this to-do list.
2:25:01
Así que sí, ese fue otro ejemplo de esta lista de tareas. A continuación, tenemos que crear nuestro perfil, así que solo crearé un componente con el nombre de profile.jsx.
So yeah that was another example of this to-do list. Next we have to create our profile so I'll just create a component with the name of profile.jsx.
2:25:08
Estaré usando el RAFC dentro de ahí y
I'll be using the RAFC inside there and
2:25:11
lo primero que quiero hacer es inicializar mi perfil o mi estado con el valor de perfil, así que usaré como useState y el valor inicial se establecerá en este objeto y voy a especificar el nombre.
the first thing that I want to do is that I want to initialize my profile or my state with the value of profile so I'll use like you state and the initial value will be set to this object and I'm going to specify the name.
2:25:22
El nombre se establecerá en una cadena completamente vacía. También vamos a proporcionar un borde y el borde también se establecerá en una cadena completamente vacía.
Name will be set to totally empty string. We're going to be also providing an edge and edge will be also set to totally empty string.
2:25:28
Así que lo que voy a hacer es desestructurar algunas cosas de ahí.
So what I'm going to do is that I'm going to destructure a few things out of there.
2:25:32
Así que vamos a desestructurar el perfil y también el setProfile de este usado aquí. Así que eso está hecho.
So we're going to be destructuring the profile and also the set profile from this used here. So that's done.
2:25:38
A continuación, tenemos que ir y eliminar este perfil de allí y
Next we have to go ahead and remove this profile from there and
2:25:41
voy a usar h2 y seleccionaré perfil de usuario y
I'm going to be using h2 and I'll select user profile and
2:25:45
ahora debajo de este h2 vamos a crear nuestro div y dentro
now underneath this h2 we're going to be creating our dev and inside
2:25:48
de ese div, solo proporcionemos nuestra etiqueta y no vamos a proporcionar
there dev let's just provide our label and we're not going to be providing
2:25:51
valores html4 a esto, solo lo eliminaré de aquí y
any html4 values to this i'll just remove that from here and
2:25:55
solo voy a decir nombre y ahora dentro de esta etiqueta
i'm going to only say name and now inside this label
2:25:58
incluso vamos a definir nuestro campo de entrada, está bien, así que el
even we are going to be defining our input field okay so the
2:26:01
el tipo se establecerá en texto, también vamos a proporcionar el nombre
type will be set to text we're going to be also providing the name
2:26:04
y el nombre se establecerá en nombre y simplemente proporcionemos el valor y
and name will be set to name and let's just provide the value and
2:26:08
el valor vendrá de profile.name, está bien
value will be coming from the profile.name okay
2:26:11
así que este es profile.name que vendrá de allí y cuando alguien escriba algo dentro de ahí, vamos a
so which is this profile.name which will be coming from there and when somebody types something inside there we're going to be
2:26:20
disparar esta función que dirá como manejar el cambio
firing this function which will say like handle change ching
2:26:23
ahí vamos, así que vamos a crear esta función en unos segundos
there we go so we're going to be creating this function in a few seconds
2:26:27
pero sabes qué, primero voy a ocuparme
but you know what i'm going to first of all take
2:26:30
del resto de estas etiquetas y cosas, está bien, así que debajo de esto
care of the rest of these labels and stuff okay so underneath this
2:26:33
div déjame definir otro div, vamos a proporcionar una vez más
div let me define another div we're going to be once again providing
2:26:36
una etiqueta, no vamos a proporcionar un valor html4 a ellos
a label we're not going to be providing an html4 value to them
2:26:39
y dentro de esta etiqueta, lo primero que quiero hacer es proporcionar mi edad y simplemente proporcionemos nuestro campo de entrada aquí, así que el tipo se establecerá en número, voy a
and inside this label the first thing that i want to do is that i want to provide my age and let's just provide our input field right here so the type will be set to number i'm going to
2:26:48
proporcionar el nombre de edad y también voy a proporcionar el valor y el valor se establecerá en profile
provide the name of edge and i'm going to also provide the value and value will be set to profile
2:26:53
punto edad que vendrá de mi estado y cuando alguien
dot edge which will be coming from my state and when somebody
2:26:56
cambie, una vez más vamos a disparar este manejar cambio
change there once again we are going to be firing this handle change
2:26:59
función en unos segundos que vamos a crear, está bien
function in a few seconds which we are going to be creating okay
2:27:02
así que ahora debajo de este div vamos a usar nuestro h3 y
so now underneath this div we're going to be using our h3 and
2:27:06
usaré como información del perfil y ahora
i'll use like profile information and now
2:27:09
debajo de esta información del perfil, así que simplemente renderizaré todos esos valores que voy a proporcionar en mi campo de entrada, así que simplemente escribiré como nombre y voy a usar como
underneath this profile information so i'll just like render all of that values which i'm going to be providing in my input field so i'll just write like name and i'm going to use like
2:27:17
profile.name y también voy a crear una edad
profile.name and also i'm going to be creating an edge
2:27:21
y aquí vamos a renderizar el profile.edge
and here we are going to be rendering the profile.edge
2:27:24
así que ahora déjame guardar ahí y finalmente déjame crear este manejar
so now let me just save there and finally let me just create this handle
2:27:27
cambio función y eso va a estar aquí, así que lo que voy a
change function and that's going to be here so what i'm going
2:27:30
hacer es que voy a escribir como manejar cambio, va a tomar el evento
to do is that i'm going to write like handle change it's going to take the event
2:27:33
objeto y dentro de esta función vamos a desestructurar
object and inside this function we are going to be destructuring
2:27:37
como eh el nombre y también el valor de este event.target value t-a-r-g-e-t, ahí vamos y también vamos a usar el set
like uh the name and also the value out of this event.target value t-a-r-g-e-t there we
2:27:44
vamos y también vamos a usar el conjunto
go and we're going to be also using the set
2:27:47
perfil y aquí tenemos que especificar el anterior así que
profile and here we have to specify the previous one so
2:27:50
vamos a estar usando como el perfil anterior y es
we are going to be using like previous profile and it's
2:27:53
vamos a etiquetar ese evento, va a tomar esta función de callback así que
gonna tag that event it's gonna take this callback function so
2:27:56
primero tenemos que desglosar el perfil anterior y
first of all we have to spread out the previous profile and
2:28:00
ahora tenemos que especificar el nuevo así que vamos a tomar el nombre
now we have to specify the new one so we are going to be taking the name
2:28:03
y tenemos que proporcionar el nuevo valor allí, está bien
and we have to provide the new value to there okay
2:28:06
así que voy a guardar mi archivo y eso va a estar aquí para todo este perfil, déjame mostrarte esto, así que voy a refrescarlos, oh primero tenemos que registrar
so i'm going to save my file and that's going to be here for this entire profile let me just show you this so i'm going to refresh them oh first of all we have to register
2:28:14
allí en nuestro componente de la aplicación, así que voy a comentar esto
there into our app component so i'm going to comment this
2:28:17
lista de tareas y voy a registrar mi componente de perfil
to-do list and i'm going to register my profile component
2:28:20
ahí vamos, guardo mi archivo y ahora estamos obteniendo
there we go save my file and now we are getting
2:28:24
nuestro componente de perfil, así que primero si especifico algún tipo de un
our profile component so first if i specify some sort of a
2:28:27
nombre como hosan y se va a añadir allí mismo para
name like hosan and it's going to add there right here for
2:28:30
este nombre aquí, uh no sé, como 20
this name right here uh i don't know like 20
2:28:33
o 22 o algo así, así que se va a añadir automáticamente
or 22 or something like that so it's going to automatically add
2:28:37
allí mismo, uh para esta información del perfil así que
there right here uh for this profile information so
2:28:40
ese fue otro y ahora hablemos del final
that was another one and now let's talk about the final one
2:28:43
que será la lista de compras, así que voy a comentar esta línea
which will be the shopping list so i'm going to comment this line out
2:28:47
y déjame continuar y crear mi lista de compras así que
and let me just go ahead and create my shopping list so
2:28:50
vamos, lista de compras.jsx, estoy
come on shopping list.jsx i'm
2:28:53
usando mi rafce así que mi archivo va a
going to be using my rafce so my file go to
2:28:56
el app.js y usar nuestra lista de compras
the app.js and use our shopping list
2:29:00
y renderizar allí, guardo mi archivo una vez más y lo primero que quiero hacer es inicializar todo mi estado, así que solo crearé como items y también set items y eso va a ser igual a
and render there save my file once again and the first thing that i want to do is that i want to initialize all of my state so i'll just create like items and also set items and that's going to be equals to
2:29:12
usar set y el valor inicial se establecerá en vacío, ahora vamos a
used set and the initial value will be set to empty now we are going to
2:29:15
también crear uno para el nombre, así que set name va a ser
be also creating one for the name so set name is going to be
2:29:18
igual al estado de uso y el valor inicial se establecerá como cadena vacía
equals to the use state and the initial value will be set to empty string
2:29:21
también vamos a crear uno para la cantidad y
we're going to be also creating one for the quantity and
2:29:24
también establecer cantidad ahí vamos es
also set quantity there we go it's
2:29:28
igual al estado de uso y vamos a operar la cadena vacía
going to be equals to the use state and we're going to be operating the empty
2:29:31
cadena dentro de ahí ahora déjame ir a la interfaz de usuario
string inside there now let me just go ahead and go to the ui
2:29:34
y eliminar la lista de compras de ahí voy a escribir mi h1
and remove the shopping list from there i'm gonna write my h1
2:29:37
que dirá como lista de compras y debajo de este h1
which will say like shopping list and underneath this h1
2:29:40
esto es crear nuestro formulario no vamos a proporcionar ninguna acción a
this is create our form we're not going to be providing any action to
2:29:43
ellos pero vamos a proporcionar el controlador de envío y
them but we are going to be providing the on submit handler and
2:29:47
cuando alguien envíe eso entonces vamos a encontrar
when somebody submit that then we are going to be finding
2:29:50
esta función bien así que vamos a crear nuestro campo de entrada
this function okay so let's just create our input field
2:29:53
dentro de ahí el tipo será texto y también vamos a
inside there the type will be text and we're going to be also
2:29:56
proporcionar un marcador de posición que dirá como nombre del artículo
providing a placeholder which will say like item name
2:29:59
o algo así y también vamos a especificar el valor
or something like that and we're going to be also specifying the value
2:30:02
y el valor vendrá del nombre
and value will be coming from the name
2:30:06
así que voy a copiar ahí y vamos a proporcionar ahí mismo y
so i'm going to copy there and let's just provide there right here and
2:30:09
cuando alguien intente cambiarlos vamos a activar esta función así que
when somebody tries to change them we're going to be firing this function so
2:30:12
usaré como establecer nombre y voy a escribir como evento punto objetivo punto valor así que voy a guardar mi archivo y eso será todo por esto
i'll just use like set name and i'm going to write like event dot target dot value so i'm going to save my file and that's going to be it for this
2:30:20
primer campo de entrada y ahora podemos duplicar esto totalmente estoy
first input field and now we can totally duplicate this i'm
2:30:23
voy a seleccionar ahí y duplicarlos aquí tenemos
going to select there and duplicate them here we have
2:30:26
cambiar el tipo a número también tienes que cambiar eso a
to change the type to number you also have to change that to
2:30:29
cantidad así que cantidad ahí vamos también tenemos que especificar el valor como cantidad y también establecer cantidad ahí vamos
quantity so quantity there we go we also have to specify the value like quantity and also the set quantity there we go
2:30:40
ok así que eso será todo ahora debajo de eso también vamos a crear un botón que
okay so that's going to be it now underneath that we are going to be also creating a button which
2:30:44
dirá como agregar artículo y aquí tenemos
will say like add item and here we
2:30:47
que especificar el tipo que se establecerá en enviar en
have to specify the type which will be set to submit in
2:30:50
en minúsculas enviar ahí vamos ahora eso es genial y todo
lower case submit there we go now that's cool and everything
2:30:54
pero la última cosa que tenemos que hacer es que tenemos que mostrar nuestra compra
but the final thing that we have to do is that we have to show our shopping
2:30:57
lista así es como vamos a crear nuestra lista de compras
list this is how we are going to be creating our shopping list
2:31:00
vamos a proporcionar un nombre de nuestro artículo que vamos a
we're going to be providing a name of our item we're going to be
2:31:03
también proporcionar una cantidad y cuando alguien haga clic en este botón se va a agregar allí pero también tenemos que mostrar esa cantidad y también
also providing a quantity and when somebody clicks on this button so it's going to add there but we also have to show that quantity and also
2:31:10
el nombre así que para mostrarlos vamos a usar nuestro
the name so to show them we're going to be using our
2:31:13
ul y dentro de este ul vamos a usar como items.map
ul and inside this ul we're going to be using like items.map
2:31:17
y tenemos esos artículos que hemos declarado arriba
and we have that items which we have declared up above
2:31:20
tenemos todos sus artículos justo aquí va a tomar el artículo
we have all of their items right here it's going to take the item
2:31:23
y también va a tomar el índice también y dentro de ahí
and it's going to also take the index as well and inside there
2:31:26
vamos a proporcionar qué li y va a tomar la clave
we're going to be providing what li and it's going to take the key
2:31:29
y la clave vendrá del índice y para el valor vamos a usar como item.name y luego vamos a
and key will be coming from the index and for the value we're going to be using like item.name and then we're going to be
2:31:36
también proporcionar la cantidad q u n t i
also providing the quantity q u n t i
2:31:39
t y y la cantidad será item.dot cantidad
t y and quantity will be item dot quantity
2:31:43
ahí vamos oh sabes qué déjame cambiar ahí
there we go oh you know what let me just change there
2:31:46
a punto y coma así que voy a guardar mi archivo siguiente
to semicolon so i'm going to save my file next
2:31:49
tenemos que crear nuestra función de manejar enviar que hemos especificado aquí así que déjame ir y crear eso voy a usar como manejar enviar va a tomar el objeto de evento
we have to create our handle submit function which we've specified right here so let me just go ahead and create that i'm going to be using like handle submit it's going to take the event object
2:31:59
dentro de ahí vamos a prevenir el comportamiento predeterminado primero que todo y ahora dentro de ahí
inside there we are going to be preventing the default behavior first of all and now inside there
2:32:04
vamos a verificar si no tenemos el nombre o
let's just check if we don't have the name or
2:32:07
si no tenemos la cantidad así que en esta situación vamos
if we don't have the quantity so in this situation we
2:32:10
a devolver solo como nada básicamente así que
are going to be only returning like nothing basically so
2:32:14
solo queremos detener nuestra ejecución ahí si eso no es el
we just want to stop our execution there if that's not the
2:32:17
caso y si solo tenemos como ya sea el nombre o la cantidad
case and if we only have like either the name or the quantity
2:32:20
así que en esta situación vamos a crear nuestro nuevo objeto
so in this situation we are going to be creating our new object
2:32:23
que seleccionará nuevo artículo artículo ahí vamos y vamos a crear nuestro nuevo objeto de artículo va a tomar el nombre vamos a
which will select new item item there we go and we're going to be creating our new item object is going to take the name we're going to
2:32:31
también estamos proporcionando la cantidad pero en este caso
we're also providing the quantity but in this case
2:32:34
también podemos escribir como cantidad así
we can also just write like quantity just like so we
2:32:37
podemos incluso eliminar uno de ellos si quisieras pero ahora en esta
can even remove one of them if you wanted to but now in this
2:32:40
situación vamos a convertir nuestra cantidad a un número
situation we are going to be converting our quantity to a number
2:32:43
así que para convertir eso a un número vamos a usar el parse integer y
so to convert that to number we are going to be using the parse integer and
2:32:47
aquí tenemos que especificar nuestra cantidad así que ahora déjame guardar allí y así es como vamos a crear nuestro nuevo ítem y ahora tenemos que establecer eso en este set item así que
here we have to specify our quantity so now let me just save there and this is how we are going to be creating our new item and we have to now set that to this set item so
2:32:56
simplemente continuaré y usaré mis elementos establecidos este
i'll just go ahead and use my set items this
2:33:00
se proporcionaron nuestros elementos anteriores y aquí estamos
is provided our previous items and here we are
2:33:03
vamos a usar primero que nada vamos a clonar nuestros elementos anteriores y
going to be using first of all let's just clone our previous items and
2:33:06
vamos, qué demonios estoy haciendo, déjame clonar
come on what the hell am i doing let me just clone
2:33:09
este ítem anterior y también proporcionar una coma allí y
this previous item and also provide a comma there and
2:33:12
usaré mi nuevo ítem aquí, está bien, y también vamos
use my new item right here okay and also we
2:33:16
a limpiar el campo de entrada así que vamos a usar como uh set name y también el set quantity y simplemente proporcionemos una cadena vacía para todos ellos
are going to be clearing the input field so we are going to be using like uh set name and also the set quantity and let's just provide empty string for all of them
2:33:24
ahora eso es todo, has terminado, voy a vender mi archivo, mira esto
now that's all you're done i'm going to sell my file check this out
2:33:27
así que tenemos nuestra lista de compras, así que puedo escribir como um
so we have our shopping list so i can just write like um
2:33:30
computadora y eso es
computer and that's
2:33:33
va a ser como 3000 o algo así, no
going to be like 3000 or something like that i
2:33:37
puedo ni siquiera hablar más, maldita sea, déjame hacer clic en este agregar
can't even speak no more god damn it let me click on this add
2:33:40
ítem, ahora nos va a dar el nombre del ítem y también va a
item now it's going to give us the name of the item and it's going to also
2:33:43
darnos la cantidad y la cantidad es esa, así que yo
give us the quantity and quantity is that much so i
2:33:46
puedo escribir como básicamente cualquier cosa que quiera y puedo agregar
can just write like basically anything i want and i can add
2:33:49
eso y aquí puedes ver que ahora estoy obteniendo ese mismo resultado, así que sí, eso fue un gran desafío pero espero que valiera la pena
that and here you can see i'm now getting that same result so yeah that was a huge challenge but i hope that was worth it
2:33:56
porque use state es lo más
because use state is the most
2:33:59
importante en react.js y tienes que asegurarte de que
important thing in react.js and you have to make sure that
2:34:02
domines el use state, así que eso fue un gran
you master the use state so that was a huge
2:34:05
desafío sobre el estado de uso y incluso construiste como tres o cuatro
challenge about the use state and you even build like three or four
2:34:09
desafíos o tal vez tus proyectos para ser precisos, así que yo
challenges or maybe your projects to be precise so i
2:34:12
puedo descomentar todos ellos y ahora, déjame mostrarte
can totally uncomment all of them and now and now let me show
2:34:15
todo eso y aquí puedes ver que ahora podemos incrementar y
you all of that and here you can see we can now increment and
2:34:18
también decrementar, también podemos agregar un nuevo que hacer, podemos
also decrement we can also add a new to do we
2:34:21
también simplemente proporcionar un nombre y también la edad si así lo deseas
can also just provide a name and also the age if you wanted to
2:34:24
y lista de compras, tú ponle el nombre que quieras, así que
and shopping list you name it okay so we
2:34:27
estaríamos obteniendo totalmente nuestro valor que ahora se ha añadido, así que
would be totally getting our value which is now added so
2:34:30
ahora hablemos sobre el portal de react, así que ¿qué quiero decir con react?
now let's talk about the react portal so what do i mean by react
2:34:33
portal, el portal de react es una característica que te permite
portal react portal is a feature that allows you to
2:34:36
renderizar un componente hijo en un nodo DOM que existe
render a child component into a dom node that exists
2:34:39
fuera de la jerarquía del componente padre, así que esto puede ser útil para escenarios como cuando estamos creando un modelo
outside the hierarchy of the parent component so this can be useful for scenarios like whenever we are creating a model
2:34:46
o tooltips o menús desplegables donde quieres romper la estructura habitual padre-hijo y renderizar en una parte diferente del DOM.
or tooltips or drop-down menus where you want to break out of the usual parent-child structure and render in a different part of the DOM.
2:34:55
Así que, puedes pensar en el portal como el portal de Rick y Morty,
So, you can think about the portal is just like the Rick and Morty portal,
2:35:01
bien, que te permitirá ir a cualquier parte dentro de tu DOM. Así que eso fue solo una teoría básica.
okay, so which will allow you to go to anywhere inside your DOM. So that was just a basic theory.
2:35:06
Y ahora vamos a entrar en la codificación y entonces sabrás de qué estoy hablando.
And now let's get into the coding and then you will get to know what I'm talking about.
2:35:09
Así que para aprender sobre el portal de React, primero vamos a crear una carpeta de componentes.
So to learn about the React portal, first of all, we're going to be creating a components folder.
2:35:14
Y dentro de esta carpeta, vamos a definir nuestro archivo copy input.jsx.
And inside this folder, we are going to be defining our copy input.jsx file.
2:35:19
Y dentro de este archivo, vamos a crear nuestro archivo rafce.se. Ve a mi app. y renderiza este componente aquí mismo.
And inside this file, we're going to be creating our rafce.se file. Go to my app. and render this component right here.
2:35:27
Así que usaré como copy input y cerraré eso. Así que lo primero que quiero hacer es crear un componente simple.
So I'll use like copy input and close that. So the first thing that I want to do is that I want to just make a simple component.
2:35:33
Así que crearé un estado con el nombre de valor de entrada.
So I'll just create a stat with the name of like input value.
2:35:37
Vamos, el valor de entrada también va a tomar un conjunto de valor de entrada.
Come on input value is going to also take a set input value.
2:35:41
Así que vamos a establecer eso con el uso de estado y para el valor inicial solo vamos a proporcionar una cadena vacía.
So we're going to be setting that with the use stat and for the initial value we're going to be providing only empty string.
2:35:48
También vamos a crear otro conjunto para el copiado y luego establecer copiado
We're going to be also creating yet another set for the copied and then set copied
2:35:53
así que será igual al uso de hilo una vez más y
like so it's going to be equals to the use thread once again and
2:35:56
para el valor inicial vamos a especificar falso allí está bien
for the initial value we're going to be specifying false to there okay
2:35:59
eso también está hecho ahora vamos a entrar en la interfaz de usuario y
that's also done now let's get into the ui and
2:36:02
voy a eliminar este texto de entrada de copia de aquí y voy a
i'm going to remove this copy input text from here and i'm going to
2:36:05
crear mi campo de entrada dentro de allí dios esto
create my input field inside there god this
2:36:09
el teclado es súper rápido proporcionaré el valor y
keyboard is super fast i'll provide the value and
2:36:12
el valor vendrá del valor de entrada que estás creando arriba y cada vez que alguien intente cambiar algo dentro de esto
the value will be coming from the input value which you are creating up above and whenever somebody tried to change something inside this
2:36:19
Así que vamos a activar esta función y proporcionar o establecer el campo de entrada aquí.
So we're going to be firing this function and providing or set input field right here.
2:36:25
Y el valor inicial se establecerá en event.target.value. Y sí, supongo que estará bien.
And the initial value will be set to event.target.value. And yeah, I guess that's going to be fine.
2:36:30
Pero también vamos a crear un botón que dirá algo como copiado o copiar estaría bien. Está bien.
But we're going to be also creating a button which will say like copied or copy would be fine. Okay.
2:36:36
Así que cada vez que alguien haga clic en este botón, vamos a activar esta función de copia o manejar la copia.
So whenever somebody clicks on this button, we're going to be firing this copy or handle copy function.
2:36:41
Así que ahora déjame copiar eso y crear esta función aquí. Así que usaré como cons manejar copia, crear esta función de error aquí.
So now let me copy that and create this function right here. So I'll use like cons handle copy, create this error function right here.
2:36:47
Así que vamos a usar como navegador y un V I G A T O R. Esta es una función de JavaScript.
So we're going to be using like navigator and a V I G A T O R. This is a JavaScript function.
2:36:53
Así que tenemos que usar la propiedad del portapapeles allí y quieres escribir texto en eso es lo que usas como escribir texto.
So we have to use like clipboard property on there and you want to write text to that is what use like write text.
2:37:02
Y aquí tenemos que especificar qué valor de entrada. Y también queremos usar el método then porque vamos a retrasar allí.
And here we have to specify what input value. And also we want to use the then method because we're going to be delaying there.
2:37:09
Así que simplemente usemos nuestro método then y dentro de allí vamos a proporcionar un set copy y proporcionar verdadero a ellos.
So let's just use our then method and inside there we're going to be providing a set copy and provide true to them.
2:37:17
también tenemos que usar nuestro set timeout y aquí tenemos que especificar
we also have to use our set timeout and here we have to specify
2:37:20
nuestra función de callback y para esta función de callback vamos a
our callback function and for this callback function we're going
2:37:23
proporcionar nuestro set copy que se establecerá en falso tú
to be providing our set copy which will be set to false you
2:37:26
quieres simplemente establecer eso en falso y también quieres proporcionar
want to just set that to false and also you want to provide
2:37:29
dos segundos de retraso para eso así que ahora déjame guardar
two seconds of delay to that so now let me just save
2:37:33
mi archivo y revisar esto así que aquí puedes ver que tenemos nuestro
my file and check this out so here you can see we have our
2:37:36
campo de entrada puedo escribir lo que quiera escribir dentro
input field i can type whatever i want to type inside
2:37:39
allí escribo como hosan web depth y ahora si
there i write like hosan web depth and now if
2:37:42
hago clic en esta copia y si voy a la nueva pestaña y
i click on this copy and if if i go into the new tab and
2:37:45
colocarlo aquí así que aquí puedes ver que ahora estamos obteniendo lo que estaba en rep dev bien
place it right here so here you can see we're now getting what was in rep dev right
2:37:48
aquí lo cual es genial ahora lo siguiente que queremos hacer es que queremos
here which is cool now the next thing that we want to do is that we want
2:37:51
crear nuestro componente de contenido emergente .jsx
to create our pop up content dot jsx component
2:37:55
y voy a estar usando mi rafc dentro de ahí así que déjame pegar esto copiado como una prop a esta función así que aquí voy a estar renderizando mi componente emergente
and i'm going to be using my rafc inside there so let me just paste this copied as a prop to this function so here i'm going to be rendering my pop up component
2:38:06
cerremos ahí y vamos a pasar esto copiado como esta prop copiada aquí
let's just close there and we're going to be passing this copied as this copied prop right here
2:38:11
ahora déjame ir y agarrar eso usando la desestructuración
now let me go ahead and grab that by using the destructuring
2:38:15
así que ahora déjame guardar mi archivo y ahora voy a cambiar eso a una sección así que solo escribiré una sección aquí lo que fue que este teclado es súper rápido así que ahora déjame cambiar eso a una sección
so now let me just save my file and now i'm going to change that to a section so i'll just write a section right here what the was that this keyboard is super fast so now let me just change that to a section
2:38:27
dios s-a-c-t-i-o y ahí vamos bien y también voy a cambiar esta etiqueta y aquí tenemos que verificar si copiamos el contenido así que lo que significa que quieres mostrar esta interfaz de usuario así que usaré como
god s-a-c-t-i-o and there we go okay and i'm going to also change this label and here we have to check if we copied the content so which means you want to show this ui so i'll use like
2:38:39
div dentro de este div está bien como copiado a
div inside this div all right like copied to
2:38:42
portapapeles así que está bien así que
clipboard like so okay so
2:38:45
ahora déjame guardar mi archivo pero también quiero proporcionar un poco de estilo a
now let me just save my file but i also want to provide a bit of styling to
2:38:48
esto así que usaré como estilo y aquí para el estilo vamos a estar
this so i'll use like style and here for the style we are going to be
2:38:51
proporcionando una posición y la posición se establecerá en absoluta y
providing a position and position will be set to absolute and
2:38:55
también queremos proporcionar el fondo y el fondo será
we also want to provide the bottom and bottom will be
2:38:58
establecido en solo tres rems ahora déjame ir y revisar esto así que ahora déjame refrescar ahí y si escribo algo dentro de ahí y yo
set to only three rems now let me go ahead and check this out so now let me just refresh there and if i type anything inside there and i
2:39:06
hago clic en este botón de copiar nos va a mostrar esto copiado al
click on this copy button it's going to show us this copy to the
2:39:09
portapapeles y luego desaparecerá déjame intentar allí una vez más
clipboard and then it will disappear let me try there once again
2:39:12
si hago clic en este copiar nos va a mostrar este contenido copiado
if i click on this copy it's going to show us this copied content
2:39:15
y luego hará que desaparezca así que sí, eso es genial
and then it will make it disappear so yeah that's cool
2:39:18
y todo pero ahora déjame mostrarte el árbol dom si abro mi
and everything but now let me show you the dom tree if i open my
2:39:21
consola quiero decir como el elemento déjame ir al cuerpo déjame también ir a la raíz así que aquí puedes ver todo nuestro contenido déjame hacer zoom un poco todo nuestro
console i mean like the element let me go to the body let me also go to the root so here you can see all of our content let me just zoom in a bit all of our
2:39:30
contenido ahora está disponible dentro de esta raíz y esta raíz proviene de este archivo index.html.
content is now available inside this root and this root is coming from this index.html file.
2:39:36
Así que aquí puedes ver que tenemos un div y dentro de este div tenemos el ID de raíz.
So here you can see we have a div and inside this div we have the ID of root.
2:39:40
Ahora estamos seleccionando ahí y ahora estamos renderizando todo nuestro contenido a esa raíz aquí.
We are now selecting there and we are now rendering all of our content to that root right here.
2:39:46
Pero supongamos que no queremos renderizar nuestro contenido a este div.
But let's suppose if we don't want to render our content to this div.
2:39:49
Así que supongamos que queremos renderizar nuestro contenido al cuerpo o a algún otro lugar. Así que cómo en el mundo vamos a hacer eso.
So let's suppose if we want to render our content to the body or somewhere else. So how in the world we are going to be doing there.
2:39:55
Así que supongamos que queremos renderizar nuestro contenido en el cuerpo o en algún otro lugar. Entonces, ¿cómo vamos a hacer eso?
So to do that you guessed it we are going to be using the react.
2:40:00
portal, así que primero vamos a importar el react
portal so first of all we are going to be importing the react
2:40:03
portal, así que usaré algo como importar y luego crear portal
portal so i'll use like import and then create portal
2:40:06
y vamos a obtenerlo de la
and we are going to be getting there from the
2:40:09
react dom, no de react js, sino
react dom not from the react js but
2:40:12
de la react dom, así que primero tienes que
from the react dom okay so first of all you have
2:40:15
importar este crear portal y ahora para usarlos, así es como vamos a usarlo. Así que ahora déjame llamar a este crear portal aquí y aquí lo primero que tenemos que hacer es especificar
to import this create portal and now to use them this is how we are going to be using that so now let me just call this create portal right here and here the first thing that we have to do is that we have to specify
2:40:27
qué contenido quieres renderizar, intentando renderizar el
what content you want to render trying to render the
2:40:30
h1 o cualquier tipo de contenido que quieras renderizar, eso va a ser
h1 or any kind of content that you want to render that's
2:40:33
el primer perímetro. A continuación, también tienes que especificar
going to be the first perimeter next you also have to specify
2:40:36
dónde quieres renderizarlos, así que usaré algo como
where you want to render them so i'll just use like
2:40:39
algo más, pero primero voy a ir a mi index.html
something else but first of all i'm going to go ahead and go into my index.html
2:40:44
archivo y aquí voy a renderizar como algún tipo de div que tendrá contenido emergente o algo así. Así que aquí puedes ver que definí mi propio div con el ID de contenido emergente.
file and here i'm going to just render like some sort of a div which will have like pop up content or something like this so here you can see i defined my own div with the ID of pop-up content.
2:40:55
Voy a copiar eso de aquí. Y ahora déjame poner una coma allí una vez más. Así que solo pondré una coma aquí.
I'm going to copy that from here. And now let me go ahead and put a comma there once again. So I'll just put a comma here.
2:41:01
Ahora tenemos que seleccionar ese div. Así que usaré algo como document.querySelector, no select all, sino solo un query selector.
Now we have to select that div. So I'll use like document.querySelector, not select all, but just a query selector.
2:41:10
Y dentro de este query selector, queremos acceder a ese div, que acabamos de crear aquí.
And inside this query selector, we want to access that div, which we just created right here.
2:41:15
Así que primero tenemos que poner este símbolo de libra y luego tenemos que especificar este contenido emergente.
So first of all, we have to put this pound symbol and then we have to specify this pop-up content.
2:41:20
Así que ahora, si guardo mi archivo y actualizo, ¿qué estamos obteniendo? Estamos
So now if I save my file and refresh there and what are we getting we
2:41:23
obteniendo este contenido emergente. Ahora, si lo expando y
are now getting this pop-up content now if i expand that and
2:41:27
dentro de allí tenemos nuestra sección, así que dentro de allí
inside there we have our section so inside there
2:41:30
aquí puedes ver que tenemos nuestra sección y esta sección está actualmente vacía
here you can see we have our section and this section is currently empty
2:41:33
porque no copiamos nuestro contenido. Así que aquí puedes
because we did not copy our content so here you
2:41:36
ver que si solo escribo algo y tan pronto como haga clic
can see if i just type something and as soon as i click
2:41:39
allí, va a renderizar mi contenido aquí y luego
on there it's going to render my content right here and then
2:41:42
hará que desaparezca. Así que sabes qué, déjame poner un poco más de retraso a esto, así que cambiemos a cinco segundos, estaría bien. Así que ahora, si guardo mi archivo y ahora déjame pasar como
it will make it disappear so you know what let me put a bit more delay to this so let's change there to five second would be fine so now if i save my file and now let me just pass like
2:41:51
porque entonces tenemos dev y si hago clic en esto copiar y aquí puedes ver si expando allí y sí, ahora estamos obteniendo este dev.
because then we have dev and if I click on this copy and here you can see if I expand there and yeah we are now getting this dev.
2:41:59
Déjame intentar allí una vez más. Expande allí. Sí, ahora estamos obteniendo esto copiado al portapapeles.
Let me try there once again. Expand there. Yep we are now getting this copied to the clipboard.
2:42:05
Así que sí, así es como vamos a renderizar nuestro contenido a otra parte de nuestro DOM utilizando el portal de react.
So yeah this is how we are going to be rendering our content to another part of our DOM by using the react portal.
2:42:11
Así que ya hemos visto claves en la sección de lista. Quiero explicar allí un poco más.
So we've already seen keys in the list section. I want to explain there a bit more.
2:42:15
Así que lo que voy a hacer es que voy a crear mi carpeta de componentes y
So what I'm going to do is that I'm going to create my components folder and
2:42:19
dentro de esta carpeta voy a crear un switcher.jsx
inside this folder I'm going to create a switcher.jsx
2:42:22
y solo escribiré mi RFC dentro de allí y registraré
and I'll just write my RFC inside there and register
2:42:25
ahí justo aquí dentro de mi componente de aplicación switcher
there right here inside my app component switcher
2:42:29
ahí vamos, ahora déjame ir y acceder a mi componente y primero
there we go now let me go ahead and go to my component and first
2:42:32
voy a crear un inicio con el nombre de sw4 switcher
I'm going to create a start with the name of sw4 switcher
2:42:35
y luego establecer sw va a ser igual a esto, eh
and then set sw it's going to be equals to this uh
2:42:39
usar inicio una vez más y vamos a proporcionar el valor inicial de archivos hoy, así que lo que voy a hacer es renderizar mi oscuro
use start once again and we're going to be providing the initial value of files today okay so what I'm going to do I'm going to render my dark
2:42:46
en modo claro, así que solo lo pondré allí así que usaré
in light mode so i'll just put it there like so so i'll use
2:42:49
como sw si tenemos allí en esa situación queremos
like sw if we have there in that situation we want
2:42:52
crear una interfaz de usuario, pero si no tienes, quieren proporcionar
to create one ui but if you don't have they want to provide
2:42:55
otra interfaz de usuario, así que solo escribiré como un span y
another ui so i'll just write like a span and
2:42:58
este span dirá oscuro, está bien, pero si eso no es el
this span will say dark okay but if that's not the
2:43:01
caso, queremos proporcionar aún otro con el texto de claro
case we want to provide yet another with the text of light
2:43:05
a ello, está bien, así que ahora déjame guardar allí, así que eso también está hecho, también tenemos que proporcionar un br para un salto y ahora debajo de eso vamos a crear
to it okay so now let me just save there so that's also done we also have to provide a br for a breaking and now underneath that we're going to be creating
2:43:13
un campo de entrada con el tipo de texto y ahora debajo de esta entrada
input field with the type of text and now underneath this input
2:43:16
quieres crear un botón que dirá algo como cambiar
you want to create a button and which will say like switch
2:43:19
swr tch y cuando alguien haga clic en este botón
swr tch and when somebody clicks on this button
2:43:23
queremos cambiar eso, así que usaré como establecer switch
we want to change that so i'll use like set switch
2:43:26
o un set sw para ser precisos, esto es adelante
or a set sw to be precise this is forward
2:43:29
s y no s, ustedes ya saben todo sobre
s and not s you guys already know all of
2:43:32
todas estas cosas así que déjame explicarlo una vez más aquí puedes ver que ahora estamos
this stuff so let me just explain that once again here you can see we are now
2:43:35
renderizando este contenido solo dinámicamente luego tenemos un
rendering this content only dynamically then we have a
2:43:38
br luego también tenemos un campo de entrada y también un botón que
br then we also have an input field and also a button which
2:43:41
nos permite cambiar entre el modo oscuro y el modo claro está bien
allows us to switch between the dark and light mode okay
2:43:44
así que así es como se verá así que si hago clic allí va a hacerlo
so this is how it will look like so if i click on there it's going to make it
2:43:47
oscuro si hago clic allí una vez más así que va a hacerlo claro vamos
dark if i click on there once again so it's going to make it light let's
2:43:51
supongamos que escribo algo dentro de este campo de entrada y
suppose if i type something inside this input field and
2:43:54
si hago clic en este interruptor y aquí puedes ver que la entrada
if i click on this switch and here you can see that input
2:43:57
el campo se mantendrá igual aunque cambiemos eso a oscuro pero este campo de entrada aún tiene este valor así que para hacerlo totalmente único así que para eso podemos proporcionar una clave.
field will stay the same even though we change that to dark but this input field still have this value so to make it totally unique so So for that we can provide a key.
2:44:07
Así que lo que voy a hacer es que aquí voy a pasar una clave. Y esta clave tomará nuestro estado que es un SW.
So what I'm going to do is that here I'm going to pass a key. And this key will take our state which is a SW.
2:44:14
Así que si ese es el caso vamos a proporcionar un oscuro. Pero si ese no es el caso vamos a proporcionar un claro.
So if that is the case we are going to be providing a dark. But if that's not the case we are going to be providing a light.
2:44:18
Ahora estamos proporcionando un valor único a este campo de entrada específico. Así que si tenemos algún tipo de valor.
Now we are providing a unique value to this specific input field. So if we have some sort of a value.
2:44:25
Así que si nuestro campo de entrada está configurado en verdadero va a hacerlo oscuro. Pero si ese no es el caso vamos a obtener un claro.
So if our input field is set to true it's going to make it dark. But if that's not the case we are going to be getting a light.
2:44:32
Esto ahora está configurado en oscuro. Déjame cambiar eso a claro. y si
This is now set to dark. Let me change that to light. and if
2:44:35
escribo algo dentro de este campo de entrada y hago clic en este interruptor
i type something inside this input field and click on this switch
2:44:38
aquí puedes ver que el valor ahora ha desaparecido con éxito nosotros
here you can see that value is now successfully gone we
2:44:41
no los estamos almacenando en algún tipo de almacenamiento local o en algún tipo de un
are not storing them in some sort of a local storage or in some sort of a
2:44:44
base de datos así que por eso la consulta ahora ha desaparecido con éxito
database so that's why query is now successfully gone
2:44:47
está bien así que ahora si escribo algo dentro de este campo de entrada una vez más
okay so now if i type something inside this input field once again
2:44:50
así que va a eliminar todos sus valores de este campo de entrada está bien así que así es como vamos a hacer que nuestro elemento específico o un componente sea totalmente único proporcionando una clave allí.
so it's going to remove all of their value from this input field okay so this is how we are going to be making our specific element or a component totally unique by by providing a key to there.
2:45:01
Si cambio allí a algo más como, no sé, como un marcador de posición o algo así. Déjame escribir un marcador de posición.
If I change there to something else like, I don't know, like placeholder or something like that. Let me just write a placeholder.
2:45:08
Y ahora si guardo mi archivo y aquí puedes ver que ahora está configurado en claro.
And now if I save my file and here you can see it's now set to light.
2:45:11
Si escribo algo dentro de allí y cambio allí, ese valor seguirá estando allí. ¿Por qué?
If I type something inside there and switch there, that value will still be there. Why?
2:45:16
Porque estamos usando un marcador de posición y no una clave. Así que si convierto eso en clave, si escribo algo dentro de este campo de entrada, lo eliminará de aquí porque este campo de entrada ya no es el antiguo.
Because we are using a placeholder and not a key. So if I convert that to key, if I type something inside this input field, so it will remove that from here because this input field is no longer that old one.
2:45:28
Está bien, así que así es como vamos a hacerlo único. Ahora hablemos sobre el hook de efecto de uso.
OK, so this is how we are going to be making it unique. Now let's talk about the use effect hook.
2:45:32
Así que el hook useEffect te permite realizar efectos secundarios en tu componente.
So use effect hook allow you to perform a side effects in your component.
2:45:36
Así que algunos ejemplos de efectos secundarios son como obtener datos, actualizar directamente el DOM y también registrar algo en la consola, también se consideran un efecto secundario dentro de tu componente.
So some example of a side effects are like fetching the data, directly updating the DOM and also logging something to the console are also considered to be a side effect inside your component.
2:45:46
Así que cada vez que quieras hacer algún tipo de efecto secundario dentro de tu componente, como por ejemplo, si quieres ajustar algún tipo de datos dentro de tu componente, en esa situación, vamos a usar el hook useEffect.
So anytime you want to do some sort of a side effect inside your component, like for instance, if you want to fit some sort of data inside your component, so in that situation, we're going to be using the useEffect hook.
2:45:56
¿Cómo se verá la sintaxis? Aquí puedes ver que ahora, primero estamos usando nuestro hook useEffect.
So how the syntax will look like? Here you can see we are now first of all using our useEffect hook.
2:46:01
Y ahora dentro de este hook useEffect, estamos proporcionando nuestra función de callback.
And now inside this useEffect hook, we are now providing our callback function to it.
2:46:05
Y luego dentro de esa función de callback, puedes hacer lo que quieras hacer.
And then inside that callback function, you can do anything you want to do.
2:46:09
Pero hay algunas cosas que quiero que tengas en cuenta al trabajar con useEffect.
But there are a few things that I want you to keep in mind when working with the useEffect.
2:46:13
La primera cosa es que aquí puedes ver que no estamos proporcionando ningún array.
the first thing is here you can see we are not providing any array
2:46:16
Ese array es algo llamado el array de dependencias que voy a explicar en unos segundos, así que cada vez que no especificamos la dependencia.
that array is something called the dependency array which i'm going
2:46:19
En esa situación, esa función de callback se llamará.
to be explaining in a few seconds so anytime we don't specify the dependency
2:46:23
En cada renderizado individual.
array so in that situation that callback function will
2:46:26
llama en cada renderizado
call on every single render i
2:46:29
quiero que tengas eso en mente cada vez que no especifiquemos el arreglo de dependencias, lo que significa que esa función de callback que ahora estamos proporcionando dentro de nuestro use effect se ejecutará en cada renderizado.
want you to keep that in mind whenever we don't specify the dependency array which means like that callback function which we are now providing inside our use effect will be fired on every single render.
2:46:40
A continuación, hablemos sobre el use effect con condicional. No puedes envolver tu hook dentro de la declaración condicional.
Next, let's talk about the use effect with conditional. So, you cannot wrap your hook inside the conditional statement.
2:46:46
Si quieres usar la declaración condicional, tendrás que usarla dentro del hook use effect. Bien, así que también ten eso en mente.
If you want to use the conditional statement, you are going to have to use the inside the use effect hook. Okay, so also keep that in mind.
2:46:53
Ahora, lo último que quiero que tengas en mente es que cada vez que especificamos el arreglo de dependencias vacío
Now, the final thing that I want you to keep in mind is that anytime we specify the empty dependency array
2:46:59
para nuestro use effect, solo se ejecutará esa función que está disponible dentro de nuestro hook use effect en
for our use effect, it will only fire that function which is available inside our use effect hook on
2:47:05
el renderizado inicial, como cuando nuestro componente se renderiza por primera vez
the initial render like when our component first renders it
2:47:08
se llamará a esa función, no cuando nuestro componente cambie, sino
will call that function not when our component changes but
2:47:11
si creamos algún tipo de estado y proporcionamos el valor
if we create some sort of a state and we provided the value
2:47:14
de ese estado, así que cada vez que ese estado cambie, ese
of that state so anytime that state changes that
2:47:18
componente se volverá a renderizar y esa función de callback se
component will re-render and that callback function will
2:47:21
ejecutará, bien, así que sé que eso fue mucha teoría, ahora
fire okay so i know that was a lot of theories now
2:47:24
entremos en la codificación y entonces sabrás de qué estoy hablando ahora
let's get into the coding and then you'll get to know what i'm talking about now
2:47:27
hablemos de otro hook que se llama el hook use effect
let's talk about yet another hook which is called the use effect hook
2:47:31
así que configuramos el hook de efecto para ejecutar algún código cuando
so we set up the use effect hook to run some code when
2:47:34
nuestro componente se renderiza por primera vez y cada vez que
our component render for the first time and whenever it
2:47:37
se vuelve a renderizar y también cuando algún tipo de datos
re-renders and also when some sort of a data
2:47:40
cambia dentro de nuestro componente, así que cómo vamos a
changes inside our component so how are we going to
2:47:43
hacer una configuración para eso, lo primero que tenemos que hacer es que tenemos que agarrar
be making a setup for that the first thing that we have to do is that we have to grab
2:47:46
nuestro use state y también el use effect, está bien
our use stat and also the use effect okay
2:47:49
así que vamos a importar nuestro use effect de React JS y ahora tenemos que usar eso, pero antes de usar eso, voy a
so we are going to be importing our use effect from the react js and now we have to use that but before we use that i'm going to
2:47:56
también hacer una configuración para mi valor, así que solo usaré como valor y
also make a setup for my value so i'll just use like value and
2:47:59
también establecer valor y eso va a ser igual a
also set value and that's going to be equals to the
2:48:02
use state y vamos a proporcionar el valor inicial de cero dentro
use state and we're going to be providing the initial value of zero inside
2:48:05
ahí, ahora voy a usar mi hook de efecto
there now i'm going to be using my use effect hook
2:48:09
y ahora dentro de este hook de efecto toma dos argumentos
and now inside this use effect hook it takes two arguments
2:48:12
el primer argumento que toma es una función de callback y
the first argument it takes is a callback function and
2:48:16
el segundo argumento que toma es un array de dependencias, que es algo que voy a mostrarte en unos segundos, pero ahora hablemos
the second argument it takes is a dependency array which is something i'm going to be showing you in a few seconds but now let's talk
2:48:22
sobre esta función de callback, ahora dentro de esta función de callback
about this callback function now inside this callback function
2:48:25
puedes escribir cualquier tipo de lógica que desees, incluso puedes
you can write any kind of logic that you like you can even
2:48:28
usar tu document.title, puedes registrar algo en la consola
use your document.title you can log something to a console
2:48:31
puedes obtener algún tipo de datos, puedes hacer lo que quieras
you can fetch some sort of a data you can do anything you want
2:48:34
hacer dentro de esta función de callback, está bien, así que lo que voy a
to do inside this callback function okay so what i'm
2:48:37
hacer es que solo voy a usar mi console.log y voy a
going to do is that i'm going to just use my console.log and i'm going
2:48:40
simplemente escribir como llamar al use effect aquí y también voy a usar mi document.title y eso va a ser igual
to just write like call use effect right here and i'm going to also use my document.title and that's going to be equals
2:48:47
a incrementar y solo proporcionaré el valor que ya he configurado dentro de mi estado aquí
to increment and i'll just provide the value which i've already set up inside my strat right here
2:48:55
está bien, así que solo lo llamaré, ahora la siguiente cosa que quiero hacer es que voy a simplemente
okay so i'll just call that now the next thing that i want to do is that i'm going to just
2:48:58
quitar esta f de aquí y ahora dentro de ahí solo voy a
remove this f from here and now inside there i'll just
2:49:01
usar mi h2 y también voy a renderizar mi valor dentro
use my h2 and i'm going to also render my value inside
2:49:04
ahí y también voy a crear un botón para incrementar
there and also i'm going to just create a button to increment
2:49:07
mi contador así que solo usaré como clic en mí y también proporcionaré el controlador de eventos on click
my counter so i'll just use like click me and i'm going to also provide the on click event handler to it and let's just pass
2:49:14
nuestra función de callback dentro de ahí así que solo usaré como establecer valor y
our callback function inside there so i'll just use like set value and
2:49:17
aquí vamos a pasar como valor más uno que es solo
here we are going to be passing like value plus one which is just
2:49:20
incrementando ahí así que aquí puedes ver que quiero que solo te enfoques
incrementing there so here you can see i want you to only focus
2:49:24
en este use effect justo aquí ahora dentro de este use
on this use effect right here now inside this use
2:49:27
effect no estamos proporcionando nuestro array de dependencias, solo
effect we are not providing our dependency array we
2:49:30
estamos creando nuestro use effect o simplemente estamos llamando a nuestro use
are just creating our use effect or we are just calling our use
2:49:33
effect y solo estamos pasando nuestra función de callback ahí, así que ahora si guardo los cambios y si actualizo, aquí puedes ver que ahora estamos obteniendo este resultado que es como llamar a use effect dos veces y ¿por qué lo estamos obteniendo dos veces?
effect and we are just passing our callback function to there okay so now if i save the changes and if i refresh there here you can see we are now getting this result which is like call use effect twice and why are we getting there twice?
2:49:44
Eso es porque aquí puedes ver que estamos usando este modo estricto.
That's because here you can see we are using this strict mode.
2:49:48
Así que si simplemente elimino este modo estricto de aquí, guardo mi archivo y ahora si actualizo, solo estoy recibiendo este mensaje una vez, no dos veces.
So if I just remove this strict mode from here, save my file and now if I refresh there, I'm only getting this message once, not twice.
2:49:56
Así que hay algo más que si quieres tener en cuenta, puedes
So there's also something if you want to keep in mind, you
2:49:59
totalmente tener eso en cuenta, así que sí, aquí puedes
can totally keep that in mind so yeah so here you can
2:50:02
ver que ahora cada vez que cambio algo dentro
see now anytime i change something inside
2:50:05
de mi componente, esa función de callback se
my component that callback function will
2:50:08
ejecutará cada vez, así que aquí puedes ver
fire every single time okay so here you can see
2:50:11
si hago clic en este botón y nos dará ese mensaje una vez
if i click on this button and it's going to give us that message once
2:50:15
de nuevo si hago clic allí una vez más y aquí puedes ver que mi título está cambiando y también estoy obteniendo este resultado justo aquí dentro de mi consola, así que ¿por qué es
again if i click on there once again and here you can see my title is changing and also i am getting this result right here inside my console so why is
2:50:23
eso? porque no estamos proporcionando ningún array de dependencias, ¿verdad?
there that's because we are not providing any dependency array right
2:50:26
aquí, así que cuando no estamos proporcionando ningún array de dependencias a
here so when we are not providing any dependency array to
2:50:29
nuestro use effect, ejecutará este código cada
our use effect it will run this code every
2:50:32
vez que nuestro componente se vuelva a renderizar
single time whenever our component re-renders
2:50:35
así que quiero que tengas eso en cuenta, pero ahora voy a
so i want you to keep that in mind but now i'm going
2:50:38
también proporcionar mi array de dependencias vacío justo aquí, así que si solo
to also provide my empty dependency array right here so if i just
2:50:42
uso como coma y también proporcionaré mi array de dependencias vacío y ahora si guardo mi archivo y ahora déjame actualizar, aquí puedes ver
use like comma and i'm going to also provide my empty dependency array and now if i save my file and now let me just refresh there here you can see
2:50:49
estamos obteniendo nuestra llamada use effect en el primer renderizado
we are getting our call use effect on the first render
2:50:52
pero ahora, si hago clic en este botón, no estamos
but now if i click on this button we are not
2:50:55
obteniendo nuestro resultado justo aquí y aquí puedes ver el título
getting our result right here and here you can see the title it
2:50:59
también no está incrementando y tampoco estamos obteniendo ningún
is also not incrementing and we are also not getting any
2:51:02
más resultados, ¿por qué es eso? Como dije, una vez que especificamos este array de dependencias vacío, no especificamos nada dentro de él, como si este array de dependencias estuviera totalmente vacío
more results why is that as i said that once we specify this empty dependency array we didn't specify nothing inside there like this dependency array is totally empty
2:51:13
así que en esta situación, esta función de callback solo se activará
so in this situation this callback function will only fire
2:51:16
una vez, una vez que nuestro componente renderiza esta callback
once once our component renders this callback
2:51:19
la función se activará, pero no una y otra vez, pero
function will fire but not again and again but
2:51:23
ahora en esta situación, también voy a copiar este valor
now in this situation i'm going to also copy this value
2:51:26
y también lo voy a colocar justo aquí, así que si guardo
and i'm going to also place that right here so if i save
2:51:29
mi archivo y ahora déjame refrescar eso y aquí puedes ver
my file and now let me just refresh that and here you can see
2:51:32
tenemos nuestra función de callback llamada una vez más y ahora, si hago clic en este botón 'clic aquí', estamos llegando allí. Ahora sé que muchas personas me preguntarán, como Huzhan, ¿cuál es el punto de proporcionar este valor?
we have our callback function called once again and now if i click on this click me button we are getting there now i know a lot of people will ask me like huzhan then what's the point of providing this value?
2:51:42
Y también podemos simplemente eliminar los ins. También puede darnos ese mismo resultado justo aquí. Como estamos obteniendo este resultado justo aquí dentro de la consola.
And we can also just remove the ins. It can also give us that same result right here. Like we are getting this result right here inside the console.
2:51:49
Y también nuestro título también está incrementando. Así que si hago clic allí, aquí puedes ver que ambos están funcionando exactamente igual.
And also our title is also incrementing. So like if I click on there, here you can see both of them are working exactly the same thing.
2:51:56
¿No es así? Ahora, si especificamos este valor aquí, y cada vez que nuestro componente cambia debido a este estado, esta función de callback se activará.
Like don't they? Now, if we specify this value right here, and any time our component changes because of this state, this callback function will fire.
2:52:08
Pero si tenemos algún tipo de otro estado, y ese estado también
But if we have some sort of other state, and that state is also
2:52:11
se vuelve a renderizar o componente, este código no
re-rendering or component this code will not
2:52:14
se activará, así que ahora déjame darte el ejemplo de eso, siento que estoy confundiendo
fire so now let me just give the example of that i feel like i'm confusing
2:52:18
así que sabes qué, déjame decir eso una vez más ahora
you so you know what let me just say that once again now
2:52:21
que especificamos el valor de este estado y cada vez
that we specify the value of this state and any time
2:52:24
que ese estado cambia y nuestro componente se vuelve a renderizar
that state changes and our component re-renders
2:52:28
debido a este estado, esta función de callback se
because of this state this callback function will
2:52:31
activará, pero si tenemos algún tipo de otro estado
fire but if we have some sort of other state
2:52:34
y qué componente se renderizó o se volvió a renderizar debido
and what component rendered or re-render because
2:52:37
a ese otro estado, esta función de callback no
of that other state this callback function will not
2:52:41
disparar así que ahora déjame darte un ejemplo de eso, así que solo usaré como const
fire so now let me give you example of that so i'll just use like const
2:52:44
y luego algo y luego establecer algo y
and then something and then set something and
2:52:47
eso va a ser igual a este efecto de uso una vez más y vamos a
that's going to be equals to this use effect one more time and we're going to
2:52:50
proporcionar el valor inicial de cero hoy, así que voy a duplicar
be providing the initial value of zero today so i'm going to duplicate
2:52:53
esta línea de código y también voy a escribir como uh incrementar
this line of code and i'm going to also write like uh increment
2:52:57
por algo está bien y ahora en lugar
by something okay and now instead
2:53:00
de proporcionar el valor establecido, voy a cambiar eso a como establecer algo
of providing the set value i'm going to change that to like set something
2:53:03
y ahora si guardo mi archivo y aquí puedes ver si solo actualizo
and now if i i save my file and here you can see if i just refresh
2:53:06
ahí y quiero que tengas en cuenta aquí puedes ver que
there and i want you to keep in mind here you can see it's
2:53:09
nos va a dar ese valor para la primera renderización y ahora si
going to give us that value for the first render and now if
2:53:12
hago clic en el clic aquí, volverá a renderizar mi
i click on the click me it will re-render my
2:53:15
componente debido a este estado justo aquí, estamos
component because of this state right here we
2:53:19
proporcionando este valor justo aquí, pero ahora si hago clic en esto
are now providing this value right here but now if i click on this
2:53:22
incrementar por algo, nada está sucediendo aquí y ¿por qué es eso? porque aquí puedes ver que solo estamos proporcionando este valor que es un
increment by something nothing is happening right here and why is that because here you can see we are only providing this value which is a
2:53:30
valor de estado y cada vez que el componente cambia debido a
state value and whenever what component changes because of
2:53:33
este valor, entonces esta función de devolución de llamada se
this value so then this callback function will
2:53:36
disparará bien y cada vez que el componente cambie debido a
fire okay and whenever what component changes because
2:53:39
algo más, esta función de devolución de llamada no se disparará, así que
of something else this callback function will not fire so
2:53:43
si también copio allí y si solo escribo una coma aquí y
if i also copy there and if i just write a comma here and
2:53:46
voy a proporcionar también este algo justo aquí, guardar mi archivo y ahora déjame solo actualizar, ahí si hago clic en este botón, se va a disparar, si hago clic en este botón, también se va a disparar
i'm going to also provide this something right here save my file and now let me just refresh there if i click on this button it's going to fire if i click on this button it's going to also fire
2:53:55
así que sí, ten eso en cuenta y ahora la última cosa que quiero
okay so yeah keep that in mind and now the final thing that i want
2:53:58
mostrarte es que la declaración condicional, así que
to show you is that the conditional statement so
2:54:01
voy a simplemente quitar eso de aquí y ahora si solo uso
i'm going to just remove that from here and now if i just use
2:54:04
como um si el valor es mayor que
like um if value is greater than
2:54:08
cero, quiero envolver todo este gancho dentro
zero i want to wrap this entire hook inside
2:54:11
esa declaración condicional, así que si guardo mi archivo y miro
that conditional statement so if i save my file and watch
2:54:14
lo que sucede, así que aquí puedes ver que estamos obteniendo sobre la interfaz de usuario, pero ahora si hago clic en el botón clic aquí, estamos obteniendo un error justo aquí y ese es un gran error, sabes que voy
what happens so here you can see we are getting over ui but now if i click on the click me button we are getting over error right here and that's a huge error you know i'm going
2:54:23
a ir a la parte superior, React ha detectado un cambio en el orden
to go to the top react has detected a change in the order
2:54:26
de la tarjeta de gancho por aplicación, esto llevará a un error y errores
of the hook card by app this will lead to a bug and errors
2:54:30
si no se corrige, para más información ve a este enlace, está bien
if not fixed for more information go to this link okay
2:54:33
así que no se nos permite envolver nuestro gancho
so we are not allowed to wrap our hook
2:54:36
dentro de la renderización condicional si quieres
inside the conditional rendering if you want
2:54:39
usar algún tipo de condición, tenemos que usar eso dentro
to use some sort of a condition we have to use that inside
2:54:42
del efecto de uso, así que si solo pongo eso dentro de este efecto de uso, también lo voy a poner dentro de este efecto de uso y ahora si guardo mi archivo y ahora si solo
the use effect so if i just put that inside this use effect i'm going to also put that inside this use effect and now if i save my file and now if i just
2:54:51
actualizo allí y ahora puedo hacer clic allí y todo
refresh there and now i can click on there and everything will
2:54:54
funcionará exactamente igual, así que sí, eso fue
work totally the same so yeah that was
2:54:57
solo lo básico del efecto de uso, voy a eliminar todas sus cosas y ahora
just the basics of use effect i'm gonna remove all of their stuff and now
2:55:00
déjame mostrarte cómo vamos a obtener nuestros datos mediante
let me show you how we are going to be fetching our data by
2:55:03
el uso de nuestro efecto de uso, así que solo guardaré mi archivo, ahora vamos a
using our use effect so i'll just save my file now let's
2:55:06
entrar en la obtención de datos, así que para obtener nuestros datos, lo primero
get into the data fetching so to fetch our data the first
2:55:09
que tenemos que hacer es que tenemos que crear algún tipo de estado donde
thing that we have to do is that we have to create some sort of a state where
2:55:12
vamos a poner los datos, así que solo usaré como, uh, datos y luego establecer datos y vamos a usar nuestro uso, vamos, usa estado una vez más, en el valor inicial, voy a especificar un arreglo vacío justo aquí.
we're going to be putting over data so i'll just use like uh data and then set data and we're going to be using our use come on use stat once Once again, in the initial value, I'm going to specify empty array right here.
2:55:24
OK, ahora debajo de eso, voy a usar mi efecto de uso una vez más. Y ahora dentro de este efecto de uso, solo voy a pasar mi función de callback.
OK, now underneath that, I'm going to be using my use effect one more time. And now inside this use effect, I'm going to just pass my callback function.
2:55:32
Y ahora aquí, voy a pasar mi arreglo de dependencias vacío justo aquí.
And now here, I'm going to pass my empty dependency array right here.
2:55:35
Este arreglo de dependencias vacío simplemente significa que esta función de callback se ejecutará solo una vez.
This empty dependency array just simply means that this callback function will run only once.
2:55:41
OK, y ahora dentro de eso, vamos a usar nuestra función asíncrona. Así que solo crearé mi función asíncrona.
OK, and now inside there, we are going to be using our asynchronous function. So I'll just create my asynchronous function.
2:55:47
Y le voy a dar el nombre de obtener datos. puedes darle cualquier nombre
And I'm going to give it the name of like get data. you can give any name
2:55:50
que te guste, no voy a proporcionar ningún perímetro para eso y voy a
that you like i'm not going to be providing any perimeter to that and i'll
2:55:53
simplemente usar como una palabra y vamos a obtener nuestros datos de este
just use like a word and we are going to be fetching our data from this
2:55:56
recurso, si voy a este tipo de marcador de posición json, escribo código
resource if i go to this json placeholder type i code
2:55:59
y aquí puedes ver que este es un sitio web de eso que
and here you can see this is a website of that you
2:56:03
puedes aprender más sobre eso si quisieras, pero el que nos interesa
can learn more about that if you wanted to but the one we are interested in
2:56:06
pero es obteniendo estos datos, así que solo lo copiaré allí o
but is by getting this data so i'll just copy there or
2:56:09
sabes qué, voy a entrar en eso para hacerlo, así que solo usaré eso aquí y voy a proporcionar mis tareas y presionar enter y aquí puedes ver que va a
you know what i'm going to just go into that to do so i'll just use that right here and i'm going to provide my to do's and hit enter and here you can see it's going to
2:56:18
darnos muchas tareas aquí, así que tenemos como id
gives us a lot of to do right here so we have like id
2:56:21
sabes, déjame acercar un poco para que tengamos nuestro id, tenemos el título
you know let me just zoom in a bit so we have our id we have the title
2:56:24
y también la bandera de completado para todos estos datos
and also the completed flag for all of these data
2:56:27
y por cierto, esto es un arreglo, así que eso es
and by the way this is array so that's
2:56:30
por qué configuramos lo que se usó como nuestro arreglo aquí, voy a
why we set up what used as our array right here i'm
2:56:33
copiar este enlace y ahora voy a entrar en mi archivo
gonna copy this link and now i'm gonna go into my file
2:56:36
aquí y vamos a colocar eso dentro de nuestra búsqueda, así que lo colocaré aquí y también voy a almacenar alguna variable como const
right here and we're going to be placing that inside our fetch okay so i'll just place it right here and i'm gonna also store then some sort of variable like cons
2:56:45
res o respuesta estaría bien y ahora debajo
res or response would be fine and now underneath
2:56:48
de eso solo lo convertiré a json, así que nos va a dar
that i'll just convert it to the json so it's going to give us
2:56:51
como respuesta, voy a cambiar eso a json y almacenar
like response i'm going to change that to the json and store
2:56:54
eso en la variable de datos, así que ahora puedo registrar el
that in the data variable okay so now i can log the
2:56:57
datos y puedo hacer muchas cosas con esos datos, pero sabes
data and i can do a lot of things with that data but you know
2:57:00
que solo voy a poner una declaración condicional como si tuviéramos los datos y
i'm going to just put a conditional statement like if we have the data and
2:57:04
la longitud de los datos, como si tuvieras algún tipo de datos, así que en esta situación vamos a tomar nuestro estado que es un conjunto
the data dot length like if you have some sort of a data so in this situation we are going to be taking our state which is a set
2:57:10
de datos y vamos a estar usando allí justo aquí y
data and we're going to be using there right here and
2:57:14
ahora déjame ejecutar allí, vamos a tomar esos datos como un
now let me just run there we're going to be taking that data as a
2:57:17
valor de retorno y vamos a ponerlo dentro de nuestro
return value and we are going to be putting the inside our
2:57:20
conjunto de datos, está bien, ahora que hemos creado exitosamente nuestro
set data okay now that we successfully created our
2:57:23
función, pero ahora tenemos que llamarlo aquí dentro, así que
function but now we have to call that right here inside there so
2:57:26
si solo uso como obtener datos y solo voy a ejecutar allí
if i just use like get data and i'm going to just execute there
2:57:29
y así es como vamos a estar obteniendo nuestros datos usando el
and this is how we are going to be fetching our data by using the
2:57:32
la lógica de obtención de datos ahora se ha completado con éxito, así que voy a colapsar aquí ahora que hemos obtenido los datos con éxito, pero lo siguiente que tenemos que hacer es renderizar esos datos en el DOM.
use effect our data fetching logic is now successfully done so i'm going to collapse there right here now that we successfully get the data but the next thing that we have to do is that we have to render that data to the DOM.
2:57:43
Así que voy a usar como UL y dentro de este UL voy a usar mis datos porque este es el estado donde se encuentran todos nuestros datos.
So I'm going to be using like UL and inside this UL I'm going to use my data because this is the state where all of our data is located.
2:57:51
Así que vamos a usar eso y ya sabemos que hay, vamos a entrar en el array de tareas y dentro de este array tenemos muchos objetos aquí.
So we're going to be using that and we already know that there is come on let me just go into the to do that is array and inside this array we have a lot of like objects right here.
2:58:02
Así que vamos a iterar sobre eso y para iterar sobre eso vamos a
So we're going to be iterating over through there and to iterate over through there we are going to be
2:58:06
usar el método map y voy a pegar como item o tarea estaría bien, así que ahora dentro de cada una de estas tareas vamos a usar un li y ahora solo voy a renderizar como, vamos.
using the map method and i'm going to just paste like item or to do would be fine okay so now inside each of these to do we're going to be using what li and now i'll just render like um come on
2:58:19
voy a renderizar como tarea a tarea.
i'll render like to do to do dot
2:58:22
título y supongo que eso estará bien, también puedo poner el
title and i guess that's going to be fine i can also put the
2:58:25
id de math.random o puedo usar como tarea.id que es este id, espero que nos dé. Así que tenemos nuestro ID aquí.
id of like math dot random or i can use like uh to do dot id which is this id hopefully it will give us So we have our ID right here.
2:58:36
Así que también puedes usar eso. Así que si guardo mi archivo y aquí puedes ver que ahora estamos obteniendo todos los ID de las tareas.
So you can also use that. So if I save my file and here you can see we are now getting all of the to do's ID.
2:58:41
Así que ahora déjame refrescar y todo está funcionando como esperamos que funcione.
So now let me just refresh there and everything is working the way we expand to work.
2:58:46
Así que ahora estamos obteniendo el ID, pero también podemos obtener el cuerpo. Bien, no tenemos el cuerpo.
So we are now getting the ID, but we can also get the body. Okay, we don't have the body.
2:58:51
Así que si entro, déjame volver. Sí, voy a ir a la publicación. Ahora dentro de esta publicación, tenemos nuestro cuerpo.
So if I go into, let me just go back. Yeah, I'm going to go to the post. Now inside this post, we have our body.
2:58:58
Así que voy a copiar eso. Voy a entrar y aquí solo cambiaré eso a publicación.
So I'm going to copy there. I'm going to go in there and here I'll just change there to post.
2:59:04
publicaciones o sí, las publicaciones estarían bien, así que si digo
posts or yeah posts would be fine so if i say
2:59:07
allí ahora puedo obtener el cuerpo con éxito como
over there now i can successfully get the body as
2:59:10
bueno, así que si solo duplico eso y cambio eso al cuerpo.
well so if i just duplicate there and change that to the body
2:59:13
y estamos obteniendo un error, así que lo hemos envuelto en
and we are getting an error so we have wrapped in
2:59:17
una especie de sección, voy a cortar eso de aquí y también
some sort of a section i'm gonna cut that from here and also
2:59:20
colocarlo aquí, guardar mi archivo y ahora si voy allí.
place it here save my file and now if i go there
2:59:23
refrescar allí, maldita sea, no estoy obteniendo ningún cuerpo.
refresh there god damn it i'm not getting any body
2:59:26
cada carga debe ser una clave única, maldita sea, corta eso de aquí, ponlo para la sección, no lo necesitas aquí.
each charge should be a unique key god cut that from here put that for the section you don't need that right here
2:59:34
así que solo voy a eliminar el caso de mi archivo y
so i'll just remove the case of my file and
2:59:37
refrescar allí, solo estamos obteniendo el título, pero yo
refresh there we're only getting the title but i
2:59:41
supongo que no estamos obteniendo el cuerpo, así que si solo escribo como cuerpo.
guess we are not getting the body so if i just write like body
2:59:44
y guión guión, sí, estamos obteniendo este cuerpo.
and dash dash yeah we are getting this body
2:59:47
aquí mismo, así que sí, así es como vamos a obtener el título y
right here so yeah this is how we are going to be getting the title and
2:59:50
así es como vamos a obtener el cuerpo, así que así es como vamos a usar el efecto de uso para obtener los datos y también aprendemos mucho sobre el efecto de uso, bienvenidos al efecto de uso
this is how we are going to be getting the body so this is how we are going to be using the use effect to fetch the data and also we learn a lot about the use effect welcome to the use effect just
3:00:00
Y así, en este, quiero que crees el componente de efecto de uso. Luego usa el efecto de uso para registrar un mensaje en la consola cada vez que el componente se monte por primera vez.
And so in this one, I want you to create the use effect component. Then use the use effect to log message to the console whenever the component first mounts.
3:00:07
Por ejemplo, cuando se ejecute por primera vez. Luego, en la segunda parte, vas a usar el efecto de uso una vez más. Crea primero el componente de efecto contador.
For example, when it runs for the first time. Then in the second portion, you're going to be using the use effect one more time. Create first of all the counter effect component.
3:00:15
Luego usa el efecto de uso para actualizar el título del documento. Cada vez que el valor del componente cambie, como primero tienes que inicializar el conteo en cero usando la etiqueta de uso.
Then use the use effect to update the document title. Whenever the component value changes, like first you have to initialize the count to zero value by using the use tag.
3:00:24
Luego renderiza un botón que incremente el conteo y usa el efecto de uso para actualizar el título del documento.
Then render a button that increments the count and use the use effect to update the document title.
3:00:29
título cada vez que el componente cambie y finalmente vas a usar el efecto de uso para
title whenever the component changes and finally you're going to be using the use effect to
3:00:33
obtener los datos, así que primero tienes que crear un componente con el nombre de
fetch the data so first of all you have to create a component with the name of like
3:00:36
efecto de obtención de datos y luego dentro de eso vas a usar
fetch data effect and then inside that you're going to be using
3:00:39
el efecto de uso para obtener tus datos de este punto final, como de este
the use effect to fetch your data from this endpoint like from this
3:00:43
api que es un json placeholder.typeicode.com
api which is a json placeholder.typeicode.com
3:00:46
y para slash post, sí, haz tu mejor esfuerzo, si puedes hacerlo, entonces vuelve y mira la solución y te voy a dar mi
and for slash post yeah give it your best shot if you can do it then come back and watch the solution and i'm going to give you my
3:00:53
solución, así que primero crea un componente con el nombre de efecto básico
solution so first of all create a component with the name of like basic
3:00:56
.jsx, voy a estar usando
effect.jsx i'm going to be using
3:00:59
mi rfc dentro de ahí, simplemente vamos a mi aplicación
my rfc inside there let's just go ahead and go to my app
3:01:02
y registra mi componente aquí mismo, así que
and register my component right in here so
3:01:05
usaré como efecto básico y cerraré ahí, así que si yo
i'll use like basic effect and close there so if i
3:01:08
guardo mi archivo y aquí puedes ver que ahora estamos obteniendo nuestro componente básico
save my file and here you can see we're now getting our basic component
3:01:12
o efecto básico, más bien, ahora lo primero que quiero hacer es que quiero obtener mi efecto de uso de react.js y voy a pasar una función de callback
or basic effect rather now the first thing that i want to do is that i want to grab my use effect from the react.js and i'm going to be passing a callback function
3:01:19
ahí y dentro de ahí, simplemente usemos nuestro console.log que
to there and inside there let's just use our console.log which
3:01:22
dirá como componente básico montado
will say like basic component mounted
3:01:25
aquí vamos a proporcionar también una dependencia vacía
right here we're going to be also providing an empty dependency
3:01:28
y observa lo que sucede cada vez que el componente se renderiza por primera vez
array and watch what happens whenever the component first renders
3:01:31
así que solo escribiré como h1 y revisaré la consola para ver el mensaje, así que vamos a revisar la consola ahora mismo, así que déjame simplemente ir
so i'll just write like h1 and check the console console to see the message so we're going to be checking the console right now so let me just go ahead
3:01:44
y ve a la consola, solo actualicemos allí
and go to the console let's just refresh there
3:01:47
y ahora estamos montando un componente básico por primera vez
and now we are getting a basic component mounted for the first time
3:01:50
y ¿por qué es eso? Eso es por este array de dependencias vacío así que
and why is that that's because of this empty dependency array so
3:01:53
ese fue el desafío número uno y vamos a eliminar eso, voy a crear
that was the challenge number one and let's just remove that i'm going to create
3:01:56
otro componente que será un efecto contador.jsx
another component which will be a counter effect dot jsx
3:02:00
y vamos a usar lo que rafc dentro de ahí y
and let's just use what rafc inside there and
3:02:03
registrar mi componente aquí que dirá efecto contador y voy a colocar allí mismo y dentro de este componente lo primero que quiero hacer es crear mi conteo y también establecer el conteo
register my component right here which will say counter effect and i'm going to place there right here and inside this component the first thing that i want to do is that i want to create my count and also set count
3:02:15
va a ser igual a usar come on use 10
is going to be equal to the use come on use 10
3:02:18
y el valor inicial se establecerá en cero ahora
and the initial value will be set to zero now
3:02:21
voy a usar el efecto una vez más para el lado
i'm going to be using the use effect one more time for the side
3:02:24
efectos así que ahora dentro de entonces también vamos a pasar un conteo
effects so now inside then we're going to be also passing a count
3:02:27
aquí como cada vez que nuestro componente cambia por esto así que observa lo que sucederá, así que solo usaré como document.title y eso va a ser igual a
right here like whenever our component changes because of this so watch what will happen so i'll just use like document.title and that's going to be equals to
3:02:37
este literal de plantilla y vamos a proporcionar nuestro conteo
this template literal and let's just provide our count
3:02:40
y el valor del conteo de nuestro estado así que solo voy a
and the count value from our state so i'll just
3:02:43
usar como signo de dólar y luego y luego este conteo y
use like dollar sign and then and then this count and
3:02:47
ahora para esta interfaz de usuario voy a eliminar eso de aquí y voy a
now for this ui i'm going to remove that from here and i will
3:02:50
simplemente escribir como conteo aquí y renderizar mi
just write like count here and render my
3:02:53
conteo totalmente dinámicamente ahora también vamos a crear un botón
count totally dynamically now we are going to be also creating a button
3:02:56
que dirá como incrementar y aquí cada vez que alguien haga clic en este botón van a activar esta función que será el establecer conteo y aquí tenemos que especificar conteo más uno.
which will say like increment and here whenever somebody clicks on this button they're going to be firing this function which will be the set count and here we have to specify count plus one.
3:03:07
Voy a guardar mi archivo ahora y observa lo que sucede. Así que aquí puedes ver quiero que notes esta área justo aquí, este título.
I'm going to save my file right now and watch what happens. So here you can see I want you to notice this area right here, this title.
3:03:15
Así que cada vez que haga clic en este incrementar, va a cambiar el contador a eso y también va a cambiar este título de conteo justo aquí a eso.
So whenever I click on this increment, it's going to change the counter to it and it's going to also change this count title right here to it.
3:03:22
Así que si solo hago clic en eso y aquí puedes ver que va a incrementar mi contador en uno. Así que ese fue el segundo desafío.
So if I just click on that and here you can see it's going to increment my counter by one. So that was the second challenge.
3:03:28
Ahora para el tercer desafío, tenemos que crear nuestro fetch data
Now for the third challenge, we have to create our fetch data
3:03:31
componente así que usaré como efecto fetch data
component so i'll use like fetch data effect
3:03:34
dot jsx dot jsx y
dot jsx dot jsx and
3:03:37
déjame usar mi rafc dentro de ahí, vamos a crear nuestro
let me just use my rafc inside there let's just create our
3:03:40
estadísticas para que podamos almacenar nuestros datos allí, así que solo usaré como post
stats so that we can store our data inside there so i'll just use like post
3:03:44
entonces establecer post y eso va a ser igual a la uso
then set post and that's going to be equal to the use
3:03:47
estadística y vamos a proporcionar el array de dependencias vacío o no
stat and we're going to be providing the empty dependency array or not
3:03:50
dependencia pero array vacío solo para mantener nuestros
dependency but empty array just for holding our
3:03:53
datos ahora vamos a estar realizando los efectos secundarios, así que para eso tenemos que usar nuestro efecto de uso y aquí estamos
data now we are going to be performing the side effects so for that we have to use our use effect and here we are
3:04:00
vamos a proporcionar nuestro array de dependencias vacío justo aquí
going to be providing our empty dependency array right here
3:04:03
y ahora vamos a definir nuestra función que nos permitirá
and now we are going to be defining our function which will allow us to
3:04:06
obtener nuestros datos, así que, ¿qué estoy haciendo?
fetch our data so what am i even doing
3:04:09
¿qué demonios? solo proporcionemos nuestra función asincrónica y
what the hell let's just provide our asynchronous function and
3:04:12
vamos a proporcionar primero la respuesta y solo usemos
we are going to be providing first of all the response and let's just use
3:04:15
nuestro evento y vamos a estar obteniendo nuestros datos de esta url
our event and we're going to be fetching our data from this url
3:04:18
y también tenemos que convertir nuestros datos o respuesta a json, así que vamos a almacenar eso en los datos y
and also we have to convert our data or response to json so we're going to be storing the in the data and
3:04:25
finalmente tenemos que almacenar eso dentro de nuestras estadísticas, vamos a usar como set
finally we have to store the inside of our stats we are going to be using like set
3:04:29
post y poner nuestros datos allí ahora
post and put our data inside there now
3:04:32
debajo de esta función vamos a estar llamándola este cuchillo i
underneath this function we are going to be calling it this knife i
3:04:35
envía mi archivo y llama a eso y nos va a dar la perfecta
send my file and call that and it's going to give us the perfect
3:04:38
respuesta, así que también tenemos que renderizar sus datos en el dom para
response so we have to also render their data to the dom so
3:04:41
que podamos ver allí, así que no voy a hacer nada loco, así que solo escribiré
that we can see there so i'm not going to do anything crazy so i'll just write
3:04:44
como el título del primer post y aquí debajo
like first post title and here underneath
3:04:48
este h1 vamos a estar iterando sobre todos los posts, así que solo usaré como post . longitud es mayor que cero, así que en esta situación
this h1 we're going to be iterating over through all of the posts so i'll just use like post dot length is greater than zero so in this situation
3:04:55
vamos a estar usando nuestro h2 y solo escribiré como um post y solo queremos obtener el primer post.
we are going to be using our h2 and i'll just write like um post and we just only want to get the first post.
3:05:02
No estamos interesados en todos ellos y solo queremos obtener el título de eso.
We are not interested in all of them and we only want to get the title out of that.
3:05:06
Pero si ese no es el caso, vamos a estar renderizando o bajando punto punto punto. Así que ahora, si guardo mi archivo, primero no tendrás que registrarte.
But if that's not the case we are going to be rendering or lowering dot dot dot. So now if I save my file first of all you won't have to register.
3:05:14
Así que solo iré a mi aplicación y comentaré esta línea y registraré mi componente de efecto de datos de fetch allí.
So I'll just go to my app and comment this line out and register my fetch data effect component there.
3:05:20
Guarda mi archivo. Ahora estamos obteniendo este título y sí, este cuerpo también.
Save my file. Now we are getting this title and yeah this body as well.
3:05:24
Así que ahora, si actualizo allí, nos dará la carga por un breve segundo, como pueden ver. Y luego nos dará los datos.
So now if I refresh there, it's going to give us the loading for a brief second, as you can see. And then it's going to give us the data.
3:05:31
Así es como vamos a obtener nuestros datos utilizando el efecto de uso. Y así es como vamos a realizar más efectos secundarios utilizando el efecto de uso.
This is how we are going to be fetching our data by using the use effect. And this is how we are going to be performing more side effect by using the use effect.
3:05:38
Así que ahora, déjame descomentar todo eso. Y ahora podemos incrementar algo y también podemos revisar los registros y cosas así.
So now let me just uncomment all of that. And now we can increment something and we can also check out the logs and stuff like that.
3:05:44
Así que ahora hablemos del famoso problema con ReactJS, que se llama el prop drilling. ¿Qué es el prop drilling y por qué debería importarle a alguien?
So now let's talk about the famous problem with ReactJS, which is called the prop drilling. So what is a prop drilling and why should anyone care about that?
3:05:52
Así que aquí pueden ver que tengo una jerarquía de componentes aquí.
so here you can see i have a component hierarchy right here so
3:05:55
Tengo un componente diferente como app card header navigation user.
i have a different component like app card header navigation user
3:05:58
fecha hora y así sucesivamente y aquí dentro.
date time and so on and so forth and here inside
3:06:01
en el componente de la aplicación tengo un dato, supongamos que quiero.
the app component i have a data suppose if i want to
3:06:05
pegar esos datos del componente de la aplicación al componente de fecha.
paste that data from the app component to the date component
3:06:08
¿Cómo puedo hacer eso? Para hacer eso hay.
so how can i go about doing that so to do that there
3:06:11
muchas maneras de hacer el nreact.js que vamos a aprender a lo largo del curso, como usando zoos 10 y también usando el contexto.
are a lot of ways to do the nreact.js which we are going to be learning throughout the course like by using zoos 10 and also using the context
3:06:17
API y también Redux Toolkit y hay muchas maneras, pero ahora hablemos del prop drilling.
API and also Redux Toolkit and there are a lot of ways but now let's talk about the prop drilling.
3:06:23
Vamos a perforar estos datos en múltiples componentes. Así que vamos a tomar esos datos y los vamos a pasar a todos estos componentes usando las props.
We are going to be drilling this data into multiple components. So we are going to be taking that data and we are going to be passing that data into all of these components by using the props.
3:06:33
¿Cómo vamos a hacer eso? Así que voy a pasar mis datos del componente de la aplicación al componente del carrito usando la prop.
So how are we going to be doing them? So I'm going to pass my data from the app component to the cart component by using the prop.
3:06:39
Luego voy a pasar eso al componente de usuarios y ahora, finalmente, voy a pasar eso al componente de fecha y luego allí podemos usar eso.
Then I'm going to pass that to the users component and now finally I'm going to pass that to the date component and then there we can use that.
3:06:46
Pero imagina si estás trabajando con Google o tal vez Facebook o algunas grandes empresas, tendrían como muchos componentes.
But imagine if you are working with like Google or maybe Facebook or some big companies, they would have like a lot of components.
3:06:53
Y quiero decir, como muchos, tendrían como mil componentes, si no millones de componentes.
And I mean like a lot, they would have like a thousand components, if not million components.
3:06:58
Así que lo que harás es que solo espaciarás tus datos usando las props y simplemente perforarás tus datos.
So what you will do is that you will just space your data by using the props and you will just drill your data.
3:07:04
Ahora hay una solución para eso. Te mostraré la solución en unos segundos, pero primero quiero mostrarte el prop drilling en acción.
Now there is a solution for that. I'm going to show you the solution in a few seconds, but first of all, I want to show you the prop drilling in action.
3:07:11
Luego saltaremos a la solución. Así que ahora hablemos del prop drilling en acción.
Then we will jump into the solution. So now let's talk about the prop drilling in action.
3:07:15
Así que lo que voy a hacer es que voy a crear mis componentes.
So what I'm going to do is that i'm going to just create my components
3:07:18
carpeta y dentro de esta carpeta voy a crear mi componente.
folder and inside this folder i'm going to create my component
3:07:21
a.jsx y también componente.
a.jsx and also component
3:07:24
b.jsx y finalmente componente c.jsx.
b.jsx and finally component c.jsx
3:07:29
y ahora solo entraré en mi componente a y.
and now i'll just go into my component a and
3:07:32
voy a usar mi rafce y voy a ir al componente b, solo usemos lo que rafce y también al componente c, así que ahora dentro de mi componente de aplicación
i'm going to use my rafce and i'm going to go to the component b let's just use what rafce and also to the component c so now inside my app component
3:07:43
voy a crear algún tipo de variable con el nombre de como nombre y
i'm going to just create some sort of a variable with the name of like name and
3:07:46
voy a dar mi nombre dentro de ahí, así que voy a guardar esto
i'm going to give my name inside there so i'm going to save this
3:07:49
archivo, ahora tenemos que pasar estos datos de nombre a
file now we have to pass this name data into
3:07:52
este componente c, así que ¿cómo puedes hacerlo?
this component c so how can you go about doing
3:07:55
eso, así que para hacer eso, lo primero que tenemos que hacer es que tenemos
that so to do that the first thing that we have to do is that we have
3:07:58
que llamar a nuestro componente a y ahora vamos a
to call our component a and now let's
3:08:02
simplemente renderizarlos, tenemos que pasar ese nombre como la prop de nuestro componente a, así que solo proporcionaré mi nombre aquí, voy a guardar allí, ahora dentro
just render them we have to pass that name as the prop or our component a so i'll just provide my name right here i'm going to save there now inside
3:08:09
de mi componente a, voy a desestructurar allí mismo y también vamos a estar simplemente
my component a i'm going to destructure there right here and also we are going to be just
3:08:15
pasando eso al componente b, así que solo usaré
passing there into the component b so i'll just use
3:08:18
como componente b y voy a presionar enter, así que se va a importar automáticamente
like component b and i'm going to hit enter so it's going to auto import
3:08:21
ahí y vamos a estar tomando esa prop de nombre y
there and we're going to be taking that prop of name and
3:08:24
vamos a estar pasándola a nuestro componente b, así que solo escribiré como nombre aquí, así que voy a guardar allí, ahora voy a ir al componente b, también voy a desestructurar allí mismo
we're going to be passing there to or component b so i'll just write like name right here so i'm going to save there now i'm going to go into the component b i'm going to also destructure there right here
3:08:34
solo usaré mi nombre y finalmente tenemos que usar eso
i'll just use my name and finally we have to use that
3:08:37
dentro del componente c, así que solo cerraré allí
inside the component c okay so i'll just close there
3:08:40
aquí y también voy a pasar eso como una prop para
right here and i'm going to also pass that as a prop so
3:08:43
que pueda usar eso dentro de mi componente c, así que solo voy a
that i can use that inside my component c so i'll just
3:08:46
ir a mi componente c y solo voy a desestructurar allí bien
go to my component c and i'm going to just destructure there right
3:08:49
aquí, solo voy a desestructurar mi nombre y ahora simplemente
here i'll just destructure my name and now let's just
3:08:52
usaré eso aquí, así que solo usaré mi h1 y ahora voy a
use there right here so i'll just use my h1 and now i'm going to
3:08:55
simplemente renderizar el nombre aquí, así que si guardo mi archivo ahora, así que ahora estamos pasando este nombre como una prop a todos estos componentes, como primero estamos pasando
just render the name right here so if i save my file now so now we are drilling this name as a prop to all of these components like first of all we are passing
3:09:03
eso al componente A, luego al componente B, luego al componente C, y finalmente ahora estamos renderizando eso dentro del componente C.
that to component A, then to the component B, then to the component C, and finally we are now rendering that inside the component C.
3:09:11
Así que eso va a ser un gran proceso. Y supongamos que estás trabajando con algún tipo de una empresa más grande y vas a tener que pasar tus datos como una prop a todos estos componentes, y eso va a ser una pesadilla.
So that's going to be a lot of process. And let's suppose if you are working with some sort of a bigger company and you're going to have to pass your data as a prop to all of these components, and that's going to be a nightmare.
3:09:21
Así que para resolver este problema, vamos a aprender sobre la API de Contexto. Así que ahora hablemos sobre la API de Contexto.
So to solve this problem, we are going to be learning about the Context API. So now let's talk about the Context API.
3:09:27
La API de Contexto es una característica que te permite gestionar y compartir el estado a través de tu árbol de componentes
Context API is a feature that allows you to manage and share state across your component tree
3:09:33
sin tener que pasar props manualmente en cada nivel de tu árbol de componentes.
without having to pass prop down manually at every level of your component tree.
3:09:37
Es útil para escenarios donde necesitas compartir datos o funciones entre muchos componentes, especialmente cuando estos componentes están profundamente anidados, algo que acabamos de ver hace unos segundos.
It is useful for scenarios where you need to share data or function across many components, especially when these components are deeply nested, something which we just saw a few seconds ago.
3:09:48
Así que para eso usamos las props, pero en esta situación no vamos a usar ninguna prop.
So for that we use the props, but in this situation we are not going to be using any props.
3:09:51
Vamos a usar algo llamado la API de Contexto y ahora vamos a entrar en ello.
We are going to be using something called the Context API and now let's get into it.
3:09:56
Así que esa fue la teoría básica sobre la API de Contexto y ahora
So that was the basic theory about the Context API and now
3:09:59
vamos a refactorizar o hacer prop drilling para usar la
let's refactor or prop drilling to use the
3:10:02
API de contexto, así que lo que voy a hacer es que primero
context api so what i'm going to do is that first of
3:10:05
tendré que importar mi contexto, así que solo usaré como crear
all i'm going to have to import my context so i'll just use like create
3:10:09
contexto y vamos a importar eso desde React JS, así que
context and we're going to be importing there from the react js so
3:10:12
ahora que lo importamos con éxito, lo siguiente que tenemos que hacer es crear la instancia de allí, así que solo usaré como crear contexto y ahora vamos a tener que almacenar algún tipo de variable. Así que solo le daré el nombre de datos.
now that we successfully import that so the next thing that we have to do is that we have to create the instance of there so i'll just use like create context and now we're going to have to store then some sort of a variable So I'll just give it the name of data.
3:10:23
Básicamente, puedes darle cualquier nombre que desees. Y también lo voy a exportar para poder usar este contexto en cualquier lugar dentro de mi proyecto.
You can basically give it any name that you like. And I'm going to also export that so that I can use this context anywhere inside my project.
3:10:30
Así que eso está bien. Ahora, lo siguiente que quiero hacer es envolver toda mi aplicación para usar este contexto.
So that's good. Now the next thing that I want to do is that I want to wrap my entire application to use this context.
3:10:36
¿Cómo puedo hacer eso? Solo lo envolveré usando mis datos, que ahora están sosteniendo el valor de mi contexto.
So how can I go about doing that? I'll just wrap that by using my data, which is now holding the value of my context.
3:10:44
Así que ahora estoy llamando a estos datos aquí. Y solo voy a cerrar eso.
So I'm now calling this data right here. And I'm going to just close that.
3:10:48
y una vez que cierre eso, también voy a envolver mi componente A dentro
and once i close there and i'm going to also wrap my component a inside
3:10:51
de allí, entonces tenemos dos propiedades, así que si solo escribo como
there then we have two properties so if i just write like
3:10:54
punto, nos va a dar consumidor y también nos va a dar
dot it's going to give us consumer and it's going to also gives us
3:10:58
el proveedor, así que proveedor simplemente significa que
the provider so provider just simply means it's
3:11:01
nos permitirá proporcionar nuestro valor o nuestros datos a
going to allows us to provide our value or our data into
3:11:04
múltiples componentes, así que voy a elegir este proveedor y aquí solo tenemos que usar nuestro valor y dentro de este valor tenemos que pasar esos datos que queremos pasar dentro de nuestro componente.
multiple components so i'm going to just choose this provider and here we just have to use our value and inside this value we have to pass that data which we want to pass inside our component
3:11:15
así que ya no tenemos que usar todas estas props, así que solo voy a eliminar eso
so we no longer have to use all of these props so i'm going to just remove that
3:11:18
de aquí voy a copiar mi nombre de allí y solo voy a
from here i'm going to copy my name from there and i'm going to just
3:11:21
poner eso aquí, así que si guardo mi archivo y también tenemos
put that right here so if i sell my file and we also have
3:11:24
que solo copiar este y tenemos que
to just uh copy this one and we have to
3:11:27
colocarlo aquí, así que así es como vamos a usar
place it right here so this is how we are going to be using
3:11:30
nuestro prop primero que nada tenemos que importar eso luego tenemos que crear una instancia de
our prop first of all we have to import that then we have to create an instance of
3:11:34
eso luego tenemos que usar la propiedad del proveedor allí y esta propiedad del proveedor nos permite proporcionar nuestros datos en múltiples componentes así que ya no tenemos que
that then we have to use the provider property on there and this provider property allows us to provide our data into multiple components so we no longer have to
3:11:43
datos del mundo real en múltiples componentes usando las props
real world data into multiple components by using the props
3:11:46
así que voy a entrar en mi componente a y
so i'm going to go into my component a and
3:11:49
ya no necesitamos este nombre aquí así que voy a simplemente eliminarlo vamos a
we no longer need this name right here so i'm going to just remove there let's
3:11:52
simplemente eliminarlo voy a entrar en el componente b también
just remove there i'm going to go into the component b i'm going to also
3:11:55
eliminarlo de aquí vamos a simplemente eliminarlo de aquí y
remove there from here let's just remove there from here and
3:11:59
ahora dentro del componente c también voy a eliminar
now inside the component c i'm going to also remove
3:12:02
eso de aquí pero ahora la pregunta es cómo vamos a recibir esos datos ahora que pasamos esos datos aquí
there from here but now the question is how are we going to be receiving that data now that we pass that data right here
3:12:09
en este componente pero cómo en el mundo vamos a recibir
into this component but how in the world we are going to be receiving
3:12:12
eso o consumirlo para recibir entonces lo primero
there or consuming there to receive then the first
3:12:15
que tenemos que hacer es que tenemos que importar nuestro contexto como
thing that we have to do is that we have to import our context as
3:12:18
dije que vamos a usar esta exportación para que podamos
i said like we are going to be using this export so that we can
3:12:21
usar este contexto dentro de múltiples componentes así que ahora vamos a
use this context inside multiple components so now we are going to
3:12:24
estar importando allí así que solo usaré como importar mis datos
be importing there so i'll just use like import my data
3:12:27
y si solo presiono enter aquí así que va a importar desde mi componente de app y ahora tenemos que usarlo dentro de nuestro componente así que lo que voy a hacer es que voy a simplemente
and if i just hit enter right here so it's going to import there from my app component and now we have to use the inside our component so what i'm going to do is that i'm going to just
3:12:36
eliminar eso de aquí y también voy a eliminar estos divs de
remove that from here and i'm going to also remove these divs from
3:12:39
aquí y en su lugar voy a reemplazar eso con estos datos y
here and instead i'm going to replace that with this data and
3:12:42
si solo escribo el punto así que qué estamos obteniendo ahora estamos obteniendo el proveedor
if i just write the dot so what are we getting we are now getting the provider
3:12:45
y también estamos obteniendo el consumidor así que este consumidor
and we are also getting the consumer so this consumer
3:12:49
nos permitirá consumir sus datos o recibir
will allows us to consume their data or receive
3:12:52
sus datos así es como estamos pasando los datos y
their data this is how we are passing the data and
3:12:56
así es como vamos a recibir sus datos ahora este consumidor toma una función de callback así que vamos a pasar
this is how we are going to be receiving their data now this consumer take a callback function so we are going to be passing
3:13:02
nuestra función dentro de allí para obtener nuestros datos así que voy a simplemente
our function inside there to get our data so i'm going to just
3:13:05
escribir estas llaves aquí y voy a simplemente proporcionar mi función
write these curly braces right here and i'm going to just provide my function
3:13:09
va a tomar el perímetro así que solo voy a especificar el perímetro
it's going to take the perimeter so i'm going to just specify the perimeter
3:13:12
de nombre y ahora vamos a crear nuestra función de callback
of name and now let's just create our callback function now
3:13:15
dentro de ahí puedo devolver como h1 y ahora dentro
inside there i can just return like h1 and now inside
3:13:18
este h1 puedo usar mi nombre aquí así que si solo escribo un nombre
this h1 i can use my name right here so if i just write a name
3:13:21
guarda mi archivo y si solo actualizo ahí y aquí puedes ver que ahora estoy obteniendo mi nombre así que si voy y cambio eso a como no sé john o algo así, aquí puedes ver que ahora estamos obteniendo
save my file and if i just refresh there and here you can see i'm now getting my name so if i go ahead and change that to like i don't know john or something so here you can see we're now getting
3:13:31
la palabra john así que se ve genial como si realmente estuviéramos recibiendo
word john so that's looking cool like we are totally receiving
3:13:34
estos datos pero ahora la pregunta es vamos
this data but now the question is let's
3:13:37
supongamos que quiero proporcionar como múltiples datos, así que ¿cómo puedo hacerlo?
suppose if i want to provide like multiple data so how can i go about
3:13:40
haciendo eso voy a entrar en mi contexto una vez más y
doing that i'm gonna go into my context once again and
3:13:43
voy a duplicar ahí como si estuviéramos creando una instancia más
i'm gonna just duplicate there like we are creating one more instance
3:13:46
de nuestro contexto y voy a renombrar eso a nuestros datos uno
of our context and i'm gonna just rename that to our data one
3:13:49
puedes darle básicamente cualquier nombre que prefieras pero en mi caso voy a renombrar eso a datos uno, voy a guardar este archivo y ahora lo siguiente que tenemos que hacer es crear algún tipo de otros datos para que podamos pasar esos datos a nuestro componente.
you can like basically give it any name that you prefer but in my case i'm gonna just rename that to data one i'm gonna save this file and now the next thing that we have to do is that we have to just create some sort of other data so that we can pass that data into our component.
3:14:02
Así que solo usaré como edge en este caso y tengo 22 así que solo pondré mi 22 edge aquí.
So I'll just use like edge in this case and I am 22 so I'll just put my 22 edge right here.
3:14:08
Está bien y ahora si quieres pasar eso a nuestro componente, en esa situación vamos a usar nuestros datos uno y luego punto y tenemos nuestro proveedor y este proveedor nos permitirá pasar nuestros datos.
Okay and now if you want to pass that into our component so in that situation we're going to be using our data one and then dot and we have our provider and this provider will allow us to pass our data.
3:14:19
Así que voy a envolver eso aquí y una vez más vamos a usar nuestro valor y en este caso vamos a pasar el edge como un valor aquí.
So I'm going to just wrap that right here and once again we're going to be using our value and in this case we're going to be passing the edge as a value right here.
3:14:26
Ya proporcionamos el nombre pero ahora en este caso vamos a pasar el valor así que ahora que hemos pinchado estos datos tenemos que entrar en nuestro componente c y
We already provided the name but now in this case we are going to be passing the value so now that we successfully
3:14:32
tenemos que consumir esos datos o agarrar esos datos así que
pinched this data we have to go into our component c and
3:14:35
voy a comentar esta línea y ahora si quieres consumir
we have to consume that data or grab that data so
3:14:38
esos datos o recibir esos datos así que ahora dentro
i'm going to just comment this line out and now if you want to consume
3:14:42
esos datos o recibir esos datos así que ahora dentro
that data or receive that data so now inside
3:14:45
estos datos uno qué tenemos que hacer tenemos que simplemente usar nuestra declaración de retorno y ahora dentro de esta declaración de retorno una vez más vamos a estar usando nuestros datos uno dentro de esto
this data one what do we have to do we have to just use our return statement and now inside this return statement once again we are going to be using our data one inside this
3:14:54
si simplemente presiono enter así que se va a importar automáticamente eso justo aquí está bien
if i just hit enter so it's going to auto import that right here okay
3:14:57
así que ahora tenemos que usar eso y una vez más vamos a estar usando nuestra propiedad de consumidor
so now we have to use that and once again we are going to be using our consumer property
3:15:01
dentro de ahí y ahora dentro de este consumidor de datos uno nosotros
inside there and now inside this data one consumer we
3:15:04
vamos a estar una vez más usando una función de callback así que solo
are going to be once again using a callback function so i'll just
3:15:07
usar como borde y ahora dentro de ahí voy a usar
use like edge and now inside there i'm going to just use
3:15:10
mi h1 aquí primero tenemos que regresar porque estamos usando llaves y voy a escribir como mi nombre es y luego solo pondré
my h1 right here first of all we have to return there because we are using curly braces and i'm going to write like my name is and then i'll just put
3:15:18
mi nombre dentro de ahí como nombre y también voy a usar
my name inside there like name and i'm going to also use
3:15:21
como y tengo uh años
like and i am uh age years
3:15:25
o ahí vamos, así que si guardo mi archivo y aquí puedes
or there we go so if i save my file and here you can
3:15:28
ver que ahora estoy obteniendo como mi nombre es john y tengo 22 años o
see i'm now getting like my name is john and i'm 22 years or
3:15:31
así que esta es una vez más no una buena manera de pasar
so this is once again not a good way to pass
3:15:34
nuestros datos, pero al menos es mejor que el prop drilling, está bien
our data but at least it is better than the prop drilling okay
3:15:38
así que estamos pasando nuestros datos, estamos recibiendo
so we are passing our data we are receiving
3:15:41
nuestros datos, pero ahora si quieres recibir esos datos, vamos a tener que usar esta función de callback y todo para resolver el problema, así que
our data but now if you want to receive that data we're going to have to use this callback function and all so to solve the problem so to
3:15:48
resolver incluso este problema, vamos a estar usando el use context
solve even this problem we are going to be using the use context
3:15:51
hook, así que ahora hablemos sobre el hook use context, ahora vamos a
hook so now let's discuss about use context hook now let's
3:15:54
hablar sobre el hook use context en react.js, así que use
talk about the use context hook in react.js so use
3:15:57
el hook context nos permite acceder al valor del contexto proporcionado
context hook allows us to access the context value provided
3:16:00
por el objeto de contexto directamente dentro del componente funcional
by the context object directly within the functional component
3:16:04
así que el contexto proporciona una manera de pasar los datos a través del componente
so context provides a way to pass the data through the component
3:16:07
árbol sin tener que pasar props manualmente en cada nivel, algo que acabamos de ver hace unos segundos, así que ahora solo
tree without having to pass prop down manually at every level something which we just saw a few seconds ago so now we only
3:16:14
nos importa el hook use context y ahora vamos a profundizar en ello, así que
care about the use context hook and now let's get into it so
3:16:17
ahora vamos a refactorizar este código para usar nuestro hook de contexto, así que lo que voy a
now let's refactor this code to use our context hook so what i'm
3:16:20
hacer es que primero tenemos que importar
going to do is that first of all we have to import
3:16:23
o usar el hook de contexto aquí, así que una vez
or use context hook right here so once
3:16:26
que importemos con éxito eso, la siguiente cosa que tenemos que hacer es que tenemos que llamar a eso
we successfully import that the next thing that we have to do is that we have to call that
3:16:29
aquí, así que voy a usar como use context y ahora dentro
right here so i'm going to use like use context and now inside
3:16:33
de este contexto, tienes que tener en cuenta de dónde provienen tus datos, si provienen de los datos o de los datos uno que
this context you have to keep in mind from where your data is coming from is that coming from the data or the data one which
3:16:41
ya estamos creando aquí, como estamos creando nuestro create context
we are already creating right here like we're creating our create context
3:16:45
instancia y ahora estamos pasando nuestros datos usando
instance and now we are passing our data by using
3:16:48
ya sea los datos o los datos uno, así que ahora en esta
either the data or the data one so now in this
3:16:51
situación tenemos que decirle a nuestro hook de qué contexto
situation we have to tell our hook like from which context
3:16:54
provienen los datos, así que en esta situación voy a copiar estos datos
where data is coming from so in this situation i'm going to copy this data
3:16:57
y los voy a poner aquí y los voy a almacenar en una especie de
and i'm going to just put that right here and i'm going to store in some sort of a
3:17:00
variable como nombre de usuario o algo así, así que así es como vamos
variable like username or something like that so this is how we are going
3:17:04
a obtener nuestros datos usando este use context, ya no tenemos que proporcionar todas estas funciones de callback
to be getting our data by using this use context we no longer have to provide all of these callback function
3:17:10
de retorno y todo eso, así que también puedo usar allí
return statement and all of that so i can also use there
3:17:13
para los datos uno, así que solo usaré como edad y voy a usar mi use
for the data one so i'll just use like age and i'm going to use my use
3:17:16
no estado, sino use context una vez más y voy a
not state but use context once again and i'm going
3:17:19
simplemente pasar mis datos uno dentro de allí, así que ahora yo
to just pass my data one inside there so now i
3:17:22
puedo eliminar totalmente todos estos códigos, así que solo los eliminaré allí
can totally remove all of these codes so i'll just remove there
3:17:25
y aquí puedes ver que podemos usar como nuestro h1 y
and here you can see we can just use like our h1 and
3:17:29
ahora dentro de este h1 puedo usar como mi nombre es
now inside this h1 i can use like my name is
3:17:32
y luego voy a pasar mi nombre de usuario aquí y tengo años y
and then i'm going to just pass my username right here and i am age years old and
3:17:38
voy a guardar mi archivo, tenemos que escribir una mayúscula A y
i'm going to save my file we have to write uppercase a and
3:17:42
guardar mi archivo y aquí puedes ver que ahora estoy obteniendo como mi nombre es
save my file and here you can see i'm now getting like my name is
3:17:45
Juan y tengo 22 años, así que este use context es
john and i'm 22 years old so this use context is
3:17:49
muy útil, así que así es como vamos a pasar nuestros datos
very helpful so this is how we are going to be passing our data
3:17:52
y así es como vamos a recibir
and this is how we are going to be receiving
3:17:55
nuestros datos usando el use context, así que sí, eso
our data by using the use context so yeah that
3:17:58
fue sobre el hook de use context, es hora del desafío de contexto, así que lo primero que quiero que hagas es crear el archivo user context.jsx y dentro
was it about the use context hook time for the context challenge so the first thing that i want you to do is that i want you to create the user context.jsx file and inside
3:18:06
de ese archivo crea un contexto de usuario y también el proveedor de usuario que te permitirá mantener los datos compartidos.
that file create a user context and also the user provider which will allow you to hold the shared data.
3:18:12
A continuación, tienes que usar el use context para acceder a esos datos.
Next you have to use the use context to access that data.
3:18:15
Así que una vez más, tendrás que crear el componente user profile.jsx y dentro de ese componente tendrás que usar el use context para acceder a esos datos.
So once again you're going to have to create the user profile.jsx component and inside that component you're going to have to use the use context to access that data.
3:18:24
Está bien, y finalmente vas a estar actualizando esos datos. Así que una vez más, tendrás que crear el archivo update user.jsx y dentro de ese archivo tienes
Okay and then finally you're going to be updating that data. So once again you're going to have to create the update user.jsx file and inside that file you have
3:18:32
que definir el componente y luego usar el contexto que
to define the component then use the use context which
3:18:35
te permitirá acceder a sus datos y de alguna manera actualizar
will allow you to access their data and somehow update
3:18:38
sus datos, así que dale lo mejor de ti si puedes
their data so give it your best shot if you can
3:18:41
hazlo, está completamente bien, luego vuelve y mira la solución y
do it that's completely okay then come back and watch the solution and
3:18:44
ahora te voy a dar mi solución, así que dentro de este src voy a
now i'm going to give you my solution so inside this src i'm going
3:18:48
crear un archivo con el nombre de user context.jsx
to create a file with the name of user context.jsx
3:18:52
y dentro de ahí, lo primero que quiero hacer es importar mi create context y también el use state, luego tenemos
and inside there the first thing that i want to do is that i want to import my create context and also the use state as well next we
3:19:00
que definir nuestro contexto, voy a usar create context y
have to define our context i'm going to be using create context and
3:19:04
ejecutar ahí y también voy a almacenar en algún tipo de variable
execute there and i'm going to also store in some sort of a variable
3:19:07
así que simplemente le daré el nombre de user context y
so i'll just give it the name of like user context and
3:19:10
ahora debajo de eso tenemos que crear nuestro proveedor, así que simplemente usaré
now underneath that we have to create our provider so i'll just use
3:19:13
como cons user provider y eso va a ser igual a
like cons user provider and that's going to be equals
3:19:16
estos hijos y va a tomar los hijos y
to this children and it's going to take the children and
3:19:20
también dentro de este componente vamos a definir qué se usó allí y el valor inicial será el nombre, así que simplemente escribiré
also inside this component we are going to be defining what used there and the initial value will be name so i'll just write
3:19:26
como john doe y vamos a estar desestructurando
like john doe and we're going to be destructuring
3:19:29
el usuario y también el set user de esto
the user and also the set user out of this
3:19:32
use date, está bien, así que ahora debajo de eso vamos a estar retornando
use date okay so now underneath that we're going to be returning
3:19:35
nuestro contexto de usuario que ya hemos creado
our user context which we've already created
3:19:39
justo aquí vamos a estar llamando allí y ahora dentro
right here we are going to be calling there and now inside
3:19:42
de este contexto ya sabemos que tenemos una propiedad llamada
this context we already know that we have a property called
3:19:45
dot provider, así que simplemente voy a escribir provider, copiar allí y también colocar allí justo aquí y ahora dentro de ahí vamos a tener que colocar algún tipo de datos, así que
dot provider so i'm going to just write provider copy there and also place there right here and now inside there we're going to have to place some sort of data so
3:19:54
Ahora en esta situación, vamos a estar pasando el usuario y también pasaremos la función que nos permite
Now in this situation, we're going to be passing over the user and we will also pass the function which allows us
3:20:00
cambiar ese usuario, así que simplemente escribiré como user, vamos
change that user so i'll just write like user come on
3:20:03
valor, primero que todo, y aquí tenemos que definir nuestro usuario y
value first of all and here we have to define our user and
3:20:06
ahora voy a crear una función que nos permitirá cambiar ese estado
now i'm going to be creating a function which will allows us to change that state
3:20:10
así que solo usaré ese concepto de actualizar usuario, va a ser una función
so i'll just use that concept update user it's going to be a function
3:20:13
que tomará un nuevo, eh sí, nuevo nombre
which will take like a new uh yeah new name
3:20:16
estaría bien, ahora solo escribiré como establecer usuario y aquí
would be fine now i'll just write like set user and here
3:20:19
voy a poner el nombre, luego solo pondremos el actualizado
i'm going to put the name then we will just put the updated
3:20:22
nombre, así que ahora hemos creado con éxito esta función, así que estoy
name okay so now we successfully created this function so i'm
3:20:25
a punto de copiar el nombre de allí y colocarlo justo aquí y aquí
going to copy the name of there and place it right here and here
3:20:28
también tenemos que proporcionar sus hijos que ahora estamos tomando
we also have to provide their children which we are now taking
3:20:31
como una propiedad, así que solo escribiré sus hijos y eso es todo
as a prop so i'll just write their children and that's everything
3:20:35
que tenemos que hacer y finalmente también tenemos que exportar esto
that we have to do and finally we also have to export this
3:20:38
para que podamos usarlo en otro archivo, así que usaré como exportar
so that we can use the in other file so i'll use like export
3:20:41
exportar el contexto de usuario y también el
export the user context and also the
3:20:44
proveedor de usuario para que pueda usarlo en otro componente
user provider so that i can use the in other component
3:20:47
así que ahora eso está hecho, a continuación tenemos que crear nuestro componente
so now that's done next we have to create our component
3:20:51
así que voy a entrar en mi carpeta de componentes y voy a crear mi usuario
so i'm going to go into my component folder and i'm going to create my user
3:20:54
perfil.jsx, así que dentro de allí
profile.jsx okay so inside there
3:20:57
vamos a usar el contexto para acceder
we are going to be using the use context to access
3:21:00
a los datos de nuestro contexto y también vamos a importar
the data from our context and we are going to be also importing
3:21:03
el contexto de usuario, de qué contexto queremos obtener
the user context like from which context we want to get
3:21:06
esos datos, ahora déjame crear mi componente justo aquí y
that data now let me create my component right here and
3:21:10
voy a darle el nombre de perfil de usuario y ahora dentro de este
i'm going to just give it the name of like user profile and now inside this
3:21:13
componente tenemos que acceder a los datos de nuestro contexto
component we have to access the data from our context
3:21:16
vamos a usar el contexto para acceder a esos datos, de qué contexto, de este contexto de usuario que ya hemos especificado o
we are going to be using the use context to access that data from which context from this user context which we've already specified or
3:21:24
definir justo aquí, así que eso está
define right here okay so that's
3:21:27
hecho, ahora voy a desestructurar solo el usuario, no necesitamos esto
done now i'm going to destructure only the user we don't need this
3:21:30
actualizar usuario justo aquí, solo estamos interesados en este usuario
update user right here we are only interested in this user
3:21:33
que ahora estamos proporcionando justo aquí, está bien si quieres obtener eso
which we are now providing right here okay if you want to get that
3:21:37
usuario, así que voy a eliminar este perfil de usuario de aquí y voy
user so i'm going to remove this user profile from here and i'm going
3:21:40
a escribir como h1 perfil de usuario y ahora debajo
to write like h1 user profile and now underneath
3:21:43
este h1 vamos a crear nuestro párrafo y aquí tenemos que renderizar nuestro usuario punto nombre, está bien, así que sí, eso va a estar bien. Así que ahora, si guardo mi archivo, déjame solo ejecutar allí.
this h1 we are going to be creating our paragraph and here we have to render our user dot name okay so so yeah that's going to be fine So now if I save my file, let me just run there.
3:21:53
npm run dev. No nos va a dar nada porque tenemos que definir allí dentro de nuestra aplicación.
npm run dev. It's not going to give us anything because we have to define there inside our app.
3:21:59
Así que solo escribiré como perfil de usuario. P-R-O-F-I-L-E. Ahí vamos. Ahora déjame solo guardar mi archivo y refrescar allí.
So I'll just write like user profile. P-R-O-F-I-L-E. There we go. Now let me just save my file and refresh there.
3:22:07
Aún así, no estamos obteniendo nada. No sé por qué. Solo abramos mi elemento de inspección. Ve a la consola.
Still, we are not getting anything. I don't know why. Let's just open my inspect element. Go to the console.
3:22:13
Y estamos obteniendo algún tipo de error. No se puede desestructurar una propiedad del contexto de usuario ya que está indefinido. Oh, y mi error.
And we are getting some sort of error. Cannot destructure a property of user context as it is undefined. Oh, and my bad.
3:22:20
aquí también tenemos que escribir nuestro proveedor de usuario para que podamos proporcionar eso en toda nuestra aplicación
here we also have to write our user provider so that we can provide that in our entire application
3:22:27
así que solo escribiré como proveedor de usuario y ahora podremos
so i'll just write like user provider and now we will be successfully
3:22:30
obtener esos datos, así que aquí puedes ver que ahora estamos obteniendo el usuario
able to get that data so here you can see we're now getting the user
3:22:33
perfil y ahora estamos obteniendo los datos del contexto dentro
profile and we're now getting the data from the context inside
3:22:37
de este componente de perfil de usuario, así que esa es la
this user profile component so that's the
3:22:40
segunda cosa, ahora para la última cosa tenemos que crear nuestro componente update user.jsx y déjame solo eliminar eso de allí y aquí
second thing now for the final thing we have to create our update user.jsx component and let me just remove that from there and here
3:22:49
una vez más, vamos a importar el use context que
once again we are going to be importing the use context which
3:22:52
nos permitirá obtener los datos y también el use state
will allow us to get the data and also the use state
3:22:55
y que nos permitirá crear nuestro estado y también vamos a importar
and which will allow us to create our state and we're going to be also importing
3:22:59
el contexto de usuario de nuestro contexto que hemos
the user context from our context which we've
3:23:02
ya definido hace unos segundos y voy a usar mi rafce
already defined a few seconds ago and i'm going to be using my rafce
3:23:05
para definir mi componente y ahora dentro de allí vamos
to define my component and now inside there we're
3:23:08
a desestructurar el update user de dónde, del use context si quieres desestructurar allí de este específico
going to be destructuring the update user from where from the use context if you want to destructure there from this specific
3:23:16
contexto de usuario, ahora debajo de eso vamos a obtener
user context now underneath that we are going to be getting
3:23:19
el nuevo nombre y solo escribamos como set new
the new name and let's just write like set new
3:23:22
nombre y eso va a ser igual al use state y el
name and that's going to be equals to the use state and the
3:23:25
el valor inicial se establecerá como una cadena vacía ahora para esta interfaz
initial value will be set to empty string now for this ui
3:23:28
voy a eliminarlos y escribir mi h2 que dirá
i'm going to remove them and write my h2 which will say
3:23:32
como actualizar el nombre de usuario y ahora debajo
like update username and now underneath
3:23:35
que simplemente vamos a crear nuestro formulario, eliminar la acción porque no
that let's just create our form remove the action because we
3:23:38
necesitamos allí y proporcionar el evento on submit y en este submit
don't need there and provide the on submit and on this submit
3:23:41
vamos a estar ejecutando esta función que vamos a crear en unos segundos
we are going to be firing this function which we we are going to be creating in a few seconds
3:23:44
y también tendremos que crear nuestro campo de entrada el
and we will also have to create our input field the
3:23:48
tipo se establecerá en texto el valor se establecerá en
type will be set to text the value will be set to
3:23:51
nuevo nombre que ya estamos definiendo aquí mismo
new name which we are already defining right here
3:23:54
y cuando alguien escribe algo en este campo de entrada, así que estamos
and when somebody types something in this input field so we are
3:23:57
vamos a estar ejecutando esta función que dirá como establecer nombre o
going to be firing this function which will say like set name or
3:24:00
establecer nuevo nombre en cambio y vamos a estar obteniendo nuestros datos usando
set new name rather and we are going to be getting our data by using
3:24:03
el valor del evento punto objetivo punto valor está bien y
the event dot target dot value okay and
3:24:06
ahora fuera de allí también vamos a proporcionar un marcador de posición que
now outside from there we are going to be also providing a placeholder to the which
3:24:09
dirá como ingresar nuevo nombre ahora déjame decir
will say like enter new name now let me just say
3:24:12
mi archivo y ahora debajo de eso también vamos a crear un
my file and now underneath there we are going to be also creating a
3:24:15
botón que dirá como actualizar y el tipo
button which will say like update and the type
3:24:19
se establecerá en enviar está bien así que ahora
will be set to submit okay so now
3:24:22
déjame crear esta función de manejar envío aquí mismo así que
let me just create this handle submit function right here so
3:24:25
no vamos a hacer nada loco, pero vamos a proporcionar nuestro objeto de evento y ahora dentro de allí vamos a prevenir el comportamiento predeterminado
we are not going to be doing anything crazy but we are going to be providing our event object and now inside there we are going to be preventing the default behavior
3:24:33
está bien y también vamos a verificar si nuevo nombre punto trim, escribamos nuestro trim así que si
okay and also we are going to be checking if new name dot trim let's just write our trim so if
3:24:41
si ese es el caso, vamos a usar updateUser y proporcionar nuestro nuevo nombre allí.
If that's the case, we are going to be using updateUser and provide our new name to there.
3:24:46
Y también vamos a vaciar nuestro campo de entrada proporcionando un setNewName y establecer allí en emptyString.
And we are going to be also empty out our input field by providing a setNewName and set there to emptyString.
3:24:53
Ahora déjame guardar mi archivo y ahora si escribo algo dentro de ese componente, pero primero tenemos que registrar allí mismo como updateUser user
Now let me just save my file and now if I type something inside that component, but first of all we have to register there right here like updateUser user
3:25:01
y ahora déjame decir mi así que aquí puedes ver que ahora estamos obteniendo nuestros datos de
and now let me just say my so here you can see we are now getting our data from
3:25:04
otro componente y ahora si escribo como Arnaud
another component and now if I write like Arnaud
3:25:07
mi nombre si hago clic en actualizar, así que se va a actualizar su
my name if I click on the update so it's going to update their
3:25:10
datos, pero estamos obteniendo algún tipo de error en la nueva actualización
data but we are getting some sort of error new update
3:25:14
no está definido, maldita sea, en lugar de un nuevo nombre especifiqué la nueva actualización, así que ahora déjame cambiar allí a un nuevo nombre, digamos mi archivo y actualizar allí
is not defined okay god damn it instead of a new name I specified the new update so now let me just change there to a new name say my file and refresh there
3:25:24
y si escribo mi propio nombre una vez más, hago clic en actualizar y aquí tú
and if i write my own name once again click on the update and here you
3:25:27
puedes ver que se va a actualizar su nombre si escribo algo más
can see it's going to update their name if i write like something else
3:25:31
y hago clic en actualizar, así que se va a cambiar allí a algo más
and click on the update so it's going to change there to something else
3:25:34
así que sí, ese fue nuestro desafío sobre el uso
so yeah that was our challenge about the use
3:25:37
contexto y también el sí y
context and also the yeah and
3:25:40
también solo sobre el contexto, ahora hablemos sobre el hook use reducer, así que use reducer es un hook que es similar al hook use state, pero está diseñado para más complejos
also just about the context now let's talk about the use reducer hook so use reducer is a hook that is similar to the use state hook but it is designed for more complex
3:25:49
objeto de estado o transiciones de estado, hay múltiples subvalores.
state object or state transitions, there involves multiple sub values.
3:25:54
Así que te permite gestionar el estado de manera funcional e inmutable.
So it allows you to manage state in the functional and immutable way.
3:25:58
Sé que la definición suena un poco aterradora y créeme,
I know the definition sounds a bit scary and trust me,
3:26:02
la sintaxis es más aterradora que la, pero para el curso, prometo que te voy a dar mucha práctica sobre el hook user reducer.
the syntax is more scarier than the, but for the course, I promise I'm going to give you a lot of practice about the user reducer hook.
3:26:09
Así que ahora así es como se verá la sintaxis. Primero que todo, tenemos nuestro user reducer y ahora estamos pasando la función reductora y también el valor inicial
So now this is how the syntax will look like. First of all, we have our user reducer and we are now passing the reducer function and also the initial value
3:26:17
para allí y ahora estamos desestructurando el estado y también el
for there and we are now destructuring the state and also the
3:26:20
despacho, así que ¿qué significa todo eso?
dispatch so what is all of that even mean
3:26:23
así que ahora hablemos sobre el estado inicial del use reducer, así que
so now let's talk about the use reducer initial state so
3:26:26
este es el valor inicial para el estado cuando el componente se renderiza por primera vez
this is the starting value for the state when the component first renders
3:26:30
vamos a pasar algún tipo de valor inicial allí, así que
we are going to be passing some sort of initial value to there so
3:26:33
si estás construyendo algún tipo de aplicación de contador, vas a pasar un
if you are building some sort of a counter app you're going to be passing a
3:26:36
valor cero o un valor de 10 o algo así, a continuación tenemos una función reductora, esta es una función que describe cómo la función debería cambiar según algunas acciones o algunas condiciones.
zero value or 10 value or anything like that next we have a reducer function this is a function they describe how the function should chase based on some actions or some conditions.
3:26:47
Así que toma el estado actual y la acción como entrada y devuelve un nuevo valor de estado para nosotros. Está bien.
So it takes the current state and the action as an input and return a new state value to us. Okay.
3:26:54
Así que así es como se verá nuestro user reducer. Pero ahora hablemos sobre las cosas que vamos a desestructurar del user reducer.
So this is how our user reducer will look like. But now let's talk about the things which we are going to be destructuring from the user reducer.
3:27:00
Así que la primera cosa que tenemos es el estado y este va a ser el valor actual del estado que puedes usar dentro de tu componente.
So the first thing that we have is the state and this is going to be the current state value which you can use inside your component.
3:27:07
Y luego tenemos una función de despacho y es una función que puedes llamar
And then we have a dispatch function and it is a function you can call
3:27:10
para enviar acciones a la función reductora que luego actualiza
to send action to the reducer function which then updates
3:27:14
ese estado, así que sé que puede sonar un poco aterrador y
that state so i know it may sound a bit scary and
3:27:17
difícil, pero confía en mí, no lo es, así que sabes qué, ahora
difficult but trust me it's not so you know what now
3:27:20
vamos a entrar en la codificación, entonces sabrás de qué estoy hablando, vamos a usar el
let's get into the coding then you will get to know what i'm talking about let's use the
3:27:23
reductor de usuario en acción, así que lo que voy a hacer es que voy a tomar mi reductor de usuario de react.js, a continuación, tenemos que usar eso, así que para usar eso vamos a estar usando el reductor de usuario
user reducer in action so what i'm going to do is that i'm going to grab my user reducer from the react.js next we have to use that so to use that we are going to be using the user reducer
3:27:35
y toma dos parámetros como la función reductora y también el estado inicial i n i t i a
and it takes two parameters like the reducer function and also the initial state i n i t i a
3:27:43
no puedo deletrear el inicial, así que esto es
i can't spell the initial so this is
3:27:46
cómo vamos a estar usando la función de uso reductor y ahora
how we are going to be using the use reducer function and now
3:27:49
vamos a estar desestructurando dos cosas, vamos a estar desestructurando
we are going to be destructuring two things we are going to be destructuring
3:27:52
el estado y también la función de despacho, así que ahora déjame explicar
the state and also the dispatch function so now let me explain
3:27:55
todo eso ahora mismo, primero que nada estamos proporcionando el estado inicial que vamos a estar creando aquí mismo, como cuál será el valor inicial de nuestro estado completo.
all of that right now first of all we are providing the initial state which we are going to be creating right here like what will be the initial value of our entire state.
3:28:05
Así que si estás construyendo algún tipo de aplicación de contador, vamos a estar proporcionando el valor inicial de cero para eso.
So if you are building some sort of a counter app, so we are going to be providing the initial value of zero to that.
3:28:10
Así que solo voy a escribir como cons estado inicial y ahora dentro de ahí vamos a proporcionar como conteo y ese conteo se establecerá en cero porque solo estamos creando un ejemplo simple de un contador.
So I'm going to just write like cons initial state and now inside there we are going to just provide like count and that count will be set to zero because we are just creating a simple example of a counter.
3:28:20
A continuación, tenemos una función reductora y vamos a estar creando la función reductora aquí mismo.
Next we have a reducer function and we are going to be creating the reducer function right here.
3:28:26
Así que solo escribiré como cons reductor y este reductor tomará dos cosas.
So I'll just write like cons reducer and this reducer will take two things.
3:28:30
Tomará el estado y también tomará la acción
It will take the state and it will also take the action
3:28:33
así que ¿por qué tenemos que proporcionar el estado y también la acción?
so why do we have to provide the state and also the action it
3:28:36
tomará el estado, como qué cosa estamos actualizando
will take the state like what thing we are updating
3:28:39
y luego cómo tenemos que actualizar esa cosa
and then how we have to update that thing
3:28:43
ok, como qué estamos actualizando y cómo
okay like what are we updating and how
3:28:46
estamos actualizando, así que eso es lo único que tienes que tener en mente, así que
are we updating so that's the only thing that you have to keep in mind so
3:28:49
ahora vamos a usar qué vamos a actualizar y cómo vamos a
now let's use what we will update and how we
3:28:52
actualizar eso, así que para usar eso podemos usar la declaración if y l, podemos usar el ternario, pero en esta situación vamos a estar usando el
will update that so to use that we can either use the if and l statement we can use the ternary but in this situation we are going to be using the
3:28:59
switch y casos, ok, así que solo usaré como switch y si yo
switch and cases okay so i'll just use like switch and if i
3:29:02
simplemente presiona enter, así que nos dará casos de terceros gratis ahora
just hit enter so it's going to give us third cases for free now
3:29:06
voy a estar usando acción y luego voy a proporcionar un tipo que
i'm going to be using action and then i'm going to provide a type we
3:29:09
vamos a estar usando esta acción utilizando esta función de despacho
are going to be using this action by using this dispatch function
3:29:12
pero no tienes que preocuparte por lo que es un despacho por ahora, así que si
but you don't have to worry about what a dispatch is for now so if
3:29:15
este tipo de acción es igual a incrementar, así que
this action type is equal to increment so
3:29:19
vamos a proporcionar como incrementar, así que en esta situación solo queremos devolver cada cosa que ya está
we're going to just provide like increment so in this situation we only want to return every single thing which is already
3:29:26
disponible dentro de nuestro estado, como si estuviéramos creando una copia de nuestro estado y luego solo queremos actualizar el conteo y queremos actualizarlo accediendo primero a state.count y luego más uno.
available inside our state like we are creating a copy of our state and then we only want to update the count and we want to update there by first of all accessing state.count and then plus one.
3:29:37
voy a guardar mi archivo y ahora déjame decirlo una vez más.
I'm going to save my file and now let me just say there once again.
3:29:40
Esta función reductor tomará el estado y la acción
This reducer function will take the state and action
3:29:44
y si ese tipo de acción es igual a incrementar, así que en esta situación vamos a estar creando la copia de nuestro estado completo, como supongamos que tenemos algún tipo de
and if that action type is equal to increment so in this situation we are going to be creating the copy of our entire state like let's suppose if we have some sort of
3:29:52
otras cosas como la notificación es
other stuff like notification is
3:29:56
eso encendido o apagado o algo así, así que vamos a hacer
that on or off or something like that so we are going to be making
3:29:59
una copia de eso y ahora en esta situación, si la acción
a copy of that and now in this situation if the action
3:30:02
el tipo es igual a incrementar, solo vamos a actualizar esto
type is equal to increment we are going to be only updating this
3:30:06
conteo y de dónde viene este conteo, este conteo viene
count and where is this count coming from this count is coming
3:30:09
de este estado que vamos a proporcionar para nuestra función de despacho y este estado ya tiene el conteo de valor cero aquí y solo queremos incrementar allí por uno, está bien, así que eso será para el incremento
from this state which we are going to be providing for our dispatch function and this state already has the count of zero value right here and we only want to increment there by one okay so that's going to be for the increment
3:30:21
ahora hablemos del decremento, así que voy a simplemente quitar eso de aquí, estoy
now let's talk about the decrement so i'm going to just remove that from here i'm
3:30:24
también voy a proporcionar otro caso para el decremento y si
going to also provide yet another case for the decrement and if
3:30:28
quieres proporcionar un poco más de estado, eres más que bienvenido a usar eso si
you want to provide some more state you are more than welcome to use that if
3:30:31
lo deseas, pero en mi caso solo voy a devolver primero
you wanted to but in my case i'm going to only return first of
3:30:34
todo, mi estado una vez más y luego vamos a
all dot dot dot my state once again and then we are going
3:30:37
estar cambiando nuestro conteo y nuestro conteo viene del
to be changing our count and our count is coming from the
3:30:40
estado punto conteo y solo vamos a estar decrementando
state dot count and we are going to be just decrementing
3:30:43
ahí, así que solo tienes que tener eso en mente, así que puedo simplemente eliminar estos espacios, supongo que voy a guardar mi archivo
there okay so you just have to keep that in mind so i can just totally remove these spaces i guess i'm going to save my file
3:30:49
y así es como se ve aquí, así que eso es genial
and this is how it looks like right here so that's cool
3:30:52
pero ahora también me voy a encargar del reinicio y
but now i'm going to also take care of the reset and
3:30:55
supongo que no los necesitamos, sí, los necesitamos o
i guess we don't need yeah we do need them or
3:30:59
para otro caso más para el reinicio como estamos
for yet another case for the reset like we are
3:31:02
vamos a proporcionar algún tipo de botón de reinicio allí, así que en
going to be also providing some sort of a reset button to there so in
3:31:05
esa situación vamos a estar devolviendo una vez más todo
that situation we are going to be once again returning all
3:31:08
nuestro estado completo y solo vamos a cambiar el conteo a cero, está bien, así que eso es genial y para la última cosa solo vamos a devolver
of our entire state and we are going to be just changing the count to zero okay so that's cool and for the final thing we are going to be just returning
3:31:18
el estado en general, así que voy a cortar todo eso y aquí
the state overall so i'm going to just cut all of that and here
3:31:21
puedes ver cómo vamos a estar creando o definiendo nuestro
you can see this is how we are going to be creating or defining our
3:31:24
función reductora, así que ahora estos pasos ya están completados con éxito
reducer function so now these steps are now successfully done
3:31:28
la siguiente cosa que tenemos que hacer es que tenemos que encargarnos del estado
the next thing that we have to do is that we have to take care of the state
3:31:31
y el despacho, usamos este estado para mostrar los datos en
and the dispatch we use this state to show the data into
3:31:35
nuestra interfaz, está bien, así que cómo se verá aquí, puedes ver que
our ui okay so how that's going to look like here you can see i
3:31:38
tengo mi div y ahora dentro de este div solo crearé mi h1
have my dev and now inside this dev i'll just create my h1
3:31:41
justo aquí y en esta situación voy a estar usando el estado que proviene de este use reducer, ahora estamos usando esto
right here and in this situation i'm going to be using like state which is coming from this use reducer we're now using this
3:31:47
estado y ahora dentro de este estado tenemos la propiedad de
state and now inside this state we have the property of
3:31:50
conteo, como si tuvieras algún otro tipo de propiedad como notificación o
count like if you have some sort of other property like notification or
3:31:54
está oscuro o algo así, vamos a estar accediendo allí
is dark or something like that we're going to be accessing there
3:31:58
pero ahora en esta situación solo tenemos el conteo, así que voy a acceder allí, justo aquí, así que ahora el valor inicial de mi conteo está establecido en cero, así que vamos a obtener un valor cero justo aquí
but now in this situation we only have the count so i'm going to access there right here so now initial value for my count is set to zero so we are going to be getting a zero value right here
3:32:08
está bien, así que solo puedo poner algún tipo de etiqueta como conteo justo aquí, semi archivo y ahora estamos obteniendo
okay so i can just put some sort of a label like count right here semi file and now we are getting
3:32:14
este conteo y así es como nos permitirá acceder
this count and this is how it's going to allows us to access
3:32:17
nuestros datos dentro de nuestro jsx ahora
our data inside or jsx now
3:32:20
hablemos de esta función de despacho, esta función de despacho
let's talk about this dispatch function this dispatch function will
3:32:23
nos permitirá cambiar tu estado, como realmente cambiar
allows us to change your state like actually change
3:32:28
tu estado, esto nos permitirá proporcionar algún tipo de regla
your state this will allows us to provide some sort of a rule
3:32:31
si esa regla es igual a incrementar, así que vamos a
if that rule is equal to increment so we are going
3:32:34
vamos a incrementar si esa regla es igual a decrementar, así que vamos a decrementar y así sucesivamente, así que estas son solo una regla, ahora vamos a usar eso
to be incrementing if that rule is equal to decrementing so we are going to be decrementing and so on and so forth so these are just a rule now we are going to be using that
3:32:42
reglas dentro de nuestra función de despacho y esto
rules inside our dispatch function and this
3:32:45
la función de despacho nos permitirá cambiar
dispatch function will allows us to actually change
3:32:49
nuestro estado, así que voy a crear algunos botones aquí
our state okay so i'm going to just create a few buttons right here
3:32:52
así que solo usaré un botón y ahora dentro de este botón voy a
so i'll just use like button and now inside this button i'm going to
3:32:55
simplemente proporcionar mi símbolo de más aquí, también puedes escribir como más si
just provide my plus symbol right here you can also write like plus if
3:32:58
querías, pero en mi caso voy a escribir como más y
you wanted to but in my case i'm going to just write like plus and
3:33:01
también voy a especificar el controlador de eventos on click y cuando
i'm going to also specify the on click event handler and when
3:33:04
alguien haga clic en ellos, vamos a activar nuestra función de despacho y ahora dentro de esta función de despacho vamos a proporcionar
somebody clicks on them we are going to be firing our dispatch function and now inside this dispatch function we are going to be providing
3:33:11
el tipo y si ese tipo es igual a incrementar, así que
the type and if that type is equal to increment so
3:33:14
ya sabes qué tenemos que hacer en esa situación, estamos
you already know what do we have to do in that situation we
3:33:18
ahora proporcionando un tipo y ese tipo es si
are now providing a type and that type is if
3:33:21
ese tipo es igual a incrementar, como si este tipo de acción
that type is equal to increment like if this action type
3:33:24
es igual a incrementar, vamos a estar incrementando eso, está bien
is equal to increment we're going to be incrementing that okay
3:33:27
así que también voy a crear otro
so i'm going to also create yet another
3:33:30
botón que dirá menos y cuando alguien haga clic en ese botón, vamos a usar nuevamente la función de despacho, simplemente proporcionemos nuestro tipo
button which will just say minus and when somebody click on that button we are going to be just using like dispatch function once again let's just provide our type
3:33:38
y vamos a proporcionar el decremento aquí d-e-c-r-e-m-e-n-t
and we are going to be providing the decrement right here d-e-c-r-e-m-e-n-t
3:33:43
ahí vamos, voy a guardar este archivo y finalmente vamos a crear
there we go i'm going to save this file and finally we are going to be creating yet
3:33:46
otro botón para el reinicio, así que solo escribiré un reinicio aquí
another button for the reset so i'll just write a reset right here
3:33:49
y cuando alguien haga clic en este botón, vamos
and when somebody click on this button we're going
3:33:52
a activar esta función de despacho una vez más y vamos
to be firing this dispatch function once again and we
3:33:55
a proporcionar el tipo y el tipo será reiniciar, está bien
are going to be providing the type and type will reset to reset okay
3:33:58
así que voy a guardar mi archivo y eso es todo lo que tienes que hacer para el uso del reductor, está bien, así que si hago clic en este botón de incrementar, simplemente va a incrementar
so i'm going to save my file and that's all the thing that you have to do for the use reducer okay so if i click on this increment button so it's going to just increment
3:34:07
mi contador, si hago clic en este botón de decrementar, simplemente va a decrementar
my counter if i click on this decrement button so it's going to decrement
3:34:10
mi contador y finalmente, si hago clic en
my counter and finally if i click on
3:34:13
el botón de reinicio no va a hacer nada, no sé
the reset button it's not going to do anything i don't know
3:34:16
por qué aquí puedes ver que ahora lo estamos poniendo re y sin
why here you can see we are now putting it re and without
3:34:19
el reinicio, así que ahora si hago clic
the e reset so now if i click
3:34:22
en este botón, lo va a poner en cero, así que si disminuyo
on this button it's going to make it as a zero so if i decrement
3:34:26
eso como mucho tiempo y si hago clic en el reinicio, está funcionando y también el incremento está totalmente funcionando, así que sí, así es como vamos a encargarnos de la función o gancho de usuario Reducer, para ser precisos.
it like a lot of time and if i click on the reset it's working and also the increment is totally working so yeah this is how we are going to be taking care of the user Reducer function or hook to be precise.
3:34:38
Muy bien, así que es hora del desafío del reductor de usuario. Así que primero quiero que crees el archivo counterreducer.js y dentro de ese archivo, define la función reductor que gestionará un estado de contador simple.
Alrighty, so time for the user reducer challenge. So first of all, I want you to create the counterreducer.js file and inside that file, define the reducer function that will manage a simple counter stat.
3:34:48
A continuación, tienes que crear un archivo con el nombre de counter.jsx y dentro de ese archivo, crea un componente funcional con el nombre de contador, luego usa el gancho de reductor de usuario para gestionar el estado de ese contador.
Next, you have to create a file with the name of counter.jsx and inside that file, create a functional component with the name of counter, then use the user reducer hook to manage the stat of that counter.
3:34:58
Y luego, para el tercer paso, modifica el counter reducer.js
And then for the third step modify the counter reducer.js
3:35:02
archivo para agregar más acciones que te permitirán aumentar y
file to add more action which will allow you to increase and
3:35:05
disminuir por una cantidad específica, luego actualiza eso
decrease by a specific amount then update that
3:35:08
archivo counter.jsx para aumentar y disminuir el conteo por un
counter.jsx file to increase and decrease the count by a
3:35:12
valor específico usando el campo de entrada, así que finalmente
specific value using the input field so finally
3:35:15
tienes que registrarlo dentro del archivo app.jsx y
you have to register the inside the app.jsx file and
3:35:18
eso va a ser todo, así que una vez más, debido a tu base, si puedes hacerlo, está completamente bien, luego vuelve y mira la solución y voy a estar creando mi, ¿cómo lo llamamos?, archivo counterreducer.js.
that's going to be it so once again due to your base shot if you can do it that's completely OK then come back and watch the solution and I'm going to be creating my what do we call it counterreducer.js file.
3:35:30
OK, así que dentro de este archivo vamos a estar definiendo primero nuestro estado inicial, así que usaré como estado inicial y eso va a ser igual al conteo y el conteo se establecerá en cero.
OK so inside this file we are going to be first of all defining our initial state so I'll use like initial state and that's going to be equals to the count and count will be set to zero.
3:35:40
Ahora, debajo de eso, vamos a estar creando una función y
Now underneath that we are going to be creating a function and
3:35:43
le voy a dar el nombre de como counterreducer y va a tomar el estado y también la acción y aquí vamos a estar usando, como una vez más, el switch y ksso
I'm going to give it the name of like counterreducer and it's going to take the state and also the action and here we are going to be using like once again the switch and ksso
3:35:51
para el switch, vamos a estar proporcionando un action dot
for the switch we're going to be providing an action dot
3:35:54
tipo, así que si ese es el caso, vamos a estar proporcionando el
type so if that is the case we're going to be providing the
3:35:58
primer caso como incrementar, así que si el caso
first case like increment so if the case
3:36:01
es incrementar, vamos a estar devolviendo el conteo y
is increment we're going to be returning the count and
3:36:04
simplemente escribamos el estado de conteo para acceder a nuestros datos de nuestro
let's just write state count to access our data from our
3:36:07
conteo y vamos a estar incrementándolos en uno, pero
count and we're going to be incrementing them by one but
3:36:10
si ese no es el caso y si el caso está configurado para disminuir, vamos a estar usando la declaración de retorno una vez más, simplemente usemos su retorno y vamos a
if that's not the case and if the case is set to decrement we are going to be using the return statement one more time let's just use your return and we're
3:36:18
obtener el conteo usando el estado punto conteo una vez más y simplemente eliminemos uno del decremento.
to be getting the count by using the state dot count one once
3:36:21
de nuevo y solo vamos a quitar uno del decremento
again and let's just remove one from the decrement
3:36:25
uno de ahí así que no voy a continuar y crear una interfaz de usuario para
one from there so i'm not going to go ahead and create a ui for
3:36:28
que también voy a crear ese otro estado también así que solo voy a
that i'm going to also create that other state as well so i'll just
3:36:31
usar como caso y aumentar por cantidad venir
use like case and increment by amount come
3:36:34
en aumentar por cantidad ahí vamos y voy a usar como retorno y solo vamos a escribir cuenta countStat.count más action.payload.
on increment by amount there we go and i'm going to use like return and let's just write count countStat.count plus action.payload.
3:36:45
Voy a escribir el payload así. También voy a duplicar ahí y cambiar ahí para en lugar de un incremento voy a escribir como decremento decremento por cantidad.
I'm going to write payload like so. I'm going to also duplicate there and change there to instead of an increment I'm going to write like decrement decrement by amount.
3:36:57
Una vez más en lugar de escribir un más voy a cambiar ahí a menos y para el valor por defecto solo voy a devolver mi estadística general.
Once again instead of writing a plus I'm going to change there to minus and for the default value I'm going to only return my overall stat.
3:37:04
Así que esa va a ser nuestra función completa que nos permitirá cambiar nuestros datos.
So that's going to be our entire function which will allows us to change our data.
3:37:09
Así que así es como vamos a crear lo que es el reductor de contador y
So that's how we are going to be creating what counter reducer and
3:37:12
ahora debajo de ellos vamos a exportar el inicial
now underneath them we're going to be exporting the initial
3:37:15
estado y también la función del reductor de contador
state and also the counter reducer function
3:37:18
en este archivo así que voy a continuar e ir a mi
on this file okay so i'm going to go ahead and go to my
3:37:21
componente y crear mi counter.js.jsx
component and create my counter.js.jsx
3:37:26
archivo voy a definir mi rfc dentro de ahí ir a mi app y registrarme ahí mismo así que usaré como contador y presionaré enter así que se va a registrar ahí
file i'm going to define my rfc inside there go to my app and register there right here so i'll use like counter and hit enter so it's going to register there
3:37:36
y déjame ver cómo se ve así que así es como se ve
and let me just see how it looks so this is how it looks like
3:37:39
y sí, estamos avanzando ir a
and yeah we are getting somewhere go to
3:37:42
mi contador una vez más y lo primero que quiero hacer es que quiero
my counter one more time and the first thing that i want to do is that i want to
3:37:45
obtener mi reductor de usuario y también la función de inicio de uso de
get my user reducer and also the use start function from
3:37:48
nuestro reactjs también vamos a obtener algunas
our reactjs we're going to be also getting a few
3:37:51
cosas de nuestros archivos de reductor así que vamos a
things from our reducer files so we're going
3:37:55
obtener primero el reductor de contador y también
to be getting first of all the counter reducer and also
3:37:58
el inicio inicial ven aquí inicio inicial de este reductor de contador ahora déjame usar mi usuario
the initial start come on initial start from this counter reducer now let me use my user
3:38:05
reductor para definir mi función de despacho y también mi estado
reducer to define my dispatch function and also my state
3:38:08
así que voy a estar usando como usar reductor y para el valor inicial estoy
so i'm going to be using like use reducer and for the initial value i'm
3:38:11
voy a escribir como reductor de contador y también el valor inicial
going to write like counter reducer and also the initial value
3:38:14
que ya hemos definido, está bien, así que aquí vamos a desestructurar
which we've already defined okay so here we're going to be destructuring
3:38:17
el estado y también el despachador que va a ser igual a
the state and also the dispatch that's going to be equals to
3:38:20
este uso del reductor, ahora debajo de eso también vamos a crear
this use reducer now underneath that we're going to be also creating
3:38:23
un estado para el formulario, sí, usaré como entrada
a state for the form yes i'll use like input
3:38:26
valor y también establecer el valor de entrada, está bien
value and also set input value okay
3:38:30
así que eso va a ser igual al estado utilizado y aquí vamos a proporcionar
so that's going to equals to the used state and here we are going to be providing
3:38:33
solo cero aquí, está bien, así que ahora déjame guardar, siguiente
only zero right here okay so now let me save there next
3:38:36
déjame encargarme de esta interfaz de usuario, así que voy a ir allí y escribir
let me take care of this ui so i'm going to go there and write
3:38:39
h2 y proporcionar mi valor de contador, así que usaré como
h2 and provide my counter value so i'll use like
3:38:43
estado punto cuenta para acceder a ese valor, déjame
state dot count to access that value let me
3:38:46
simplemente guardar mi archivo y revisar esto, así que aquí puedes ver que ahora estamos obteniendo la cuenta que ahora está configurada en cero, así que eso es genial, pero ahora tenemos que incrementar y también decrementar, así que voy a usar como botón
just save my file and check this out so here you can see we are now getting count which is now set to zero so that's cool but now we have to increment and also decrement there so i'm going to be using like button
3:38:56
y que nos permite incrementar mi contador y otro botón
and which allows us to increment my counter and another button
3:38:59
que nos permite decrementar mi contador, está bien
which allows us to decrement my counter okay
3:39:02
así que voy a escribir como un manejador de eventos on click cuando
so i'm going to just write like on click event handler when
3:39:06
alguien haga clic allí, vamos a disparar como manejar incremento
somebody click on there we are going to be firing like handle increment
3:39:09
y también manejar decremento
and also handle decrement
3:39:12
está bien y ahora déjame crear esta función aquí, así que no vamos a hacer nada loco, pero vamos a crear como manejar incremento y eso va a ser igual a esta función de flecha, vamos
okay and now let me create this function right here so we're not going to be doing anything crazy but we are going to be creating like handle increment and that's going to be equals to this arrow function come on
3:39:24
eso va a ser igual a esta función de flecha y vamos a llamar a la función de despachar y proporcionar el tipo de incremento allí.
that's going to be equals to this arrow function and we are going to be calling the dispatch function and provide the type of increment to there.
3:39:30
Ahora déjame duplicar esta línea de código y cambiar eso a decrementar y también cambiar el nombre de la función a manejar decremento.
Now let me just duplicate this line of code and change that to decrement and also change the function name to handle decrement.
3:39:37
Así que solo escribiré como manejar decremento así. Así que ahora esta función nos permitirá cambiar nuestros datos.
So I'll just write like handle decrement like so. So now this function will allow us to change our data.
3:39:43
Así que ahora, si hago clic en este, va a incrementar mi contador. Ahora, si hago clic en el botón de decrementar, va a decrementar mi contador.
So now if I click on this one so it's going to increment my counter. Now if I click on the decrement button it's going to decrement my counter.
3:39:50
Ahora también tenemos que proporcionar nuestro campo de entrada que nos permitirá cambiar los datos proporcionando nuestro valor.
Now we also have to provide our input field which will allow us to change the data by providing our value.
3:39:55
Así que solo escribiré un div y dentro de este div vamos a proporcionar una entrada con un tipo de número
So I'll just write a div and inside this div we're going to be providing an input with a type of number
3:40:00
y también el valor se establecerá en el valor de entrada
and also the value will be set to input value
3:40:03
está bien y también voy a poner el manejador on change y
okay and i'm going to also put the on change handler and
3:40:07
aquí vamos a pasar nuestra función de flecha que tomará como establecer entrada
here we're going to be passing our arrow function which will take like set input
3:40:10
valor y voy a escribir como event.target.value
value and i'm going to write like event.target.value
3:40:14
eso también es genial, pero ahora debajo de eso voy a
that's also cool but now underneath there i'm going
3:40:17
crear un botón que dirá agregar y también voy a crear
to be creating a button which will say like add and i'm going to also create
3:40:20
otro botón que dirá restar, está bien, y aquí tenemos que escribir como manejador de eventos on click cuando
yet another button which will say subtract okay and here we have to just write like on click event handler when
3:40:27
alguien haga clic allí, vamos a estar manejando como incrementar
somebody clicks on there we're going to be fighting like handle increment
3:40:31
por uno, déjame escribir como incrementar por
by one let me just write like increment by
3:40:34
uno o por cantidad estará bien y
one or by amount will be fine and
3:40:37
también vamos a proporcionar manejar decremento por
we're going to be also providing handle decrement by
3:40:41
cantidad y ahora déjame crear estas dos funciones así que
amount and now let me just create these two functions so
3:40:44
voy a copiar el nombre de allí y definirlo aquí mismo
i'm going to copy the name of there and define there right here
3:40:47
const manejar incremento por uh por
const handle increment by uh by
3:40:50
cantidad y aquí vamos a proporcionar nuestro dispatch y para este dispatch para el tipo vas a proporcionar
amount and here we're going to be providing our dispatch and for this dispatch for the type you're going to be providing
3:40:56
incrementar por cantidad y también
increment by amount and we
3:40:59
tenemos que proporcionar nuestra carga útil, vamos carga útil y
also have to provide our payload come on payload and
3:41:03
para la carga útil tenemos que proporcionar nuestro valor de entrada, pero primero
for the payload we have to provide our input value but first
3:41:06
tenemos que convertir allí a número, así que si quieres convertir
of all we have to convert there to number so if you want to convert
3:41:09
allí a números, puedes usar el constructor de número o puedes
there to numbers so you can use the number constructor or you can
3:41:12
también simplemente usar un más y también va a convertir allí a número
also just use a plus and it's going to also convert there to number
3:41:16
está bien y ahora debajo voy a usar como establecer valor de entrada y cambiar allí a cero, así que va a limpiar la entrada después del dispatch y ahora si yo
okay and now underneath i'm going to use like set input value and change there to zero so it's going to clear the input after the dispatch and now if i
3:41:24
guardo mi archivo y solo funcionará para el primero
save my file and it's going to only work for the first
3:41:27
uno, nos dará un error porque también
one it's going to give us an error because we also
3:41:30
tenemos que crear esta función que es manejar decremento por
have to create this function which is handle decrement by
3:41:34
cantidad, así que voy a copiar el nombre de eso y básicamente
amount so i'm going to copy the name of that and basically
3:41:37
voy a duplicar toda esta función y cambiar
i'm going to just duplicate this entire function and change
3:41:40
voy a duplicar toda esta función y cambiar
the name of that to handle decrement by amount and i'm going to also change the name of this one to decrement by amount and the rest of them will be the same so now let me just save my file
3:41:51
y aquí puedes ver que puedo escribir como no sé, tal vez 100
and here you can see I can just write like I don't know maybe 100
3:41:55
si escribo eso y hago clic en agregar, se va a agregar
if I write that and click on the add so it's going to add
3:41:58
ese 100 justo aquí y si solo escribo como uh-huh
that 100 right here and if I just write like uh-huh
3:42:01
200 y hago clic en restar, se va a quitar
200 and click on a subtract so it's going to remove
3:42:05
100 de ahí, ahora nos va a dar menos
100 from there now it's going to give us minus
3:42:08
100, también puedo incrementar mi contador, yo
100 I can also increment my counter I
3:42:11
también puedo decrementar mi contador, así que sí, ese fue nuestro
can also decrement my counter so yeah that was our
3:42:14
contador complejo y también nuestro desafío sobre el user reducer, si escuchas una voz de construcción
complex counter and also our challenge about the user reducer if you're hearing a construction voice
3:42:20
en el fondo, lo siento por eso porque aquí en mi
is in the background i'm sorry about that because here in my
3:42:23
casa se está llevando a cabo una obra de construcción y no quiero retrasar esta radio
house a construction work is going on and i don't want to delay this radio
3:42:26
más, así que ahora hablemos sobre el use ref, así que ¿qué es
no more so now let's talk about the use ref so what is
3:42:30
el use ref y por qué a alguien le debería importar el user report proporciona
the use ref and why should anyone care about the user report provides
3:42:33
una forma de acceder e interactuar con el elemento del dom o
a way to access and interact with the dom element or
3:42:36
para persistir valores a través de render sin causar un
to persist value across render without causing a
3:42:39
re-render, así que este va a ser el gancho más simple
re-render so this is going to be the most simplest hook
3:42:43
en nuestra lista de ganchos, así que ahora entremos en la codificación, entonces vas a
in our hook list so now let's get into the coding then you will get
3:42:46
saber de qué estoy hablando, muy bien chicos, ahora es hora de usar el
to know what i'm talking about all right guys now it's time to use the
3:42:49
use ref dentro de nuestro componente, así que solo usaré el use ref
use ref inside our component so i'll just use the use ref
3:42:52
justo aquí, no reduzcas nuestro use ref, ahí vamos, vamos a
right here not reduce our use ref there we go we're
3:42:55
importar eso de react js y ahora tenemos que usar eso, así que
going to be importing that from the react js and now we have to use that so
3:42:58
usaré como use ref y para el valor inicial puedes especificar
i'll use like use ref and for the initial value you can specify
3:43:01
cualquier tipo de valor, así que solo escribiré como ahora porque
any kind of value so i'll just write like now because
3:43:05
no quiero especificar ningún valor para eso y luego tenemos que usar esto, así que para usar eso, primero vamos a almacenar allí en una especie de variable, así que solo usaré como const elemento y tenemos que igualarlo a este use ref.
i don't want to specify any value to that and next we have to use this so to use that first of all we are going to be storing there in some sort of a variable so i'll just use like cons element and we have to just equal to there to this use ref.
3:43:17
Así que ahora puedes registrar eso en la consola. Así que puedo usar como elemento justo aquí. Si guardo mi archivo y voy a mi consola, déjame refrescar allí.
So now you can totally log that to the console. So I can use like element right here. If I save my file and go to my console, let me just refresh there.
3:43:23
¿Qué estamos obteniendo? Ahora estamos obteniendo este objeto con la propiedad de current que inicialmente está configurada en no.
So what are we getting? We are now getting this object with the property of current and which is initially set to no.
3:43:29
Esta propiedad current nos permitirá manipular nuestro DOM o hacer cualquier cosa con nuestro DOM.
So this current property will allow us to manipulate our DOM or to do anything with our DOM.
3:43:34
Así que solo cambiaré eso a un elemento de entrada porque vamos a crear nuestro elemento de entrada aquí. Así que voy a cambiar eso a un elemento de entrada.
So I'll just change that to like input element because we're going to be creating our input element right here. So I'm going to change that to input element.
3:43:41
Puedes cambiar eso básicamente a cualquier cosa que quieras, así que en
You can like change that basically anything that you want so in
3:43:44
mi caso, el elemento de entrada estaría bien, solo crearé mi entrada
my case input element would be fine i'll just create my input
3:43:47
aquí y el tipo se establecerá en texto y
element right here and the type will be set to text and
3:43:50
voy a usar la propiedad ref y esta propiedad ref permitirá
i'm going to be using the ref property and this ref property will allow
3:43:53
usarnos para usar esta ref dentro de o
us to use this ref inside or
3:43:56
elemento específico así que solo usaré como mi elemento de entrada, ¿verdad?
specific element so i'll just use like my input element right
3:43:59
aquí y cuchillo guardo mi archivo y déjame solo registrar eso en la consola una vez más, así que solo usaré como elemento de entrada, cuchillo guardo mi archivo y los actualizo, está bien, así que aquí puedes ver que ahora estamos obteniendo nuestra entrada y también estamos obteniendo nuestra propiedad actual.
here and knife i save my file and let me just log that to the console once again so i'll just use like input element knife i save my file and refresh them okay so here you can see we are now getting our input and we are also getting our current property
3:44:12
y si expando esto, esa propiedad actual ahora apunta a
and if i expand this so that current property is now pointing to
3:44:15
este elemento de entrada justo aquí como puedes ver allí, así que si
this input element right here as you can see there so if
3:44:18
expando esto, tenemos como la propiedad de valor, tenemos mucho
i expand this we have like the value property we have a lot
3:44:22
de cosas que podemos hacer con este elemento html, así que
of things that we can do with this html element so
3:44:25
lo que voy a hacer es que simplemente lo voy a quitar de aquí y voy a
what i'm going to do is that i'm going to just remove that from here and i'm going
3:44:28
crear un botón justo aquí que solo dirá como enfocar y
to create a button right here which will just say like focus and
3:44:33
eh escribe hosin, tal vez puedas manipular tu tonto como quieras, pero en mi caso solo voy a enfocar y escribir HUSIN dentro de ese campo de entrada.
uh write hosin maybe you can basically manipulate your dumb however you want but in my case i'm going to just focus and write HUSIN inside that input field.
3:44:42
Así que solo usaré mi función de flecha y dentro de esta función de flecha, voy a crear una función que será un enfoque de entrada y voy a ejecutar esto.
So I'll just use my arrow function and inside this arrow function, I'm going to be creating a function which will be a focus input and I'm going to execute this.
3:44:48
Así que ahora déjame crear esta función justo aquí. Escribiré
So now let me just create this function right here. I'll write
3:44:51
como const enfoque entrada y ahora dentro
like const focus input and now inside
3:44:54
de allí, vamos a usar lo que elemento de entrada punto actual
there, we're going to be using what input element dot current
3:44:57
propiedad y luego vamos a usar este método de enfoque que es
property and then we're going to be using this focus method which is
3:45:01
proveniente del dom, está bien, así que solo tenemos que usar ven aquí f-o-c-u-s, tenemos
coming from the dom okay so we have to just use come on f-o-c-u-s we
3:45:05
que usar este método de enfoque y tan pronto como guarde mi archivo y
have to just use this focus method and as soon as i save my file and
3:45:08
actualice allí y ahora si hago clic en este botón, es
refresh there and now if i click on this button it's
3:45:11
voy a enfocar mi elemento de entrada justo aquí ahora puedo hacer básicamente
going to focus my input element right here now i can basically do
3:45:14
cualquier cosa que quiera hacer con este elemento puedo cambiar el color puedo proporcionar algo dentro de ahí así que ahora déjame mostrarte cómo vamos a escribir algo dentro de ahí así que voy a
anything i want to do with this element i can change the color i can like provide something inside there so now let me show you like how we are going to be writing something inside there so i'm going to
3:45:23
x es mi elemento de entrada luego voy a escribir mi propiedad actual
x is my input element then i'm going to write my current property
3:45:27
que ya proviene del uso de ref y voy a obtener el
which is already coming from the use ref and i'm going to get the
3:45:30
valor y ese valor se establecerá como mi propio nombre así que
value and that value will be set to like my own name so
3:45:33
voy a guardar mi archivo y ahora déjame simplemente refrescar eso y ahora una vez
i'm going to save my file and now let me just refresh that and now once
3:45:36
que haga clic en este enfoque y escriba así que va a enfocar primero
i click on this focus and write so it's going to first of all focus
3:45:39
o el elemento de entrada también va a escribir este nombre bien
or input element it's going to also write this name right
3:45:42
aquí así que si cambio eso a algo más como no sé john
here so if i change that to like something else like i don't know john
3:45:46
smith o algo así guarda mi archivo y ahora si hago clic en esto va a escribir este john smith justo aquí así que así es como
smith or something like this save my file and now if i click on this it's going to write this john smith right here so this is how
3:45:52
vamos a estar usando el uso de ref y vamos a usarlo muy raramente
we are going to be using the use ref and we are going to be very rarely
3:45:56
usando este uso de ref pero no sé que fue un uso
using this use ref but i don't know that was a use
3:45:59
tiempo para el gancho de uso de ref así que quiero que crees un componente con el
ref time for the use ref hook so i want you to create a component with the
3:46:02
nombre de focus input.jsx y ese componente
name of focus input.jsx and that component will
3:46:05
se enfocará en el campo de entrada cuando se haga clic en el botón en
focus on the input field when the button is clicked in
3:46:08
la segunda parte quiero que crees un componente timer.jsx y
the second part i want you to create a timer.jsx component and
3:46:12
simplemente implementa un temporizador simple donde el intervalo del temporizador se almacena
just implement a simple timer where the timer interval is stored
3:46:15
usando el ref así que dale lo mejor de ti si puedes hacerlo está completamente bien luego vuelve y mira la solución y ahora te voy a dar mi
using the ref so give it your best shot if you can do it that's completely okay then come back and watch the solution and now i'm going to give you my
3:46:21
solución así que lo que voy a hacer es que voy a crear mi focus input.jsx
solution so what i'm going to do is that i'm going to just create my focus input.jsx
3:46:27
y vamos a crear nuestro rafce guarda mi
and let's just create our rafce save my
3:46:30
archivo y vamos a ir a mi aplicación y almacenar allí justo aquí así que tenemos un enfoque de entrada y voy a ejecutarlos vamos a comprobar esto sí está funcionando
file and let's just go ahead and go to my app and store there right here so we have a focus input and i'm going to execute them let's just check this out yep it's working
3:46:40
ahora lo primero que quiero hacer es que quiero agarrar mi uso de ref de react.js y el valor inicial se establecerá en no y voy a almacenar eso en el ref de entrada como un valor
now the first thing that i want to do is that i want to grab my use ref from the react.js and the initial value will be set to no and i'm going to store that in the input ref as a value
3:46:49
y ahora tenemos que usar eso dentro de nuestra interfaz de usuario así que lo que voy a hacer
and now we have to use that inside our UI so what I'm going to do
3:46:52
es que voy a crear mi campo de entrada con el tipo de texto y voy a
is that I'm going to create my input field with the type of text and I'm going to
3:46:55
también proporcionar el ref y aquí el ref será ese
also provide the ref and here the ref will be that
3:46:58
referencia de entrada que ya hemos almacenado aquí
input ref which we've already stored right here I
3:47:01
supongo que vamos a copiar allí y ahora déjame colocar eso aquí
guess we are going to be copying there and now let me just place that right here and
3:47:05
el marcador de posición que dirá como hacer clic
I'm going to also provide the placeholder which will say like click
3:47:08
el botón para enfocar o
the button to focus or
3:47:12
sí, supongo que eso estará bien y ahora debajo de eso vamos a crear un botón que dirá como enfocar entrada y también voy a adjuntar el onClickEventHandler y vamos a crear esta función en unos segundos.
yeah I guess that's going to be fine and now underneath that we're going to be creating a button which will say like focus input and I'm going to also attach the onClickEventHandler and we are going to be creating this function in a few seconds.
3:47:23
Así que ahora déjame crear esta función. ConsFocusInput y dentro de esta función primero vamos a verificar si tenemos el inputRep.currentValue.
So now let me just create this function. ConsFocusInput and inside this function first of all we are going to be checking if we have the inputRep.currentValue.
3:47:33
Así que en esta situación vamos a tomar ese inputRep y vamos a obtener la propiedad actual de allí y luego vamos a llamar al método focus en eso.
So in this situation we are going to be taking that inputRep and we are going to be grabbing the current property of there and then we are going to be calling the focus method on that.
3:47:42
Así que cada vez que hacemos clic en ese botón va a enfocar nuestro campo de entrada. Así que ahora déjame mostrarte eso.
So anytime we click on that button it's going to focus our input field. So now let me just show you that.
3:47:46
Así que ahora si hago clic en eso va a enfocar este campo de entrada aquí. Así que esa fue la primera parte de este desafío.
So now if I click on that it's going to focus this input field right here. So that was the first portion of this challenge.
3:47:53
Voy a cerrar allí y ahora déjame crear mi temporizador. Así que timer.jsx.rafce y ahora también tenemos que almacenar allí o registrar allí dentro de nuestra aplicación.
I'm going to close there and now let me create my timer. So timer.jsx.rafce and now we have to also store there or register there inside our app.
3:48:04
Así que solo escribiré como temporizador y presionaré enter. Así que va a obtener eso de mi archivo de temporizador.
So I'll just write like timer and hit enter. So it's going to grab there from my timer file.
3:48:10
Así que lo que voy a hacer es que voy a obtener algunas cosas. La primera cosa que obtendré es el use rep de React.js.
So what I'm going to do is that I'm going to grab a few things. The first thing I will grab is the use rep from the React.js.
3:48:15
También necesitaríamos el use effect y también el use state. Bien, así que ahora usemos todos esos hooks dentro de nuestro componente.
We would also need the use effect and also the use state. Okay so now let's just use all of that hooks inside our component.
3:48:22
Así que primero crearé mi contador y también estableceré el contador y eso vendrá del use state y el valor inicial se establecerá en cero.
So I'll just first of all create my count and also set count and that's going to be coming from the use state and the initial value will be set to zero.
3:48:30
También vamos a crear nuestra referencia de intervalo así que solo escribiré
We're going to be also creating our interval ref so I'll just write
3:48:33
como referencia de intervalo y eso será igual a la
like interval ref and that's going to be equals to the
3:48:36
use ref y el valor inicial se establecerá en ahora y ahora usemos eso dentro de nuestro componente pero primero también tenemos que crear nuestro temporizador para que podamos trabajar con esto.
use ref and the initial value will be set to now and now let's just use the inside of our component but first of all we also have to create our timer so that we can work with this.
3:48:46
Vamos a usar nuestro use effect porque en este caso vamos a trabajar con un efecto secundario y para el array de dependencias lo estableceremos en un array de dependencias vacío.
We are going to be using our use effect because in this case we are going to be working with a side effect and for the dependency array we are going to be setting that to empty dependency array.
3:48:54
Ahora voy a obtener mi valor de intervalo o intervalo
Now I'm going to get my interval value or interval
3:48:58
ref y aquí solo estamos interesados en el actual
ref and here we are only interested in the current
3:49:01
propiedad así que voy a obtener mi actual CURRENT así y eso será igual al método incorporado de JavaScript que se llama setInterval y aquí vamos a pasar una función de callback
property so I'm going to grab my current CURRENT like so and that's going to be equals to the JavaScript built-in method which is called the setInterval and here we are going to be passing a callback function
3:49:12
y también le daré como un segundo estaría bien para
and I'm going to also give it like one second would be fine for
3:49:15
un temporizador y voy a escribir como establecer contador y aquí
a timer and I'm going to write like set count and here
3:49:19
tenemos que especificar nuestro contador anterior y también tenemos que
we have to specify our previous count and also we
3:49:22
agregar uno al dos o contador anterior así y
have to add one to the two or previous count like so and
3:49:25
eso va a ser todo y finalmente también voy a escribir como la
that's going to be it and finally I'm going to also write like the
3:49:28
función de limpieza así que voy a devolver esa función de limpieza aquí mismo, así que vamos a usar como clear interval y aquí tenemos que especificar nuestra referencia de intervalo una vez más y tenemos que proporcionar esa propiedad actual allí.
cleanup function so I'm going to just return that cleanup function right here so we're going to be using like clear interval and here we have to specify our interval ref one more time and we we have to provide that current property in there.
3:49:41
Está bien, así que ahora hemos terminado completamente con todo ese valor. A continuación, tenemos que usar el interior de nuestros componentes.
Okay, so now we are totally done with all of that value. Next, we have to use the inside of our components.
3:49:45
Así que voy a quitarlos y escribiré mi temporizador H1. Y aquí tenemos que renderizar nuestro conteo y luego los segundos.
So I'm gonna remove them and I'll write my H1 timer. And here we have render our count and then seconds.
3:49:52
Y ahora debajo de eso, también vamos a crear un botón que simplemente dirá como detener el temporizador.
And now underneath that, we're going to be also creating a button which will just say like stop timer.
3:49:57
Está bien, así que nos va a permitir detener nuestro temporizador como
Okay, so it's gonna allow us to stop our timer like
3:50:00
un botón de pausa y cada vez que hacemos clic en esto, ¿qué
a pause button and whenever we click on this what
3:50:04
quieres hacer? Solo queremos ejecutar esta función que será un intervalo borrado
do you want to do we just want to fire this function which will be a cleared interval
3:50:07
y aquí tenemos que especificar nuestra referencia de intervalo y
and here we have to specify our interval ref and
3:50:10
luego el valor actual allí. Ahora déjame guardar mi archivo y aquí puedes ver que ahora estamos obteniendo como su temporizador. Déjame refrescar, uno, dos y así sucesivamente, ahora estamos obteniendo nuestro contador.
then dot current value in there now let me just save my file and here you can see we're now getting like their timer let me just refresh there one two and so on and so forth we are now getting our counter
3:50:22
o temporizador, no contador, que está funcionando totalmente bien
or timer not counter which is working totally fine
3:50:25
y ahora si quisiera detenerlo o pausarlo, puedo
and now if i wanted to stop there or pause there i can
3:50:28
hacer clic en el botón de detener temporizador, así que va a pausar mi temporizador aquí mismo
click on the stop timer so it's going to pause my timer right here
3:50:31
está bien, así que sí, esa fue la segunda parte de nuestro
okay so yeah that was the second portion of our
3:50:34
reto y eso fue sobre el uso del reto
challenge and that was about the use rough challenge
3:50:38
ahora hablemos sobre los hooks personalizados, así que los hooks personalizados son
now let's talk about the custom hooks so custom hooks are
3:50:41
funciones de javascript que comienzan con el prefijo usar
a javascript functions it starts with the prefix use
3:50:44
por ejemplo, usar fetch, usar form y así sucesivamente, y pueden llamar a otros hooks dentro de ellos, permiten extraer y reutilizar lógica que involucra estado o efectos secundarios, haciendo que tus componentes sean más legibles y mantenibles.
for example use fetch use form and so on and so forth and can call other hooks within them they allow you to extract and reuse logic that involves state or side effect making your components more readable and maintainable.
3:50:56
Así que aquí puedes ver que tengo un componente de inicio y ahora dentro de este componente de inicio estoy obteniendo los datos de las tareas y luego estoy enviando esos datos a mi estado.
So here you can see I have a home component and now inside this home component I am now fetching the data from the to-dos and then I'm sending that data to my state.
3:51:05
Está bien, así que esto está bien, como que no hay nada malo en este componente, pero ahora podemos extraer toda esa lógica en nuestro propio hook para que podamos reutilizar ese hook una y otra vez y ya no tengamos que escribir todo ese código una y otra vez.
Okay so this is okay like nothing is wrong in this component but now we can extract all of that logic into our own hook so that we can reuse that hook again and again and we no longer have to write all of that code again and again.
3:51:17
Así que para hacer eso, primero vamos a crear una función. Le daré el nombre de usarFetch.
So to do that first of all we are going to be creating a function. I will give it the name of like useFetch.
3:51:22
Y va a tomar la URL y luego vamos a definir nuestro estado para eso. Y luego usaremos nuestro useEffect.
And it's going to take the URL and then we're going to be defining our state for that. And then we will use our useEffect.
3:51:27
Y ahora dentro de este useEffect, vamos a usar nuestro fetch.
And now inside this useEffect, we're going to be using our fetch.
3:51:31
Luego vamos a tomar esa URL del perímetro y vamos a pasar eso al fetch. Luego podemos convertir esos datos a JSON.
Then we are going to be taking that URL from the perimeter and we're going to be passing that to the fetch. Then we can convert that data to the JSON.
3:51:38
Y finalmente, podemos enviar esos datos a setData. Está bien. Así es como se verá la sintaxis.
And finally, we can push that data to the setData. Okay. So this is how the syntax will look like.
3:51:43
Como este es solo un ejemplo básico, pero a lo largo del curso, vamos a ver mucho más
Like this is just a basic example, but throughout the course, we're going to be seeing a lot more
3:51:47
que allí, así que ahora para usar ese hook dentro de nuestro componente
than there so now to use that hook inside our component this
3:51:50
así es como lo vamos a hacer. Primero que nada, vamos a importar
is how we are going to be doing there first of all we are going to be importing
3:51:53
nuestro hook y luego vamos a pasar la URL de la que queremos
our hook and then we are going to be passing the url from which we want
3:51:56
obtener nuestros datos y luego podemos simplemente desestructurar los datos y podemos
to fetch our data and then we can just destructure the data and we
3:51:59
usar el dentro de nuestro componente. Así es como se verá el uso
can use the inside our component so this is how the use
3:52:02
fetch y ahora déjame mostrarte todo eso en acción. Primero
fetch will look like and now let me show you all of that in action first
3:52:05
quiero mostrarte el problema y luego te voy a mostrar cómo podemos refactorizar nuestro código para usar el hook personalizado. Así que voy a crear, primero que nada, mi
of all i want to show you the problem and then i'm going to show you how we can refactor our code to use the custom hook okay so i'm going to just create like first of all my
3:52:14
estado. Solo escribiré como const data y luego set
state i'll just write like const data and then set
3:52:17
data y eso va a venir de la
data and that's going to be coming from the
3:52:20
uso de estado y el inicial realmente se establecerá en no. Puedes
use state and the initial really will be set to no you can
3:52:23
escribir como un array si quisieras, pero en mi caso voy a escribir como no. A continuación
write like array if you wanted to but in my case i'm going to write like no next
3:52:27
tenemos que obtener nuestros datos y para obtener nuestros datos vamos a usar esto
we have to fetch our data and to fetch our data we are going to be using this
3:52:30
uso de efecto para los efectos secundarios y va a tomar
use effect for the side effects and it's going to take
3:52:33
el array de dependencias de un array totalmente vacío porque solo queremos
the dependency array of totally empty array because we only want
3:52:36
renderizar este contenido una vez y luego solo usaré como fetch
to render this content once and then i will just use like fetch
3:52:39
método aquí y voy a proporcionar esta URL de la que vamos a estar obteniendo
method right here and i'm going to provide this url we are going to be fetching
3:52:43
nuestros datos de esta URL. Ahora déjame usar mi then y
our data from this url now let me just use my then and
3:52:46
va a tomar la respuesta y vamos a convertir esa respuesta
it's going to take the response and we are going to be converting that response
3:52:49
a json y también solo usemos nuestro then una vez más
to json and also let's just use our then one more
3:52:52
para obtener los datos y solo voy a usar como
time to get the data and i'm going to just use like
3:52:55
uh set data y vamos a pasar nuestros datos a
uh set data and we're going to be passing our data to
3:52:58
ahí. Así que así es como vamos a estar obteniendo nuestros datos y esto
there okay so this is how we are going to be fetching our data and this
3:53:01
es cómo vamos a estar empujando nuestros datos a nuestro estado. Ahora dentro
is how we are going to be pushing our data to our state now inside
3:53:05
de este div, solo vamos a renderizar nuestro contenido, así que solo usaré como si tenemos los datos, entonces vamos a iterar sobre los datos, así que solo usaré como item o hacer sería bien.
this div we're going to be just rendering our content so i'll just use like if we have the data then we are going to be iterating over through the data so I'll just use like item or to do would be fine.
3:53:14
Voy a usar mi tarea o sabes qué elemento sería qué
I'll use my to do or do you know what item would be what
3:53:18
el infierno y voy a usar mis llaves de llave y ahora tenemos que devolver
the hell and I'm going to use my curly braces and now we have to return
3:53:21
este párrafo y solo usaré como item punto título y también voy a proporcionar la palabra clave aquí y la clave será item punto id justo aquí.
this paragraph and I will just use like item dot title and I'm going to also provide the keyword here and the key will be item dot id right here.
3:53:30
Así que si guardo mi archivo, como puedes ver aquí, estamos obteniendo todos sus títulos, lo cual está funcionando totalmente bien, pero ahora supongamos que quieres usar esta misma
So if I save my file as you can see right here we are getting all of their title which is working totally fine but now let's suppose if you want to use this same
3:53:39
lógica en muchos componentes, así que primero que nada vamos a tener que
logic in a lot of components so first of all we are going to have to
3:53:42
crear este estado en todos esos componentes, luego tenemos que
create this this state in all of that component then we
3:53:45
usar este efecto en todos esos componentes, luego tenemos que obtener
have to use this use effect in all of that component then we have to fetch
3:53:48
nuestros datos, cambiar eso a json y finalmente tenemos que empujar
our data change that to json and finally we have to push
3:53:51
estos datos a nuestras estadísticas y eso es mucho trabajo
this data to our stats and that's a lot of work
3:53:54
y ahora para extraer toda esa funcionalidad a una sola función
and now to extract all of that functionality to a single function
3:53:57
así es como vamos a hacer allí, así que solo voy a crear un archivo
this is how we are going to be doing there so i'll just create a file
3:54:00
le voy a dar el nombre de como usar porque estamos creando un gancho, así que solo le daré el nombre de como use fetch.jsx está bien y ahora
i'm going to give it the name of like use because we are creating a hook so i'll just give it the name of like use fetch.jsx okay and now
3:54:07
dentro de este use fetch.jsx y ahora dentro de este use
inside this use fetch.jsx and now inside this use
3:54:10
método fetch, voy a importar primero mi use
fetch method I'm going to just first of all import my use
3:54:14
estado porque ya sabemos que vamos a
state because we already know that we are going to
3:54:17
estar usando algún tipo de estado y también importaremos el use
be using some sort of a state and we will also import the use
3:54:20
efecto también porque ya sabemos que vamos a estar usando este use
effect as well because we already know that we are going to be using this use
3:54:24
efecto también, así que ahora que hemos importado con éxito, lo siguiente que tenemos que hacer es que solo tenemos que crear nuestra función, así que crearé como cons y puedes básicamente darle
effect as well okay so now that we successfully imported there the next thing that we have to do is that we have to just create our function so I'll create like cons and you can basically give
3:54:32
cualquier nombre que te guste, pero la convención es usar el use
it any name that you like but the convention is to use the use
3:54:36
está bien y luego puedes darle como básicamente cualquier
okay and then you can give it like basically any
3:54:39
nombre que te guste, así que solo le daré el nombre de como use fetch y va a
name that you like so i'll just give it the name of like use fetch and it's
3:54:42
tomar la url porque como puedes ver aquí, vamos
going to take the url because as you can see right here we
3:54:45
a proporcionar algún tipo de url, así que va a tomar esa url
are going to be providing some sort of a url so it's going to take that url
3:54:48
justo aquí y ahora vamos a crear lo que una función, así que lo
right here and now let's just create what a function so the
3:54:51
primero que quiero hacer es que quiero crear mis datos y luego establecer datos
first thing that i want to do is that i want to create my data and then set data
3:54:54
y ahora vamos a almacenar allí dentro
and now we are going to be storing there inside
3:54:57
el hilo de uso y el valor inicial se establecerá en no está bien
the use thread and the initial value will be set to no okay
3:55:01
así que esa es la primera cosa, a continuación tenemos que crear exactamente
so that's the first thing next we have to create exactly
3:55:04
el mismo efecto de uso como este, así que voy a copiar
the same use effect like this so i'm going to copy
3:55:07
allí y ahora déjame colocarlo justo aquí y en lugar de proporcionar todo
there and now let me just place it right here and instead of providing all of
3:55:10
esta url, voy a cortar eso de aquí, voy a copiar esta url como un perímetro y vamos a pasar eso a la búsqueda, finalmente solo tenemos que devolver nuestros datos para que podamos usar eso en otro componente.
this url i'm going to cut that from here i'm going to copy this url as a perimeter and we're going to be passing that to the fetch finally we just have to return our data so that we can use that in other component.
3:55:21
Así que usaré como datos justo aquí y así es como vamos a crear nuestro hook personalizado.
So I'll use like data right here and this is how we are going to be creating our custom hook.
3:55:26
Así que finalmente tendré que exportar eso para que pueda usarlo en otro componente.
So finally I'm going to have to export that so that I can use that in other component.
3:55:30
Así que usaré mi uso de búsqueda y ahora voy a guardar mi archivo y ahora tenemos que usar este uso de búsqueda dentro de nuestro componente de aplicación justo aquí.
So I'll use my use fetch and now I'm going to save my file and now we have to use this use fetch inside or app component right here.
3:55:38
Así que voy a eliminar todo eso de aquí. También voy a eliminar este. También voy a eliminar eso.
So I'm going to remove all of that from here. I'm going to also remove this one. I'm going to also remove that.
3:55:43
Guarda mi archivo y aquí puedes ver cómo se verá nuestro componente, pero primero tenemos que usar este uso de búsqueda dentro de este
Save my file and here you can see this is how our component will look like but first of all we have to use this use fetch inside this
3:55:49
componente y así es como vamos a usar, primero tenemos que
component and this is how we are going to be using the first of all we
3:55:52
importar el uso de búsqueda y ahora tenemos que
have to import the the use fetch and now we
3:55:55
usar todos como uso de búsqueda y toma
have to use the all use like use fetch and it takes
3:55:58
ese perímetro de url justo aquí, así que tenemos que
that perimeter of url right here so we have to
3:56:02
proporcionar esa url justo aquí, ahora está proporcionando estos datos
provide that url right here it is now providing this data
3:56:05
como un array, así que podemos desestructurarlo totalmente como
as array so we can totally destructure that as
3:56:08
nuestro array, así que solo usaré como datos y así es como
our array so i'll just use like data and this is how we
3:56:11
vamos a desestructurar nuestros datos justo aquí, así que ahora si tienes
are going to be destructuring our data right here so now if you have
3:56:14
los datos, entonces vamos a iterar a través de todos sus datos
the data then we are going to be iterating all through all of their data
3:56:17
y vamos a tomar el id, vamos a proporcionar
and we are going to be taking the id we are going to be providing
3:56:20
eso como clave y también vamos a tomar el título y
the as a key and we are going to be also taking the title and
3:56:24
vamos a proporcionar eso como valor jsx, así que si guardo
we are going to be providing the as or jsx value so if i save
3:56:27
mi archivo y aquí puedes ver que ahora estamos obteniendo exactamente el mismo resultado, ¿verdad?
my file and here you can see we are now getting exactly the same result right
3:56:30
aquí, lo cual es increíble y ahora puedes obtener tus datos
here which is amazing and now you can fetch your data
3:56:33
usando este gancho en todos tus componentes si lo
by using this hook in all of your component if you
3:56:36
tienes algún tipo de otro componente, puedes cambiar totalmente esta URL si quisieras y puedes crear un gancho personalizado para el formulario y para la validación y para todo como
have some sort of other component you can totally change this url if you wanted to and you can create a custom hook for the form and for the validation and for everything like
3:56:45
básicamente para todo puedes crear un gancho personalizado, ahora hablemos del
basically for everything you can create a custom hook now let's talk about the
3:56:48
gancho de id, así que el gancho de id en reactjs es
use id hook so the use id hook in reactjs is
3:56:51
utilizado para generar un id único para un componente, así que
used to generate a unique id for a component so
3:56:55
sí, es tan simple como eso, así que ahora vamos a entrar en
yeah it is as simple as that so now let's get into
3:56:58
la codificación y luego sabrás de qué estoy hablando, así que lo primero
the coding and then you will get to know what i'm talking about so the first
3:57:01
que quiero hacer es crear una carpeta de componentes y dentro
thing that i want to do is that i want to create a components folder and inside
3:57:04
de allí tenemos que crear un unique id dot jsx, usaré mi rfc dentro de allí y registraré mi componente dentro
there we have to create a unique id dot jsx i'll use my rfc inside there and register my component inside
3:57:11
de la aplicación como unique id y cerrar, prueba esto y aquí puedes ver que tenemos nuestro unique id que se ve genial, así que lo primero que queremos hacer es importar
the app like unique id and close there test this out and here you can see we have our unique id which is looking cool so the first thing that we want to do is that we want to import
3:57:21
ese unique id, así que usaré como uh use id y
that unique id so i'll use like uh use id and
3:57:25
presiona enter, así que se va a importar eso desde el react chase y ahora tenemos
hit enter so it's going to import that from the react chase and now we have
3:57:28
que usar esto, así que usaré como use id y llamaré a eso y no toma ningún parámetro, nada, ahora que tenemos que almacenar en algún tipo de variable, así que almacenaré dentro
to use this so i'll use like use id and call that and it doesn't take any perimeter nothing now that we have to store in some sort of a variable so i'll store the inside
3:57:37
como id, va a ser igual a este user id, así que
like id it's going to be equals to this user id so
3:57:40
lo que voy a hacer es que voy a definir mi etiqueta primero de
what i'm going to do is that i'm going to define my label first of
3:57:43
todo como etiqueta y ahora para esta etiqueta
all like label and now for this label
3:57:46
queremos proporcionar nuestro id, así que vamos a usar ese id
we want to provide our id so we're going to be using that id
3:57:50
totalmente de manera dinámica y ahora voy a escribir como email y
totally dynamically and now i'm going to just write like email and
3:57:53
también voy a crear mi campo de entrada, en este campo de entrada tendrá el tipo
also i'm going to create my input field in this input field will have the type
3:57:56
de email, también vamos a proporcionar el id y el id se establecerá una vez más, lo adivinaste, ese id, está bien, así que ahora si yo
of email we're going to be also providing the id and the id will be set to once again you guessed it that id okay so now if i
3:58:04
guardo mi archivo y pruebo esto, así que ahora déjame ir y acceder a mi
save my file and test this out so now let me go ahead and go to my
3:58:07
inspeccionar elemento y veamos, déjame
inspect element and go to let me
3:58:10
simplemente hacer clic en este y aquí puedes ver que nos va a dar eso
just click on this one and here you can see it's going to give us that
3:58:13
id único justo aquí para el html4 y
unique id right here for the html4 and
3:58:16
también nos va a dar ese id único para este id específico
it's going to also give us that unique id for this specific id
3:58:19
atributo bien, así que eso también está hecho, pero ahora supongamos que quieres crear otro campo de entrada, así que solo escribiré, primero que nada, la etiqueta o, ya sabes, déjame copiar toda esta cosa de allí
attribute okay so that's also done but now let's suppose if you want to create another input field so i'll just write like first of all the label or you know let me just copy this entire thing from there
3:58:30
y colócala aquí y cámbiala a algún tipo
and place it right here and change there to some sort
3:58:33
de no sé, contraseña o algo así, voy
of I don't know password or something like that I'm
3:58:37
a cambiar eso a contraseña y luego observa lo que sucede, así que si guardo mi archivo y actualizo allí, aquí puedes ver que este tiene el id de r1, pero ahora si selecciono esta contraseña
going to also change there to password and then watch what happens so if I save my file and refresh there and here you can see this one have the id of r1 but now if I select this password
3:58:47
también va a tener ese id de r1, ¿por qué no son totalmente únicos? Así que ahora sé que mucha gente pensará que si quieres hacerlos únicos, solo tenemos que duplicar eso
it's going to also have that id of r1 why is that they are not totally unique so now I know a lot of people will think that if you want to make the unique so we have to just duplicate there
3:58:58
y cambiar eso a como id2 y luego especificar eso
and change that to like id2 and then specify that
3:59:01
id2 allí, así que voy a copiar eso y colocarlo aquí y
id2 there so i'm going to copy there and place there here and
3:59:04
también colócalo aquí, así que mi archivo y ahora si selecciono el
also place there here so my file and now if i select the
3:59:07
contraseña aquí, puedes ver que este tiene el id de r1 y
password here you can see this one have the id of r1 and
3:59:10
este tiene el id de r5, pero ahora la pregunta es
this one have the id of r5 but now the question is
3:59:14
¿debo duplicar mi código para cada entrada?
should i duplicate my code for every single input
3:59:17
no, por supuesto que no, esta no es la mejor manera, así que voy a eliminar eso de aquí, en su lugar podemos proporcionar un prefijo, así que solo escribiré un guion y luego puedo
no of course not this is not the better way so i'm going to remove that from here instead we can provide a prefix so i'll just write a dash and then i can
3:59:25
escribir lo que quiera escribir, puedo escribir como correo electrónico, así que
write like whatever I want to write I can write like email so
3:59:28
solo escribiré un correo electrónico aquí, también proporcionaré el correo electrónico aquí
I'll just write an email here I'll also provide the email here
3:59:32
y ahora para este vamos a proporcionar una contraseña y
and now for this one we're going to be providing a password and
3:59:35
también para este vamos a proporcionar una contraseña una vez
also for this one we're going to be providing a password once
3:59:39
más, ahora déjame guardar mi archivo, no estás obteniendo nada que sea
again now let me just save my file you're not getting anything that's
3:59:42
porque estamos usando el id también, así que tenemos que cambiar eso a solo id
because we are using the id too so we have to change that to just id
3:59:45
y id, así que ahora si guardo mi archivo y aquí puedes ver, si hago clic en la contraseña, aquí puedes ver que ahora estás prefijando eso para el correo electrónico y también para la contraseña.
and id so now if I save my file and here you can see if I click on the password so here you can you are now prefixing there for the email and also for the password.
3:59:55
Así que ahora déjame ir y ir a mi aplicación. Solo crearé un párrafo que tendrá un lorem
So now let me go ahead and go to my app. I'll just create a paragraph which will have a lorem
4:00:00
debajo de este párrafo vamos a llamar a nuestro componente una vez más. Ahora solo cerremos esto.
underneath this paragraph we are going to be calling our component once again. Now let's just close this.
4:00:04
Así que si cierro allí y guardo mi archivo y ahora si hago clic en este componente, ahora aquí puedes ver que este componente tiene el RF.
So if I close there and save my file and now if I click on this component so now here you can see this component have the RF.
4:00:12
Déjame mostrarte allí. Este componente tiene el ID único de RF y este componente tiene el ID único de RH justo aquí.
Let me just show you there. This component have the unique ID of RF and this component have the unique ID of RH right here.
4:00:19
Eso fue solo un gancho rápido que quería cubrir. Bien, así que es hora de los 10 proyectos de nivel principiante.
That was just a quick hook which I want to cover. Okay so time for the 10 beginners level projects.
4:00:25
Así que en estos proyectos no vamos a usar ningún tipo de script
So in these projects we are not going to be using any type script
4:00:28
así que solo vamos a usar reactjs con javascript
so we are going to be only using reactjs with javascript
4:00:31
así que básicamente eso va a estar ahí, así que lo que voy a hacer es que voy
so basically that's going to be there so what i'm going to do is that i'm
4:00:34
a hacer una configuración para ello aquí, voy a abrir mi terminal y dejar
going to just make a setup for it here i'm going to open my terminal and let
4:00:37
que me acerque un poco para que ustedes puedan ver todo un poco mejor, voy a usar
me just zoom in a bit so you guys can see everything a bit better i'm going to use
4:00:40
npm create read at latest, obtendré el
npm create read at latest i'll get the
4:00:43
nombre de como demos de proyecto o sí, supongo que eso va a estar bien, voy a elegir react js y también javascript, no typescript, sino javascript, voy a entrar en mi demo de proyectos
name of like project demos or yeah i guess that's going to be fine i'm going to choose react js and also javascript not typescript but javascript i'm going to go into my projects demo
4:00:55
y usaré como npm i para instalar todas las dependencias que eso
and i'll use like npm i to install all of the dependencies that's
4:00:58
está hecho, así que voy a abrir mi vs code aquí, también voy a
done so i'm going to open my vs code right here i'm going to also
4:01:01
abrir mi terminal y usar npm run dev para
open my terminal and use npm run dev to
4:01:04
iniciar mi servidor aquí y simplemente vamos a eliminar este boilerplate
start my server right here and let's just remove this boilerplate
4:01:08
así que voy a eliminar esta carpeta pública, voy a eliminar los assets
so i'm going to remove this public folder i'm going to remove the assets
4:01:11
también este app.css y index.css
also this app.css and index.css
4:01:15
también vamos a eliminar cada cosa de allí, voy a usar mi rafce dentro de allí y también eliminar este index.css y no, también voy a eliminar el modo estricto para ello aquí.
as well let's just remove every single thing from there i'm going to use my rafce inside there and also remove this index.css and you don't I'm going to also remove the strict mode for it here.
4:01:25
Enviar mi archivo. Y ahora así es como se ve todo. Primero que nada, déjame mostrarte eso. Y aquí puedes ver que ahora estamos obteniendo nuestra app, que se ve increíble.
Send my file. And now this is how everything looks like. First of all, let me just show you that. And here you can see we are now getting our app, which is looking amazing.
4:01:33
Está bien, así que es hora de construir nuestro primer proyecto. Así que voy a crear mi carpeta con el nombre de componentes. Y dentro de allí, vamos a crear nuestro counter.jsx.
Okay, so time to build our first project. So I'm going to create my folder with the name of components. And inside there, we are going to be creating our counter.jsx.
4:01:41
Y simplemente vamos a usar nuestro RAFCE. Enviar mi archivo. Y usar ese contador aquí. Está bien, así que voy a usar mi contador. Presiona enter.
And let's just use our RAFCE. Send my file. And use that counter right here. Okay, so I'm going to be using my counter. Hit enter.
4:01:48
Enviar mi archivo. Y así es como se ve nuestro contador aquí.
Send my file. And this is how our counter looks like right here.
4:01:52
y ahora empecemos a importar muchas cosas, así que estoy
and now let's begin with importing a lot of stuff so i'm
4:01:55
voy a importar primero el use thread, como obviamente necesitaríamos
going to be importing first of all the use thread like obviously we would
4:01:58
algún tipo de hilo y también vamos a importar el style.css
need some sort of a thread and also we are going to be importing the style.css
4:02:03
que supongo que no creé, así que ahora déjame crear allí mismo
which i guess i did not create so now let me create there right
4:02:06
aquí dentro de esta carpeta src, así que voy a crear como style.css
here inside this src folder so i'm going to create like style.css
4:02:09
y voy a colocar todo el css que ya he escrito
and i'm going to place all of the css that i have already written
4:02:12
para este proyecto aquí, así que básicamente no vamos a hacer nada loco, pero solo vamos a centrar cada cosa y sí, entiendes la idea, así que si quieres
for this project right here so basically we're not going to do anything crazy but we are going to be just centering every single thing and yeah you get the idea so if you want to
4:02:21
obtener todos estos estilos, puedes ir totalmente y visitar mi repositorio de github y
get all of these styling you can totally go ahead and go to my github repository and
4:02:25
puedes obtener todo su estilo desde allí así que ahora lo primero que quiero
you can get all of their styling from there so now the first thing that i want
4:02:28
hacer es que quiero hacer una configuración de estado así que voy a usar como contador y
to do is that i want to make a state setup so i'm going to use like count and
4:02:31
luego establecer el contador y ahora simplemente usemos nuestro use state y
then set count and now let's just use our use state and
4:02:34
el valor inicial se establecerá en cero está bien así que ahora voy a guardar mi
the initial value will be set to zero okay so now i'm going to save my
4:02:37
archivo y lo siguiente que quiero hacer es que quiero mejorar un poco esta interfaz de usuario así que proporcionaré un nombre de clase a este div una clase contenedora está bien así que dentro de ahí vamos a crear nuestro h1 que será solo
file and the next thing that i want to do is that i want to make uh this ui a bit better so i'll provide a class name to this dev a container class okay so inside there we're going to be creating our h1 which will be just
4:02:50
también voy a proporcionar un nombre de clase allá arriba para como un número y también
I'm going to also provide a class name up there to like a number and also
4:02:53
aquí vamos a estar renderizando nuestro contador así que si solo uso
here we are going to be rendering our count so if I just use
4:02:56
esto guarda mi archivo aquí puedes ver que ahora estamos obteniendo más cero justo aquí
this save my file here you can see we are now getting more zero right here
4:02:59
lo cual se ve increíble y sabes qué primero déjame incluso
which is looking amazing and you know what first of all let me just even
4:03:02
envolver en algo así y el
wrap in something like so and the
4:03:05
siguiente cosa que quiero hacer es que quiero crear mi contenedor de botones
next thing that I want to do is that I want to create my buttons container
4:03:08
como el botón de incrementar y también el botón de decrementar así que
like the increment button and also the decrement button so
4:03:11
usaré como contenedor de botones este va a ser mi nombre de clase y ahora dentro de este contenedor de botones voy a estar
I'll use like buttons container this is going to be my class name and now inside this buttons container I'm going to be
4:03:19
creando dos botones uno será para incrementar y otro
creating two buttons one will be for the increment and another
4:03:22
será para decrementar así que este será para el más y
one will be for the decrement so this one will be for the plus and
4:03:25
este será para el menos así que usaré como decrementar
this one will be for the minus so i'll use like decrement
4:03:28
ahí vamos y ahora si guardo mi archivo y estoy
there we go and now if i save my file and i'm
4:03:32
voy a tener que copiar el estilo de incremento y colocar esto guarda mi archivo y ahora se ven mejor así que lo siguiente que quiero hacer es que quiero duplicar
gonna have to copy the increment styling and place this save my file and now they are looking better so the next thing that i want to do is that i want to duplicate
4:03:39
ahí y voy a estar usando el manejador de eventos on click en
there and i'm going to be using the on click event handler on
4:03:42
ambos así que para el primero cuando alguien haga clic ahí vamos a estar disparando la función de incrementar y cuando alguien haga clic así que en el segundo botón, como el botón de decrementar, vamos a estar disparando la función de decrementar.
both of them so for the first one when somebody clicks on there we are going to be firing the increment function and when somebody clicks So on the second button, like the decrement button, we're going to be firing the decrement function.
4:03:53
Así que ahora simplemente registremos esta función aquí dentro de nuestro componente.
So now let's just register this function right here inside our component.
4:03:57
Así que lo primero que quiero hacer es que quiero crear esta función como cons incrementar.
So the first thing that I want to do is that I want to create this function like cons increment.
4:04:01
Y ahora aquí vamos a estar usando como set count y el valor del contador será solo más uno. Como esta va a ser la función de incrementar.
And now here we're going to be using like set count and the count value will be just plus one. Like this is going to be the increment function.
4:04:09
Y lo siguiente que tenemos que hacer es que tenemos que cambiar eso a decrementar y también cambiar eso a menos. Así que usaré como decrementar.
And the next thing that we have to do is that we have to change that to decrement and also change that to minus. So I'll use like decrement.
4:04:15
y si guardo mi archivo y si hago clic en este botón de más
and if i save my file and if i click on this plus button
4:04:18
va a incrementar mi contador y si hago clic
it's going to increment my counter and if i click
4:04:21
en este botón de decrementar, va a decrementar mi contador así que
on this decrement button it's going to decrement my counter so
4:04:24
sí, ese fue nuestro primer proyecto más simple
yeah that was our first simplest project
4:04:27
el próximo proyecto que vamos a construir será una
ever the next project that we are going to be building will be a
4:04:30
aplicación de lista de tareas, así que solo usaré como to do.jsx y voy a usar mi rfc dentro de ahí y también voy a ir a mi hoja de estilos y eliminar todo de allí y reemplazar
to-do list application so i'll just use like to do.jsx and i'm going to use my rfc inside there and i'm going to also go ahead and go to my style sheet and remove every single thing from there and replace
4:04:41
el estilo aquí. Si te importa el estilo, puedes ir a mi repositorio de GitHub y obtener todo ese estilo de allí.
the styling right here. If you care about the styling, you can go ahead and go to my GitHub repository and grab all of that styling from there.
4:04:49
Ahora voy a guardar mi archivo y ahora tenemos que registrar este componente aquí dentro de nuestro componente de aplicación.
Now I'm going to save my file and now we have to register this component right here inside our app component.
4:04:54
Usaré como to do y ahora si presiono enter, así es como vamos a registrar esto aquí.
I'll use like to do and now if I hit enter, this is how we are going to be registering this here.
4:05:01
Está bien, así que si solo actualizo allí y aquí puedes ver que ahora estamos obteniendo todas las tareas, lo cual se ve increíble.
Okay, so if I just refresh there and here you can see we are now getting all to do which is looking amazing.
4:05:05
Así que ahora dentro de esta tarea, lo primero que quiero hacer es que quiero obtener mi use stat.
So now inside this to do the first thing that I want to do is that I want to grab my use stat.
4:05:10
Vamos a importar use stat y también necesitaremos proporcionar nuestra hoja de estilos.
Come on import use stat and we will also need to provide our style sheet.
4:05:14
Así que usaré como punto punto y proporcionaré nuestro style.css aquí dentro. A continuación, tenemos que crear dos estados.
So I'll use like dot dot and provide our style dot css right here inside there. Next we have to create two stat.
4:05:20
Uno será para las tareas y otro será para la entrada. Así que usaré como const to dos.
One will be for the to do's and another one will be for the input. So I'll use like const to dos.
4:05:28
Vamos, to dos y luego set to dos. Y eso va a ser igual a use state.
Come on, to dos and then set to dos. And that's going to be equals to the use state.
4:05:33
Y vamos a poner el valor inicial de un array vacío allí. Porque aquí vamos a almacenar todas nuestras tareas.
And we're going to be putting the initial value of empty array inside there. Because here we're going to be storing all of our to dos.
4:05:40
A continuación, tenemos que crear nuestro campo de entrada. Así que usaré como input y también set input.
Next, we have to create our input field. So I'll use like input and also set input.
4:05:45
Aquí vamos a obtener todos los datos de nuestro campo de entrada. Y vamos a almacenar allí dentro de nuestro use state.
Here we're going to be grabbing like all of the data from our input field. And we're going to be storing there inside our use state.
4:05:51
Y el valor inicial se establecerá en una cadena vacía. Ahora voy a eliminar esta tarea de aquí y también voy a proporcionar el nombre de clase de contenedor hoy.
And the initial value will be set to empty string. Now I'll remove this to do from here and I'm going to also provide the class name of container today.
4:05:58
Y ahora dentro de este contenedor, primero vamos a crear nuestro campo de entrada y el tipo se establecerá en texto.
And now inside this container, first of all, we are going to be creating our input field and the type will be set to text.
4:06:03
También voy a proporcionar un marcador de posición que dirá como nueva tarea o escribe nueva tarea, lo que quieras llamar allí.
I'm going to also provide a placeholder which will say like new to do or type new to do, whatever you want to call there.
4:06:09
También proporcionaré el valor y el valor vendrá de este campo de entrada aquí. Así que vamos a copiar allí y lo voy a colocar aquí.
I'll also provide the value and the value will be coming from this input field right here. So we're going to be copying there and I'm going to place it right here.
4:06:17
y cuando alguien cambie o cuando alguien escriba algo dentro
and when somebody change or when somebody types something inside
4:06:21
de este campo de entrada, así que vamos a activar esta función y vamos a cambiar el valor de eso, vamos a obtener todos los valores de target.value y vamos a establecer eso en nuestro campo de entrada
this input field so we are going to be firing this function and we are going to be changing the value of that we are going to be getting all of the value from the target dot value and we are going to be setting that to our input field
4:06:32
está bien, así que ahora déjame mostrarte cómo se ve eso, así que aquí puedes ver que tenemos nuestro
okay so now let me show you how that looks like so here you can see we have our
4:06:35
campo de entrada aquí y puedo escribir básicamente cualquier cosa que quiera, así que este es nuestro campo de entrada básico, lo siguiente que quiero hacer es crear un botón
input field right here and i can type like basically anything i want so this is our basic input field the next thing that i want to do is that i want to create a button
4:06:43
que nos permitirá enviar o hacer. Así que usaré un botón que dirá enviar.
which will allow us to submit or to do So I'll use like button which will say submit.
4:06:48
Y cuando alguien haga clic en este botón, vamos a activar esta función que es una función de manejo de envío.
And when somebody clicks on this button, we're going to be firing this function which is a handle submit function.
4:06:53
Voy a copiar eso y ahora vamos a crear eso aquí mismo. Voy a usar const manejar envío.
I'm going to copy that and now let's just create that right here. I'm going to use cons handle submit.
4:06:58
Y aquí dentro, vamos a usar el conjunto de tareas. Y para el conjunto de tareas, vamos a proporcionar nuestras tareas.
And here inside there, we're going to be using the set to do's. And for the set to do's, we're going to be providing our to do's.
4:07:05
Y ahora, como función de devolución de llamada, vamos a usar las tareas, ese perímetro que ahora estamos tomando para esta función.
And now as a callback function, we're going to be using the to do's, that perimeter which we're now taking for this function.
4:07:11
Y vamos a usar el método concat allí. y aquí
And we're going to be using the concat method on there. and here
4:07:14
tenemos que especificar estos valores como texto y texto
we have to specify these values like text and text
4:07:17
será igual a este campo de entrada como cualquier cosa que queramos escribir
will be equals to this input field like anything we want to type anything
4:07:20
lo que el usuario escribe dentro de este campo de entrada se establecerá en la propiedad de texto y también tenemos el id y básicamente no vamos a hacer nada loco, pero solo registraré un id aleatorio aquí usando math.floor.
the user type inside this input field that's going to be set to the text property and also we have the id and basically we're not going to be doing anything crazy but I'll just register a random id right here by using math.floor.
4:07:32
También puedes usar el uuid si quisieras, pero en mi caso solo voy a usar math.floor y también math.random por 10.
You can also use the uuid if you wanted to but in my case I'm going to just use like math.floor and also math.random times 10.
4:07:39
Vamos a usar nuestro por 10 y así es como podemos configurar nuestro manejo
Let's just use our times 10 and this is how we can set up our handle
4:07:43
enviar, también voy a limpiar el campo de entrada, así que
submit i'm going to also clear out the input field okay so
4:07:46
usaré como establecer entrada y aquí tenemos que proporcionar o
i'll use like set input and here we have to provide or
4:07:49
cadena vacía aquí, así que ahora puedo escribir algo
empty string right here okay so now i can type something
4:07:52
si quisiera, pero no puedo ver allí mismo y
if i wanted to but i cannot see there right here and
4:07:55
¿por qué es eso? Eso es porque no renderizamos todo nuestro contenido
why is that that's because we did not render all of our content
4:07:58
en nuestra interfaz de usuario, así que si hago clic en eso, aquí puedes ver que el campo de entrada ahora se ha eliminado con éxito, pero sí, no podemos ver los datos y ahora si quieres ver
to our ui so if i click on that here you can see that input field is now successfully removed but yeah we cannot see the data and now if you want to see
4:08:07
esos datos, así que debajo de este botón vamos a crear
that data so underneath this button we are going to be creating
4:08:10
nuestra ul y esta ul tendrá la clase de como
our ul and this ul will have the class of like
4:08:13
lista de tareas y ahora dentro de esta lista de tareas vamos a estar iterando
to do's list and now inside this to do's list we are going to be iterating
4:08:16
sobre todas las tareas, así que usaré el método map allí
over through all of the to do's okay so i'll use the map method on there
4:08:19
y aquí vamos a pasar nuestro texto y también el id
and here we are going to be passing our text and also id
4:08:23
que vamos a desestructurar de todo eso a
which we are going to be destructuring from all of that to
4:08:26
tareas, como puedes ver aquí tenemos un texto y también ese id que
do's like as you can see right here we have a text and also that id which
4:08:29
vamos a desestructurar de esta función y vamos a usar el interior, así que usaré como uh allí y
we are going to be destructuring from this function and we are going to be using the inside okay so i'll use like uh there and
4:08:36
dentro de ahí vamos a estar usando nuestro li y aquí dentro
inside there we are going to be using our li and here inside
4:08:39
este li específico le voy a proporcionar un nombre de clase de
this specific li i'm going to provide a class name of to
4:08:42
hacer hoy y también la clave se establecerá en esa id
do today and also the key will be set to that id
4:08:45
que ya está generado aleatoriamente por
which is already randomly generated by
4:08:48
usando este mat.floor y también este mat.random está bien
using this mat.floor and also this mat.random okay
4:08:51
así que vamos a estar especificando allí para esta clave y
so we are going to be specifying there for this key and
4:08:55
también dentro de este li vamos a estar creando nuestro span y
also inside this li we are going to be creating our span and
4:08:58
este span tomará nuestro texto así que vamos a estar renderizando nuestro texto dentro de este span y también tendremos un
this span will take our text so we are going to be rendering our text inside this span and we will also have a
4:09:04
botón que solo dirá x o eliminar lo que tú
button which will only say x or remove whatever you
4:09:07
quieras llamar ahí ahora déjame estilizar este botón proporcionando un nombre de clase
want to call there now let me style this button by providing a class name
4:09:11
de cerrar ahí y también voy a proporcionar el evento on click
of close to there and i'm going to also provide the on click event
4:09:14
manejador cuando alguien haga clic en este botón así que
handler when somebody clicks on this button so
4:09:17
vamos a estar simplemente ejecutando esta función que es eliminar para hacer y
we're going to be just firing this function which is a remove to do and
4:09:20
vamos a estar especificando la id allí está bien así que ahora déjame crear
we're going to be specifying id to there okay so now let me just create
4:09:23
esta eliminación de hacer aquí mismo así que arriba debajo de este manejar
this remove to do right here so up above underneath this handle
4:09:26
enviar también vamos a estar creando lo que eliminar para hacer así que lo que voy a hacer es que voy a usar como eliminar para hacer y va a
submit we're going to be also creating what remove to do so what i'm going to do is that i'm going to use like remove to do and it's going to
4:09:33
tomar la id y ahora aquí vamos a estar pasando el conjunto
take the id and now here we are going to be passing the set
4:09:36
de hacer aquí y ese conjunto de hacer tomará eso como un perímetro y vamos a estar iterando sobre
to do's right here and that set to do's will take that to
4:09:39
eso de hacer usando el filtro y luego simplemente proporcionaremos un
do's as a perimeter and we are going to be iterating over through
4:09:42
t para un hacer específico y luego podemos obtener el t.id
that to do's by using the filter and then we will just provide a
4:09:45
y si ese t.id no es igual a
t for a specific to do and then we can grab the t.id
4:09:49
y si ese t.id no es igual a
and if that t.id does not equal to
4:09:52
ese id así que vamos a eliminar solo ese específico para hacer está bien déjame decirlo una vez más ahora estamos iterando sobre todos los
that id so we are going to be removing only that specific to do okay let me just say that once again we are now iterating over through all of
4:10:00
los quehaceres usando este método de filtro ahora estamos filtrando todos
the to do's by using this filter method we are now filtering out all
4:10:03
los quehaceres y si ese t como ese específico
of the to do's and if that t like that specific
4:10:06
t id no es igual a ese id que
t id is not equal to that id which
4:10:09
estamos tomando como un perímetro de esta función, así que en esta situación
we are taking as a perimeter from this function so in this situation
4:10:12
vamos a eliminar esa tarea específica, está bien, así que ahora
we are going to be removing that specific to do okay so now
4:10:15
la funcionalidad está totalmente terminada, voy a continuar y solo agregar algunas tareas como, eh, pasear al perro y si hago clic en enviar, está bien, todo ha desaparecido.
the functionality is totally done i'm gonna go ahead and just add a few to do like uh walk the dog and And if I click on the submit, okay, everything is now gone.
4:10:26
supongo que hice algo mal. Y me di cuenta de que olvidé incluir la declaración de retorno justo aquí. Así que solo tenemos que escribir un retorno.
I guess I did something wrong. And I realized that I forgot to include the return statement right here. So we only have to write a return.
4:10:33
Y ahora, si guardo mi archivo, y solo vamos a refrescar eso. Y voy a escribir como pasear.perro y hacer clic en el botón de enviar. Así que se va a agregar eso aquí mismo.
And now if I save my file, and let's just refresh that. And I'm going to just write like walk.dog and click on the submit button. So it's going to add that right here.
4:10:40
Entonces puedo escribir como, no sé, grabar curso de react.js y enviar.
Then I can write like, I don't know, record react.js course submit.
4:10:48
Y ahora puedo eliminar eso completamente haciendo clic en estos íconos. aquí
And now I can totally remove that by clicking on these icons. here
4:10:51
y puedo eliminar eso completamente si quisiera, está bien
and i can totally remove that if i wanted to okay
4:10:54
así que sí, esa fue nuestra lista de tareas usando react.js
so yeah that was our to-do list by using react.js
4:10:58
bienvenido al proyecto número tres y en este proyecto vamos
welcome to the project number three and in this project we
4:11:01
a usar el efecto use para obtener nuestros datos de las comidas
are going to be using the use effect to fetch our data from the meals
4:11:04
api de db, está bien, así que voy a continuar y crear mi meals.dot
db api okay so i'm going to go ahead and create my meals dot
4:11:08
jsx y voy a usar mi rfce
jsx and i'm going to use my rfce
4:11:11
archivo semi y registrarlo aquí mismo, está bien, así que usaré mis meals y archivo semi, además voy a continuar e ir a mi hoja de estilo y eliminar cada cosa de allí y colocar este nuevo estilo aquí.
semi file and register there right here okay so i'll use my meals and semi file plus i'm going to also go ahead and go to my style sheet and remove every single thing from there and place this new styling right here.
4:11:23
Una vez más, por última vez, si te importa este estilo, puedes ir a mi repositorio de GitHub y obtener todo el estilo de allí.
Once again, for the final time, if you care about this styling, you can totally go ahead and go to my GitHub repository and grab all of the styling from there.
4:11:31
No voy a decir eso más. Está bien, así que lo que voy a hacer es que primero voy a importar muchas cosas, pero también olvidé decirte que en este proyecto no vamos a usar la API fetch.
I'm not going to say that anymore. Okay, so what I'm going to do is that I'm going to first of all import a lot of things, but I also forgot to tell you that in this project, we are not going to be using the fetch API.
4:11:41
Vamos a usar la biblioteca Axios para obtener tus datos.
We're going to be using the Axios library to fetch your data.
4:11:45
Así que si ustedes no saben qué es Axios, no tienen que preocuparse
So if you guys don't know what Axios is, you don't even have to worry
4:11:48
por eso, pero si ya sabes qué es axios, así que sí
about that but if you already know what axios is so yeah
4:11:51
felicitaciones, vamos a usar como npm i y
congratulations we are going to be using like npm i and
4:11:54
luego axios para instalarlo en nuestra máquina, aquí está, se puede instalar
then axios to install the in our machine here's nice can install
4:11:57
la siguiente cosa que quiero hacer es que quiero agarrar allí, así que estoy
it the next thing that i want to do is that i want to grab there so i'm
4:12:00
voy a usar como import axios from axios y
going to use like import axios from axios and
4:12:04
también necesitaríamos el use state y también el use effect
we would also need the use state and also the use effect
4:12:07
para proporcionar nuestro efecto secundario y obtener nuestros datos, también voy a proporcionar mi, uh, ¿cómo lo llamamos?, mi hoja de estilo aquí, así que tenemos un start.css y ahora si guardo mi archivo, aquí puedes ver que ahora estamos obteniendo nuestras comidas, lo cual se ve increíble.
to provide our side effect and fetch our data i'm going to also provide my uh what do we call it my style sheet right here so we have a start.css and now if I save my file and here you can see we are now getting our meals which is looking amazing.
4:12:19
Lo primero que quiero hacer es que quiero hacer un inicio en el que vamos a almacenar todos nuestros elementos o nuestras comidas.
The first thing that I want to do is that I want to make a start in which we are going to be storing all of our items or our meals.
4:12:24
Así que usaré elementos, puedes darle el nombre de comidas si quieres, pero en mi caso solo le voy a dar el nombre de elementos y luego establecer elementos.
So I'll use like items you can give it the name of like meals if you wanted to but in my case I'm going to only give it the name of like items and then set items.
4:12:33
Eso va a ser igual a el uso de start y eso va a ser igual al arreglo vacío porque aquí vamos a almacenar todas nuestras comidas y ahora
That's going to be equals to the use start and that's going to be equals to the empty array because here we are going to be storing all of our meals and now
4:12:40
Así que debajo de eso vamos a usar el useEffect y aquí simplemente proporcionemos nuestra función de callback hoy y también nuestro arreglo de dependencias vacío aquí.
So underneath that we are going to be using the useEffect and here let's just provide our callback function today and also our empty dependency array right here.
4:12:49
Ahora voy a usar Axios y para este Axios tenemos un método get y este método get nos permite obtener nuestros datos o buscar nuestros datos de algún tipo de URL.
Now I'm going to be using Axios and for this Axios we have a get method and this get method allows us to get our data or to fetch our data from some sort of a URL.
4:12:59
Así que la URL que es mealDB.com barra API luego JSON virtual uno uno filter.php pregunta C es igual a mariscos.
So URL which is the mealDB.com forward slash API then JSON virtual one one filter.php question mark C is equal to seafood.
4:13:07
Vamos a estar obteniendo nuestros datos de esta API. ahora
We're going to be grabbing our data from this API. now
4:13:10
También voy a usar eso, entonces, está bien, así que solo proporcionaré
I'm going to also use that then okay so I'll just provide
4:13:13
un entonces aquí y para este entonces vamos a proporcionar nuestro res
a then right here and for this then we are going to be providing our res
4:13:16
y ahora dentro de este res, primero que nada, solo voy a registrar esto
and now inside this res first of all I'm going to just log this
4:13:19
res en la consola, así que usaré como res.data y luego .mils
res to the console so I'll use like res.data and then .mils
4:13:23
así que ahora si guardo mi archivo y déjame mostrarte todo eso si
so now if I save my file and let me show you all of that if
4:13:26
abro mi consola aquí y dentro de esta consola
I open my console right here and inside this console
4:13:30
tenemos todos esos datos que ahora estamos obteniendo de ese mildb, está bien, así que tenemos nuestro id, también tenemos la comida estrella y también tenemos esta miniatura que puedo copiar allí y colocar aquí
we have like all of that data which we are now fetching from that mildb okay so we have our id we also have the star mil and we also have this thumbnail I can copy there and place there here
4:13:40
y presionar enter y ahora aquí puedes ver que ahora estamos obteniendo la imagen de la comida y
and hit enter and now here you can see we're now getting the meal image and
4:13:43
así sucesivamente, así que sí, así es como vamos a estar obteniendo nuestros
so on and so forth so yeah this is how we are going to be fetching our
4:13:46
datos, pero ahora, uh, déjame solo enviar
data but now uh let me just send
4:13:49
estos datos a estos elementos aquí, así que voy a comentar esta
this data to these items right here so i'm going to comment this
4:13:53
línea y voy a estar usando como set items y voy a
line out and i'm going to be using like set items and i'm
4:13:56
usar como res.data.mails, así que así es como estamos
going to use like res.data.mails so this is how we are
4:13:59
enviando nuestros datos a nuestro estado y ahora también voy a proporcionar una declaración catch, como en algunas situaciones obtendremos algún tipo de error, así que no queremos hacer nada loco con ese error, así que solo usaré como console.log de ese error.
going to be sending our data to our state and now i'm going to also provide a catch statement like in some situation we will get some sort of error so then we don't want to do anything crazy with that error so i'll just use like console.log off that error.
4:14:11
Está bien, así que eso va a ser para nuestra declaración catch. Así que así es como vamos a estar obteniendo nuestros datos. Está bien, así que ahora la obtención de nuestros datos está hecha.
Okay so that's going to be for our catch statement. So this is how we are going to be fetching our data. Okay so now fetching our data is done.
4:14:17
Lo siguiente que tenemos que hacer es que tenemos que renderizar sus datos y
The next thing that we have to do is that we have to render their data and
4:14:20
para hacer eso voy a eliminar estas comidas de aquí y voy a proporcionar una clase
to do that I'm going to remove these mails from here and I'm going to provide a class
4:14:24
nombre del contenedor de elementos que ya configuré dentro de mi hoja de estilos y aquí vamos a proporcionar una función que será la lista de elementos y nos permitirá renderizar todos esos elementos en nuestro DOM.
name of items container which I already set up inside my style sheet and here we're going to be providing a function which will be items list and it's going to allow us to render all of that items to our DOM.
4:14:35
Así que usaré como const lista de elementos y eso será igual a items.map porque quieres iterar sobre todos esos elementos que ya hemos agregado o comenzado.
So I'll use like cons items list and that's going to be equal to items.map because you want to iterate over through all of that items which we already pushed to or started.
4:14:45
De acuerdo, así que primero queremos iterar sobre todos esos elementos y aquí tenemos que desestructurar todas sus propiedades que vas a usar en este proyecto.
Okay so first of all we want to iterate over through all of that items and here we have to destructure all of their properties which you are going to be using in this project.
4:14:52
Así que usaré como comida salteada y también miniatura de comida salteada y también el id de esa comida específica.
So I'll use like stir meal and also stir meal thumb and also the id of that specific meal.
4:14:59
Ahora, fuera de ahí, lo que quiero hacer es simplemente
Now outside from there what I want to do I want to just
4:15:02
usar mi declaración de retorno y dentro de ahí voy a usar un
use my return statement and inside there I'm going to be using a
4:15:06
sección con un nombre, no un nombre, sino con una clase de tarjeta
section with a name not a name but with a class of card
4:15:09
y ahora dentro de esta sección vamos a usar nuestra imagen y
and now inside this section we're going to be using our image and
4:15:12
para esta fuente vamos a proporcionar nuestra comida salteada
for this source we're going to be providing our stir meal
4:15:15
miniatura, de acuerdo, que será la imagen de nuestra comida, de acuerdo, y ahora para este texto alternativo puedo simplemente escribir como mi comida salteada, no importa
thumb okay which will be the image of our meal okay and now for this alternative text I can just write like my stir meal it doesn't
4:15:24
realmente y ahora debajo de esta imagen podemos crear nuestra sección
really matter and now underneath this image we can create our section
4:15:27
y voy a proporcionar una clase de contenido hoy y ahora dentro
and i'm going to provide a class of content today and now inside
4:15:30
de esta sección vamos a crear nuestro párrafo que será una
this section we're going to be creating our paragraph which will be a
4:15:33
comida salteada y también proporcionaremos otro párrafo
stir meal and we will also provide another paragraph
4:15:36
con un símbolo de libra, ni siquiera tienes que hacer eso, eso es
with a pound symbol you don't even have to do that that's
4:15:40
solo para una etiqueta y simplemente renderizaremos nuestro id de comida aquí, vamos, id de comida, ahí vamos, y ahora si guardo mi archivo y aquí puedes ver que ahora estamos obteniendo nuestra imagen
just for a label and we will just render our id meal right here come on id meal there we go and now if i save my file and here you can see we are now getting our image
4:15:50
también nuestro título y también ese id específico, así que
also our title and also that specific id so
4:15:53
si solo elimino ese símbolo de libra aquí, déjame solo
if i just remove that pound symbol right here let me just
4:15:56
eliminar ese archivo semicolon y aquí puedes ver que ya no estamos obteniendo
remove that semi file and here you can see we are no longer getting
4:15:59
ese símbolo de libra y este símbolo de libra es solo para la etiqueta
that pound symbol and this pound symbol is just for the label
4:16:02
o lo que quieras llamarlo, de acuerdo, así que esto
or whatever you want to call it okay so this
4:16:05
es cómo vamos a obtener nuestros datos y así es como vamos a
is how we are going to be fetching our data and this is how we are going to
4:16:08
renderizar esos datos usando el efecto de uso y también la biblioteca axios, a continuación vamos a construir una calculadora, así que
be rendering that data by using the use effect and also the axios library next we are going to be building a calculator so
4:16:15
simplemente crea un archivo calculator.jnsx y yo
just create a calculator.jnsx file and i'm
4:16:18
voy a usar mi archivo semicolon rafce y registrar esa calculadora
going to be using my rafce semi file and register that calculator
4:16:22
aquí bien, así que primero tenemos que importar
right here okay so first of all we have to import
4:16:25
que también voy a ir a mi hoja de estilos y eliminar
that i'm going to also go ahead and go to my style sheet and remove
4:16:28
cada cosa de allí y colocar mis nuevos estilos aquí
every single thing from there and place my new styles right here
4:16:32
bien, así que ahora voy a entrar en mi calculadora y lo primero que quiero hacer es que quiero obtener mi estado usado porque obviamente necesitamos algún tipo de estado, también
okay so now i'm going to go into my calculator and the first thing that i want to do is that i want to grab my used state because obviously we would need some sort of a state we will also
4:16:41
importar nuestro style.css semi
import our style.css semi
4:16:44
archivo y ahora dentro de esta calculadora vamos a
file and now inside this calculator we're going to
4:16:48
estar usando nuestra constante y valor de entrada y luego
be using our const and input value and then
4:16:51
establecer el valor de entrada y eso va a ser igual a
set input value and that's going to be equals to
4:16:54
lo que inicias y el valor inicial será solo una cadena vacía, ahora voy a ir a mi jsx y proporcionar un formulario aquí, también voy a eliminar este div y proporcionar nuestro formulario allí
what you start and the initial value will be just empty string now i'm going to go ahead and go to my jsx and provide a form right here i'm going to also remove this div and provide our form there
4:17:05
y ahora dentro de esta calculadora, primero que nada, también voy a proporcionar una clase de
and now inside this calculator first of all i'm going to also provide a class of
4:17:08
calculadora, así que c-i-l-c-u-l-a-t-o-r
calculator to so c-i-l-c-u-l-a-t-o-r
4:17:11
y también voy a proporcionar el nombre de cal que podría ser
and I'm going to also provide the name of cal could be
4:17:14
bien y ahora dentro de allí vamos a estar creando nuestro campo de entrada
fine and now inside there we are going to be creating our input field
4:17:18
con una clase de valor y para el valor vamos
with a class of value and for the value we
4:17:21
a estar proporcionando nuestro valor de entrada aquí, ahora
are going to be providing our input value right here now
4:17:24
debajo de eso vamos a estar creando muchos spans, así que voy a ir
underneath there we are going to be creating a lot of span so I'm going to go
4:17:27
de regreso y vamos a crear nuestro span con una clase de o
back and let's just create our span with a class of or
4:17:31
sabes qué, sí, proporcionaremos un num y también la clase clear y aquí solo tenemos que especificar nuestro
you know what yeah we will provide a num and also the clear class and here we just have to specify our
4:17:37
ver aquí para el clear y cuando alguien haga clic en eso
see right here for the clear and when somebody clicks on that
4:17:40
vamos a activar esta función clear, bien, así que
we're going to be firing this clear function okay so
4:17:43
vamos a crear esta función clear de inmediato, ahora debajo de este hilo
let's just create this clear function right away now underneath this thread
4:17:46
vamos a estar creando nuestra función clear que
we're going to be creating our clear function which will
4:17:49
simplemente nos permite limpiar nuestro campo de entrada, bien
just allows us to clear out our input field okay
4:17:53
así que solo vamos a proporcionar nuestro hilo vacío dentro de allí y ahora debajo
so we're going to be only providing our empty thread inside there and now underneath
4:17:56
de este span vamos a estar creando muchos más spans, así que
this span we're going to be creating a lot more spans so
4:17:59
lo que voy a hacer es que voy a crear un span y sí, aquí solo tenemos que proporcionar una barra diagonal y yo
what i'm going to do is that i'm going to just create a span and yeah here we just have to provide as forward slash and i'm
4:18:06
voy a duplicar eso como muchas veces, está bien, solo vamos a eliminar
going to just duplicate there like a lot of time okay let's just remove
4:18:09
el y cambiar eso por el asterisco y siete entonces
the and change that to the star and seven then
4:18:12
ocho nueve menos cuatro cinco
eight nine minus four five
4:18:16
seis y luego más voy a
six and then plus i'm going
4:18:19
también proporcionar el controlador de eventos on click en ellos, así que cuando alguien haga clic en cada uno de ellos, van a activar algo llamado la función de visualización que vamos a crear en unos segundos
to also provide the on click event handler on them so when somebody clicks on each of them they're going to be firing the something called the display function which we're going to be creating in a few seconds
4:18:29
va a tomar algún tipo de perímetro de símbolos, así que voy a copiar todos sus símbolos y voy a proporcionar eso como un valor de cadena aquí.
it's going to take some sort of a perimeter of symbols so i'm going to copy all of their symbols and I'm going to provide that as a string value right here.
4:18:36
Además, este será uno especial. Así que vamos a usar como un nombre de clase y voy a proporcionar un nombre de clase de más para ello.
Plus, this will be a special one. So we're going to be using like a class name and I'm going to provide a class name of plus to it.
4:18:43
Ahora debajo de eso, vamos a estar creando una vez más muchos spans. Así que solo usaré como un span de tiempo.
Now underneath there, we're going to be once again creating a lot of spans. So I'll just use like a span time.
4:18:49
Está bien, así que si solo presiono tab, ahora tendré que guardar eso.
Okay, so if I just hit tab, now I'm going to have to save that.
4:18:52
Ahora voy a usar como uno, dos, luego tres, luego cero, cero, cero, luego punto.
Now I'm going to use like one, two, then three, then zero, zero, zero, then dot.
4:18:58
Y también, vamos, solo un punto. Y también tenemos que proporcionar lo que es igual a signo.
And also, come on, just a dot. And we also have to provide what equal to sign.
4:19:02
Voy a proporcionar mi selección de múltiples cursores aquí y voy a usar mi propio controlador de eventos de clic como cuando alguien hace clic allí.
I'm going to provide my multi cursor selection right here and I'm going to use my own click event handler like when somebody clicks on there.
4:19:09
Vamos a activar esta función de visualización que vamos a crear en unos segundos. Y aquí tenemos que proporcionar todos esos valores aquí.
We're going to be firing this display function which we're going to be creating in a few seconds. And here we have to provide all of that values right here.
4:19:16
Voy a copiar allí y proporcionar allí como un valor de cadena.
I'm going to copy there and provide there as a string value.
4:19:20
Y para este último que es igual, así que voy a proporcionar un nombre de clase de allí que se establecerá en num y también igual aquí.
And for this final one which is equal, so I'm going to provide a class name of there which will be set to num and also equal right here.
4:19:28
Así que ahora aquí para este no vamos a usar una visualización. Voy a poner una función de calcular aquí, que dirá como c-i-l-c-u-l-a-t-e
So now here for this one we're not going to be using a display. I'm going to put a calculate function right here, which will say like c-i-l-c-u-l-a-t-e
4:19:36
y eliminar toda esa ejecución de aquí. Pero sabes qué, tenemos que ejecutar eso.
and remove all of that execution from here. But you know what, we have to execute that.
4:19:40
Ahora tengo que crear dos funciones, una será para la visualización y una será para el cálculo.
Now I have to create two functions, one will be for the display and one will be for the calculate.
4:19:44
Así que para esta función de visualización, no vamos a hacer nada loco. Así que déjame crear eso aquí. Vamos a usar como visualización.
So for this display function, we are not going to be doing anything crazy. So let me just create that right here. We are going to be using like display.
4:19:52
Solo nos permitirá mostrar nuestro valor. Así que tomará algún tipo de valor, que ya estamos especificando aquí, como todos estos valores.
It's going to just allow us to display our value. So it's going to take some sort of a value, which we are already specifying right here, like all of these values.
4:20:00
Así que tomará algún tipo de valor y luego lo que queremos hacer con ese valor es que queremos usar nuestro valor de entrada establecido.
So it's going to take some sort of a value and then what we want to do with that value is that we want to use our set input value.
4:20:06
Y aquí tenemos que proporcionar nuestro valor de entrada de nuestro estado.
And here we have to provide our input value from our state.
4:20:10
Y también tenemos que combinar o agregar ese valor de perímetro a ello.
And also we have to just combine or add that perimeter value of value to it.
4:20:15
Así que nos permitirá renderizar todos esos datos. Y aquí puedes ver cómo se ve. Puedo escribir cualquier tipo de dato aquí.
So it's going to allow us to like render all of that data. And here you can see this is how it looks like. I can type any kind of data right here.
4:20:21
Y ahora la última cosa que quiero hacer es proporcionar una función de cálculo. Así que solo nos permitirá calcular nuestro valor.
And now the final thing that I want to do is that I want to just provide a calculate function. So it's going to just allow us to calculate our value.
4:20:29
Ahora debajo de eso, vamos a crear otra función para calcular.
Now underneath that, we're going to be creating yet another function for calculate.
4:20:33
No va a tomar ningún perímetro, pero vamos a usar el valor de entrada establecido.
It's not going to take any perimeter, but we are going to be using the set input value.
4:20:37
Y aquí tenemos que especificar el método o función eval, que voy a mostrar en unos segundos.
And here we have to specify the eval method or function, which I'm going to show in a few seconds.
4:20:42
Y dentro de este eval, vamos a proporcionar nuestro valor de entrada aquí. Así que ahora, si guardo mi archivo, y ahora déjame probar esto.
And inside this eval, we're going to be providing our input value right here. So now if I save my file, and now let me just test this out.
4:20:49
Así que si solo proporciono como 2 más 2, y si uso este signo igual aquí, nos dará 4.
So if I just provide like 2 plus 2, and if I use this equal to sign right here, it's going to give us 4.
4:20:54
y ahora si solo lo pongo como 5 más no sé, tal vez 10, así que nos dará 15 y también puedo usar como 2 menos 1, así que nos dará 1
and now if I just put it like 5 plus I don't know maybe 10 so it's going to give us 15 and I can also use like 2 minus 1 so it's going to give us 1
4:21:06
y también puedo usar como 2 por 2
and I can also use like 2 times 2
4:21:09
nos dará 4, 2 por 2, ahí vamos, nos dará 4 y ahora puedo usar como 5 dividido entre, o sabes qué, no 5, sino 6 dividido entre 2
it's going to give us 4 2 times 2 there we go it's going to give us 4 and now I can use like 5 divided by or you know what not 5 but 6 divided by 2
4:21:21
nos dará 3. Así que significa que todo está funcionando dentro de nuestra calculadora, pero ¿cómo está funcionando?
is going to give us 3. So which means like everything is working inside our calculator but how is it working?
4:21:27
Está funcionando gracias a esta función eval o método eval, como quieras llamarlo, y voy a ir a mi método eval de JavaScript y este es un método un poco aterrador.
It is working because of this eval function or eval method whatever you want to call that and I'm going to go ahead and go to my JavaScript eval method and this is a bit scary method.
4:21:39
Así que aquí puedes ver que tenemos dos variables, como x e y. x tiene el valor de 10 y y tiene el valor de 20 y también tenemos otra variable que tomará un texto
So here you can see we have two variables like x and y. x is holding the value of 10 and y is holding the value of 20 and we also have another variable which will take a text
4:21:48
y aquí puedes ver que ahora estamos proporcionando ese x e y como
and here you can see we are now providing that x and y as
4:21:52
un valor de cadena y ahora nos dará el resultado de eso, ¿de acuerdo?
a string value and now it's going to give us the result of that okay
4:21:55
así que si voy y pruebo esto y como puedes ver aquí
so if i go ahead and try this out and as you can see right here
4:21:58
ahora estamos obteniendo 200 y sabes qué, déjame mostrarte eso
we are now getting 200 and you know what let me just show you that
4:22:01
si solo copio todo eso, ven
if i just copy all of that come
4:22:05
oh, maldita sea, oh Dios mío, ahora no me está permitiendo copiar eso, déjame copiar eso
on i'm gonna god damn it god oh my god it is now it is not allowing me to copy that let me just copy that
4:22:13
y abrir mi consola aquí, y ejecutar ese código aquí, así que solo refresquemos, limpiemos esto, y tenemos, maldita sea, primero tenemos que escribir como, permitir pegar,
and open my console right here, and run that code right here, so let's just refresh there, clear this out, and we have, god damn it, we have to first of all write like, allow pasting,
4:22:25
y ahora puedo proporcionar como, todo su texto aquí, limpiar
and now I can just provide like, all of their text right here, clear
4:22:28
esto, aquí puedes ver, tenemos nuestra variable x,
this out, here you can see, we have our x variable,
4:22:31
y variable y, y luego estamos proporcionando un x por y,
and y variable, and then we are providing a x times y,
4:22:34
y ahora estamos usando el método eval, y luego estamos proporcionando nuestro valor de texto, que es como, x por y, y ahora puedo
and now we are using the eval method, and then we are providing our text value, which is like, x times y, and now I can
4:22:41
simplemente usar como resultado aquí, así que si solo uso como resultado y
just use like result right here so if i just use like result and
4:22:44
regresar y presionar enter, así que ahora nos dará el resultado de su
go back and hit enter so now it's going to give us the result of their
4:22:47
valor de cadena ten en cuenta siempre que estés usando
string value keep in mind whenever you are using
4:22:50
ellos mantén esta declaración en mente ejecutando
them keep this statement in mind executing
4:22:54
javascript desde una cadena es un gran riesgo de seguridad como tú
javascript from a string is a big security risk like you
4:22:58
no se te permite usar este método eval en la producción
are not allowed to use this eval method in the production
4:23:01
aplicaciones listas las estamos usando porque solo estamos trabajando con una simple aplicación de calculadora, pero no se te permite usar
ready apps we are using them because we are only working with just a simple simple calculator app but you are not allowed to use
4:23:08
este método de evento en un proyecto más grande especialmente si estás trabajando
this event method on a bigger project especially if you are working
4:23:12
con algún tipo de empresa o con alguien más, está bien
with some sort of a company or with someone else okay
4:23:15
así que ten eso en mente, así es como funcionó nuestra calculadora
so keep that in mind so this is how our calculator worked
4:23:18
aquí es el momento para el quinto proyecto, así que ahora en este
right here time for the fifth project so now in this
4:23:21
proyecto vamos a construir un color de fondo alternante, así que solo vamos a crear esto, así que usaré como t audible g l e toggle background color dot jnsx
project we're going to be building a toggle background color so let's just create this so i'll use like t audible g l e toggle background color dot jnsx
4:23:31
y dentro de eso voy a estar usando mi rafce y déjame ir a mi hoja de estilo
and inside that i'm going to be using my rafce and let me just go ahead and go to my style sheet
4:23:36
mover cada cosa de allí y proporcionar mi estilo aquí
move every single thing from there and provide my style right here
4:23:39
está bien, así que solo estamos seleccionando el cuerpo y la sección, también estamos
okay so we are just selecting the body and section we are also
4:23:42
comenzando el botón y también el h1, está bien, así que eso va a ser
starting the button and also the h1 okay so that's going to be
4:23:45
muy divertido y ahora dentro de esta función alternante
a lot of fun and now inside this toggle function
4:23:48
primero que todo no tendrás que registrarte aquí, así que usaré como
first of all you won't have to register there right here so i'll use like
4:23:51
toggle background colored semi file y tenemos
toggle background colored semi file and we
4:23:54
que agarrar lo que comenzó primero, así que usaré como imports use state, tenemos que importar eso de react.js y también tenemos que importar nuestro style.css dentro de allí.
have to grab what started first of all so i'll use like imports use state we have to import that from the react.js and we also have to import our style.css inside there.
4:24:05
Primero que todo, voy a estar creando tres estados. Así que usaré como color de fondo y luego set background color y eso va a ser igual al estado usado y vamos a proporcionar el valor inicial de blanco allí.
First of all, I'm going to be creating three states. So I'll use like background color and then set background color and that's going to be equals to the used state and we're going to be providing the initial value of white to there.
4:24:18
Ahora también voy a crear otro para el color del texto y establecer el color del texto aquí.
Now I'm going to also create another one for the text color and set text color right here.
4:24:24
Eso va a ser igual al estado usado y para el valor inicial, vamos a proporcionar como 1B, 1B, 1B.
That's going to be equals to the used state and for the initial value, we're going to be providing like 1B, 1B, 1B.
4:24:30
una especie de color grisáceo y también vamos a proporcionar un color para
kind of a grayish color and we're going to be also providing a color for
4:24:33
el estilo del botón también, así que podemos usar como set button style
the button style as well so we can use like set button style
4:24:37
y ahora tenemos que proporcionar el valor inicial de totalmente
and now we have to provide the initial value of totally
4:24:40
blanco para eso, está bien, así que ahora que hemos creado exitosamente nuestro estado
white to that okay so now that we successfully created our state
4:24:43
lo siguiente que hemos producido es que tenemos que usar eso dentro de nuestra interfaz de usuario, así que solo lo quitaré de aquí y proporcionaré mi estilo justo aquí, así que usaré como estilo y para este estilo vamos a usar el color de fondo
the next thing that we have produced is we have to use that inside our ui so i'll just remove that from here and provide my style right here so i'll use like style and for this style we're going to be using the background color
4:24:56
vamos a poner nuestro color de fondo y su color de fondo será igual a ese color que ya hemos configurado dentro de nuestro estado.
come on let's just put our background color and their background color will be equals to that color which we've already set up inside our stat.
4:25:03
A continuación, vamos a proporcionar un color y ese color ahora será igual a este color de texto.
Next, we're going to be providing a color and that color will be now equal to this text color.
4:25:09
Así que vamos a copiar eso y ahora déjame colocarlo justo aquí y ahora dentro de ahí vamos a crear nuestro botón que nos permite alternar nuestras clases o colores, para ser precisos.
So we're going to be copying that and now let me just place it right here and now inside there we're going to be creating our button which allows us to toggle our classes or colors to be precise.
4:25:18
Así que cuando alguien haga clic en este botón, vamos a activar la función de manejo de clic que vamos a crear en unos segundos
So when somebody clicks on this button, we are going to be firing the handle click function which we are going to be creating in a few seconds
4:25:25
pero ahora déjame proporcionar un estilo para eso. Así que para el estilo vamos a
but now let me provide a styling to that. So for the style we are going to
4:25:29
proporcionar un estilo de botón que ahora proviene de este estado
be providing a button style which is now coming from this state
4:25:32
parte aquí y también vamos a proporcionar un color que también se establecerá en el color de texto y también vamos a proporcionar un borde y aquí vamos a usar el ternario.
part here and we are going to be also providing a color which will be also set to the text color and also we are going to be providing a border and here we are going to be using the ternary.
4:25:41
Así que usaré como 2 píxeles sólidos y luego ese color de texto que ya hemos definido arriba.
So I'll use like 2 pixel solid and then that text color which we've already defined up above.
4:25:47
Así que ahora, si guardo mi archivo y aquí puedes ver que ahora estamos obteniendo ese color de texto de este estado. Bien, así que eso va a ser solo para la funcionalidad.
So now if I save my file and here you can see we are now grabbing that text color from this state. Okay, so that's going to be just for the functionality.
4:25:55
Lo siguiente que quiero hacer es proporcionar una etiqueta. Y aquí vamos a renderizar nuestra etiqueta totalmente de manera dinámica.
The next thing that I want to do is that I want to provide a label. And here we're going to be rendering our label totally dynamically.
4:26:00
Así que si nuestro color de fondo es igual a este color, que es como 1B, vamos, 1B, 1B, 1B.
So if our background color is equal to this color, which is like 1B, come on, 1B, 1B, 1B.
4:26:07
Así que en esta situación, vamos a usar el tema negro como etiqueta.
So in this situation, we're going to be using the black theme as a label.
4:26:12
Vamos a proporcionar un tema negro como etiqueta para este botón. Pero si ese no es el caso, en esta situación, vamos a proporcionar como tema blanco.
We are going to be providing a black theme as a label for this button. But if that's not the case, in this situation, we're going to be providing like white theme.
4:26:20
bien, así que déjame mostrarte allí y refrescar
okay just like so let me just show you there and refresh
4:26:23
ahí no puedes ver eso porque todo no solo está configurado
there you cannot see that because everything is not only set
4:26:26
en blanco y ahora debajo de este botón vamos a crear una
to white and now underneath this button we're going to be creating a
4:26:30
sección para nuestro contenido, así que crearé una sección con una clase de contenido
section for our content so i'll create a section with a class of content
4:26:33
y dentro de este contenido vamos a usar nuestro h1 que
and inside this content we're going to be using our h1 which will
4:26:36
simplemente selecciona bienvenido a ven a un y luego vamos a proporcionar lo que br y mundo real punto punto punto así que ahora si guardo mi archivo y refresco eso y no podemos ver nada.
just select welcome to come on to a and then we're going to be providing what br and real world dot dot dot so now if i save my file and refresh that And we cannot see anything.
4:26:47
No sé por qué. Vamos a ir a nuestra consola. Estamos obteniendo este error porque tenemos que crear nuestro manejador de eventos de clic.
I don't know why. Let's just go ahead and go to our console. We are getting this error because we have to create our handle click event handler.
4:26:54
Así que voy a copiar el nombre de eso. Y vamos a crear eso justo aquí. Vamos a encargarnos de todo el estado. Olvidé hacer eso.
So I'm going to go ahead and copy the name of that. And let's just create that right here. We are going to be taking care of all of the state. I forgot to do that.
4:27:01
Así que solo crearé mi función con el nombre de manejar clic. Y cuando alguien llame a esta función en esa situación, vamos a tomar nuestro color de fondo establecido.
So I'll just create my function with the name of handle click. And when somebody calls this function in that situation, we are going to be taking our set background color.
4:27:10
Y vamos a proporcionar el valor ternario justo aquí. Así que si tenemos el color de fondo y si eso es igual a blanco, así que en esta situación vamos a usar este color que es 1b1b1b.
And we are going to be providing the ternary value right here. So if we have the background color and if that is equal to white, so in this situation we are going to be using this color which is 1b1b1b.
4:27:21
Y si ese no es el caso, vamos a alternar ese valor a un color totalmente blanco.
And if that's not the case, we are going to be toggling that value to totally white color.
4:27:26
Y ahora ocupémonos del color de este texto que tenemos aquí.
And now let's just take care of this text color which we have right here.
4:27:31
Así que el valor inicial se establecerá en este 1b1b y solo tenemos que revertir eso.
So the initial value will be set to this 1b1b and we have to just revert that back.
4:27:35
Así que voy a proporcionar un color de texto y si eso es igual a este 1B, 1B, 1B, en esa situación vamos a cambiar el color a algo como FFA31A.
So I'm going to provide like text color and if that is equal to this 1B, 1B, 1B, in that situation we are going to be changing the color of that to like FFA31A.
4:27:48
Y si ese no es el caso, vamos a cambiar el color a 1B, 1B, 1B una vez más.
And if that's not the case we are going to be changing the color to 1B, 1B, 1B once again.
4:27:53
Está bien, así que eso será todo para el color del texto, pero también tenemos que ocuparnos de este estilo de botón.
Okay so that's going to be it for the text color but we also have to take care of this button style.
4:27:58
Así que solo vamos a usar eso o, ya sabes, establecer el estilo del botón estaría bien.
So we are going to be just using that or you know what set button style would be fine.
4:28:02
y tenemos que verificar si el fondo es igual
and we have to check if background is equal
4:28:05
a totalmente blanco, así que en esa situación vamos a
to totally white so in that situation we're going to
4:28:08
cambiar nuestro color a 1b 1b 1b
be changing our color to 1b 1b 1b
4:28:11
y si ese no es el caso, vamos a usar nuestro totalmente blanco
and if that's not the case we're going to be using our totally white
4:28:14
color, así que aquí puedes ver que tenemos nuestro texto como bienvenido al verdadero
color so here you can see we have our text like welcome to the real
4:28:18
mundo, si hago clic en este tema blanco, primero va a
world if i click on this white theme it's going to first
4:28:21
cambiar el color de fondo, también el color del texto y
of all change the background color also the text color and
4:28:24
también va a cambiar este valor de texto, así que déjame acercar un poco así y ahora, si hago clic en esto ahora
it's going to also change this text value so let me just zoom in a bit like that and now if i click on this now
4:28:30
está diciendo como color blanco y ahora, si hago clic en esto, va a dar
is saying like white color and now if i click on this it's going to give
4:28:33
un tema negro aquí, así que sí, eso fue
us like black theme right here so yeah that was
4:28:37
nuestro color o alternar el color de fondo, está bien
our color or toggle background color okay
4:28:40
así que es hora de otro proyecto, vamos a construir una barra de búsqueda oculta
so time for another project we are going to be building a hidden
4:28:43
así que usaré como barra de búsqueda oculta
search bar so i'll use like hidden search
4:28:46
barra.jsx, dentro de ahí voy a estar
bar dot jsx inside there i'm going to be
4:28:49
usando un rafce, comenta esta línea y agarra nuestra barra de búsqueda oculta, así que mi archivo ve a
using a rafce comment this line out and grab our hidden search bar so my file go to
4:28:56
mi hoja de estilos, elimina una sola cosa de ahí y pega
my style sheet remove a single thing from there and paste
4:28:59
los nuevos, revisa esto en el navegador y
the new ones check this out in the browser and
4:29:02
ahí vamos, damas y caballeros, así que lo siguiente
there we go ladies and gentlemen so the next thing
4:29:05
que quiero hacer es que quiero agarrar primero de
that i want to do is that i want to grab first of
4:29:08
todas mis estadísticas, así que usaré como tú indicas y
all my stats so i'll use like you state and
4:29:11
también necesitaremos obtener nuestro css, así que iré a mi style.css también necesitaríamos instalar una biblioteca de terceros que se llama react
we will also need to grab our css so i'll go to my style.css we would also need to install third-party library which is called the react
4:29:19
iconos que voy a estar usando npm i react icons y ahora si presiono nrs puedo instalar eso en mi máquina
icons i'm going to be using npm i react icons and now if i hit nrs can install that in my machine
4:29:26
de inmediato, bien, ahora están instalados con éxito, así que
right away okay now they're successfully installed so
4:29:29
solo vamos a obtener el icono de búsqueda fa
we are going to be only grabbing the fa search icon
4:29:33
de react js o de los iconos de react, para ser precisos
from the react js or from the react icons to be precise
4:29:36
ahora dentro de esta barra de búsqueda oculta vamos a crear
now inside this hidden search bar we're going to be creating
4:29:39
dos entradas, así que solo usaré como una entrada de mostrar y también el conjunto de entrada de mostrar que vendrá del use state y el valor inicial se establecerá en falso
two inputs so i'll just use like a show input and also the set show input that's going to be coming from the use state and the initial value will be set to false
4:29:49
también voy a crear un color de fondo y también el conjunto de color de fondo y eso será igual al U state y el valor inicial se establecerá en totalmente blanco.
I'm going to also create a BG color and also the set BG color and that's going to be equal to the U state and the initial value will be set to totally white.
4:30:00
Ahora voy a cambiar ahí a una sección en lugar de un div.
Now I'm going to change there to a section instead of a div.
4:30:04
Cambiemos ahí a sección y voy a proporcionar un nombre de clase de contenedor hoy y también el estilo de este estilo que ya estamos especificando para nuestra importación.
Let's just change there to section and I'm going to provide a class name of container today and also the style of this style which we are already specifying for our import.
4:30:14
Así que usaré como color de fondo y también eso será igual a nuestro color de fondo justo aquí.
So I'll use like background color and also that's going to be equals to our bg color right here.
4:30:19
Así que ahora si guardo eso, también vamos a proporcionar el controlador de eventos on click
So now if I save that, we're going to be also providing the on click event handler
4:30:23
y cuando alguien haga clic ahí vamos a activar esto
and when somebody clicks on there we're going to be firing this
4:30:26
función y crearemos esta función en unos segundos y
function and we will create this function in a few seconds and
4:30:29
ahora dentro de ahí vamos a estar primero verificando, está bien
now inside there we're going to be first of all checking okay
4:30:32
así que si tenemos la entrada de mostrar en esa situación
so if we have the show input in that situation
4:30:36
vamos a proporcionar alguna interfaz de usuario y si eso no es el
we're going to be providing some ui and if that's not the
4:30:39
caso, vamos a proporcionar otra interfaz de usuario, así que solo voy a
case we're going to be providing another ui okay so i'll just
4:30:42
presionar enter aquí y si esa entrada de mostrar es igual a verdadero, vamos a proporcionar un campo de entrada que tendrá el tipo
hit enter right here and if that show input is equal to true we're going to be providing an input field which will have the type
4:30:49
de texto y también dirá como un marcador de posición de
of text and also it will say like a placeholder of
4:30:52
buscar punto punto punto, pero si ese no es el caso, vamos
search dot dot dot but if that's not the case we're
4:30:56
a estar usando nuestro icono fa, si un icono de búsqueda, vamos
going to be using our fa icon if a search icon we're
4:30:59
a estar obteniendo ahí y vamos a estar adjuntando el controlador de eventos on click
going to be grabbing there and we're going to be attaching the own click
4:31:02
ahí y cuando alguien haga clic ahí vamos a
event handler on there and when somebody clicks on there we're going to
4:31:05
vamos a usar como uh set show input y el valor inicial se establecerá en verdadero voy a guardar mi archivo y ahora es hora de crear este manejador de clics está bien así que voy a ir y crear allí justo aquí.
be using like uh set show input and the initial value will be set to true i'm going to save my file and now it's time to create this handle click okay so i'm going to go ahead and create there right in here.
4:31:18
Vamos a cambiar primero el color de fondo a
We are going to be first of all changing the background color to
4:31:21
totalmente 1a 1a 1a
totally 1a 1a 1a
4:31:25
y también debajo de eso vas a verificar si e o event.target.className es triple igual al contenedor que en este caso es igual al contenedor.
and also underneath there you are going to be checking if e or event.target.className is triple equals to the container which in this case is equal to the container.
4:31:37
Así que en esa situación vamos a usar como set show input y vamos a proporcionar el valor de falso
So in that situation we are going to be using like set show input and we are going to be providing the value of false
4:31:42
a ello como aquí puedes ver que ahora estamos proporcionando el valor de falso aquí
to it like here you can see we're now providing the value of false here
4:31:46
también tenemos que proporcionar el valor de falso hoy y
we also have to provide the value of false today and
4:31:49
también vamos a cambiar el color de fondo a totalmente blanco
we're going to be also changing the background color to totally white
4:31:53
color así que ahora voy a guardar mi archivo y revisar esto aquí
color so now i'm going to save my file and check this out here
4:31:56
puedes ver que tenemos qué icono así que ahora si hago clic en eso también va a
you can see we have what icon so now if i click on that it's going to also
4:31:59
cambiar el color de fondo y nos va a dar este campo de entrada justo aquí así que ahora si hago clic en otro lugar va a eliminar
change the background color and it's going to give us this input field right here so now if i click on somewhere else so it's going to remove
4:32:05
ahí nos va a dar este icono así que sí, este también es un proyecto simple que quiero compartir con
there it's going to give us this icon so yeah this is also a simple project which i want to share with
4:32:11
ustedes es hora de crear un proyecto simple de testimonios
you guys it's time to create a simple testimonials project
4:32:14
así que voy a crear mi componente primero .jsx
so i'm going to create my component first of all dot jsx
4:32:18
y usar mi rfce y crear mi
and use my rfce and create my
4:32:21
testimonio justo aquí bebé cambia
testimonial right in here baby change
4:32:24
el estilo elimina cada cosa de allí
the style remove every single thing from there
4:32:28
y coloca un nuevo estilo y aquí tenemos que
and place a new styling and here we have to
4:32:31
ir y ir a nuestro testimonio primero tenemos que verificar cómo se ve y sí, se ve genial, es
go ahead and go to our testimonial first of all we have to check how it looks like and yeah it is looking great it is
4:32:38
se ve genial, fue un gran comienzo así que lo primero que quiero hacer es que quiero agarrar mi
looking great that was a great start so the first thing that i want to do is that i want to grab my
4:32:43
usar estado y también quiero agarrar mi estilo
use state and also i want to grab my style
4:32:46
del style.css y
from the style.css and
4:32:49
lo que voy a hacer es que voy a crear mi índice actual y
what i'm going to do is that i'm going to create my current index and
4:32:53
también establecer el índice actual primero y eso es
also set current index first of all and that's
4:32:56
va a ser igual al uso del estado y el valor inicial se establecerá
going to be equals to the use state and the initial value will be set
4:32:59
a cero porque obviamente quieres comenzar desde cero y luego vamos a crear muchos testimonios, así que tenemos algunos
to zero because obviously you want to start from a zero and then we're going to be creating a lot of testimonials so we have a few
4:33:06
testimonios, tenemos una variable y ahora dentro de esta variable
testimonials we have a variable and now inside this variable
4:33:09
tenemos nuestro arreglo y ahora dentro de este arreglo tenemos algunos objetos
we have our array and now inside this array we have a few objects
4:33:12
como objeto uno, dos y tres y dentro
like object one two and three and inside
4:33:15
de estos objetos tenemos una cita y también el autor que dijo
these objects we have a quote and also the author who said
4:33:19
esa cita, así que tenemos algo como 'este es el mejor producto que
that quote so we have like this is the best product i
4:33:22
he usado y también lo recomiendo altamente a todos'
have ever used and also i highly recommend this product to everyone
4:33:25
y este producto ha cambiado completamente mi vida, así que
and this product has completely changed my life so
4:33:28
sí, estos son mis testimonios, así que voy a ocultar desde aquí
yeah these are my testimonials so i'm going to hide there from here
4:33:31
lo siguiente que tenemos que hacer es que tenemos que usarlo dentro de nuestra interfaz de usuario
the next thing that we have to do is that we have to use the inside our ui
4:33:35
así que lo que voy a hacer es que voy a proporcionar mi testimonio
so what i'm going to do is that i'm going to provide my testimonial
4:33:38
como una clase a este desarrollo y también voy a
as a class to this dev and also i'm
4:33:41
crear un desarrollo con una clase de testimonios y luego un guion
going to create a dev with a class of testimonials and then dash
4:33:44
código y dentro de ahí, primero que nada, vamos a obtener todos los
code and inside there first of all we are going to be grabbing all the
4:33:47
testimonios que ya tenemos aquí y
testimonials which we already have right here and
4:33:51
tenemos nuestros arreglos, lo que significa que podemos obtener el índice desde allí
we have our arrays which means like we can grab the index from there
4:33:54
así que voy a usar corchetes y aquí vamos a pasar nuestro índice actual que viene de este estado aquí, así que básicamente va a comenzar desde
so i'm going to use like brackets and here we are going to be passing our current index which is coming from this state right here so basically it's going to start from
4:34:02
el cero porque estamos proporcionando el valor inicial de cero hoy, así que
the zero because we are providing the initial value of zero today so
4:34:05
nos va a dar algo como el testimonio cero, lo que significa que vamos a
it's going to give us like testimonial of zero which means like we're going to
4:34:09
obtener solo el primer testimonio aquí, como
be getting only the first testimonial right here like
4:34:12
este testimonio, así que eso está hecho
this testimonial so that's done
4:34:15
voy a continuar y copiar mi testimonio
i'm going to go ahead and copy my testimonial
4:34:18
y colocarlo allí, quiero decir, como índice actual y colocar eso allí y
and place there i mean like current index and place that there and
4:34:21
solo estamos interesados en obtener la cita, no el autor, sino solo la cita, así que vamos a obtener eso y ahora si yo
we are only interested in getting the quote not the author but only the quote okay so we're going to be getting there and now if i
4:34:28
guardo mi archivo y aquí puedes ver que ahora estamos obteniendo esta cita correctamente
save my file and here you can see we are now getting this quote right
4:34:31
aquí y ahora la siguiente cosa que quiero hacer es que
here and now the next thing that I want to do is that
4:34:34
también quiero mostrar al autor, así que para mostrar al autor vamos
I also want to show the author so to show the author we
4:34:37
a estar usando esa div una vez más y solo voy a cambiar
are going to be using like that div once again and I'm going to just change
4:34:40
el nombre de la clase a autor y ahora dentro de ahí estamos
the class name to author and now inside there we are
4:34:43
simplemente proporcionando un guion y aquí tenemos que usar una vez más
going to be just providing a dash and here we have to use once again
4:34:46
nuestros testimonios y vamos a estar proporcionando nuestro índice actual y ahora en esta situación vamos a estar obteniendo al autor de ahí, así que aquí puedes ver que ahora no me olvido de lo que hace JNE.
our testimonials and we are going to be once again providing our current index and now in this situation we are going to be grabbing the author from there so here you can see we are now I'm not forgetting what JNE do.
4:34:56
Y sí, se ve increíble. Ahora la siguiente cosa que quiero hacer es que quiero crear dos botones.
And yeah, that's looking amazing. Now the next thing that I want to do is that I want to create two buttons.
4:35:01
El primer botón simplemente nos dará el hilo anterior. Y el siguiente nos dará el siguiente hilo.
The first button will just give us the previous thread. And the next will give us the next thread.
4:35:06
Así que solo lo crearé con la clase de testimonios nav. Y ahora dentro de ahí vamos a estar creando dos botones como prev.
So I'll just create it with the class of testimonials nav. And now inside there we are going to be creating two buttons like prev.
4:35:12
Y también el siguiente botón justo aquí. Bien, así que solo usemos nuestro controlador de eventos on click allí.
And also the next button right here. Okay, so let's just use our on click event handler on there.
4:35:18
Y cuando alguien haga clic allí, vamos a estar activando como manejar prev.
And when somebody clicks on there we are going to be firing like handle prev.
4:35:22
y también vamos a estar activando el clic de manejar siguiente
and also we are going to be firing the handle next click
4:35:26
aquí bien, así que voy a copiar allí y ahora solo vamos a crear
right here okay so I'm going to copy there and now let's just create
4:35:30
ahí justo aquí, vamos, const manejar clic previo
there right here come on const handle preview click
4:35:33
y ahora dentro de ahí vamos a estar usando el
and now inside there we are going to be using the
4:35:36
establecer índice actual y solo proporcionemos nuestro índice actual más nuestro testimonio, vamos, nuestro testimonio y solo vamos a estar decrementando uno de ahí
set current index and let's just provide our current index plus our testimonial come on our testimonial and we are going to be only decrementing one from there
4:35:47
Luego tenemos que dividir todo eso usando nuestro testimonios.length.
Then we have to divide all of that by using our testimonials.length.
4:35:51
Así que ahora si guardo mi archivo y solo refresquemos eso.
So now if I save my file and let's just refresh that.
4:35:54
Oh, nos va a dar un error porque también tenemos que crear esta función manejar siguiente justo aquí.
Oh, it's going to give us an error because we also have to create this handle next function right here.
4:36:00
Así que también vamos a estar creando allí justo aquí. Así que lo que voy a hacer es que solo voy a duplicar esto en. O sabes, no voy a duplicar eso.
So we are going to be also creating there right here. So what I'm going to do is that I'm going to just duplicate this in. Or you know, I'm not going to duplicate that.
4:36:07
Déjame solo crear mi función const manejar clic siguiente justo aquí.
Let me just create my const handle next click function right here.
4:36:11
Y ahora dentro de ahí vamos a estar usando nuestro establecer índice actual una vez más.
And now inside then we're going to be using our set current index one more time.
4:36:16
Y vamos a estar proporcionando nuestro índice actual más uno una vez más. Luego dividiremos allí por testimonios.length.
And we're going to be providing our current index plus one once again. Then we will divide there by testimonials dot length.
4:36:23
Así que ahora si guardo mi archivo y aquí puedes ver que tenemos nuestro botón anterior y también tenemos nuestro botón siguiente justo aquí.
So now if I save my file and here you can see we have our previous button and we also have our next button right here.
4:36:29
Así que si hago clic en este anterior, quiero decir, en el botón siguiente, nos va a dar un siguiente producto.
So if I click on this previous, I mean like next button, so it's going to give us a next product.
4:36:33
Entonces, también puedo hacer clic en este anterior, así que nos dará ese producto anterior aquí. Así que puedo seguir y seguir, así que nos dará todo ese producto siguiente.
Then I can also click on this previous one, so it's going to give us that previous product right here. So I can go on and on, so it's going to give us all of that next product.
4:36:41
Entonces, puedo seguir y seguir en el anterior, así que nos dará esos elementos anteriores aquí.
Then I can go on and on on the previous, so it's going to give us that previous items right here.
4:36:46
Está bien, así es como vamos a obtener el siguiente.
okay so this is how we are going to be getting the next i
4:36:49
significa como el estado anterior y así es como vamos a obtener el siguiente.
mean like the previous uh state and this is how we are going to be getting the next
4:36:52
estado y también podemos eliminar estas llaves de aquí.
state and we can also remove these curly braces from here
4:36:55
y supongo que tendré que dejarlo ahí por este, así que vamos a
and i guess i'm going to have to leave there for this one so let's
4:36:58
simplemente guardar mi archivo y aquí puedes ver que puedo hacer clic en el siguiente.
just save my file and here you can see i can click on the next
4:37:01
nos dará el siguiente elemento y también puedo hacer clic en el anterior.
it's going to give us the next item and i can also click on the previous
4:37:05
nos dará el elemento anterior, así que si tienes muchos códigos, puedes obtener muchos resultados diferentes aquí, así que sí, ese fue nuestro proyecto básico de testimonios en react.js.
it's going to give us the previous item so if you have like a lot of codes you can totally get like a lot of different results right here so yeah that was our basic testimonial project in react.js.
4:37:15
Está bien, así que es hora del proyecto de acordeón. Así que ya cambié
Okay so time for the accordion project. So I already changed
4:37:19
el estilo y también tengo esta carpeta de utilidades y ahora dentro de esta carpeta de utilidades tengo este archivo content.js y ahora dentro de este archivo content.js tenemos nuestros datos de acordeón.
the styling and I also have this utils folder and now inside this utils folder I have this content.js file and now inside this content.js file we have our accordion data.
4:37:29
Ahora estamos exportando esto, lo que significa que lo vamos a usar en otros archivos.
We are now exporting this which means like we are going to be using that in other files.
4:37:34
Aquí puedes ver que tenemos nuestro arreglo y ahora dentro de este arreglo tenemos nuestro objeto.
Here you can see we have our array and now inside this array we have our object.
4:37:37
Va a tener el título que dirá qué es HTML y luego el contenido que simplemente aclarará qué es un HTML.
It's going to have the title which will say like what is html and then the content which will just like clarify like what is a HTML.
4:37:45
Luego tenemos qué es ReactJS, qué es NodeJS, qué es Golang y así sucesivamente.
Then we have like what is a ReactJS, what is a NodeJS, what is a Golang and so on and so forth.
4:37:50
Y eres más que bienvenido a proporcionar más datos a eso si lo deseas.
And you are more than welcome to provide more data to that if you wanted to.
4:37:54
Así que sí, así es como vamos a exportar eso para que podamos usarlo en otros archivos.
So yeah, this is how we are going to be exporting that so that we can use that in other files.
4:37:58
Así que lo primero que quiero hacer es crear mi componente de acordeón aquí.
So the first thing that I want to do is that I want to create my accordion component right here.
4:38:02
Así que voy a usar acordeón.jsx y simplemente usemos nuestro RAFCE, guarda mi archivo y ve a mi aplicación y regístralos.
So I'm going to use like accordion.jsx and let's just use our RAFCE, save my file and go to my app and register them.
4:38:09
pero no vamos a registrar nuestro componente así.
but we are not going to be registering our component like that.
4:38:13
Lo primero que tenemos que hacer es obtener nuestro contenido, que son los datos de acordeón.
The first thing that we have to do is that we have to get our content, which is accordion data.
4:38:20
Vamos, si podemos obtener eso. Tenemos nuestros datos de acordeón. Maldita sea.
Come on, if we can get that. We have our accordion data. God damn it.
4:38:24
Tenemos que usar nuestra importación y vamos a obtener algo de, simplemente vamos a la carpeta de utilidades,
We have to use our import, and we are going to be grabbing something from, let's just go ahead and go to the utils,
4:38:31
y vamos a obtener nuestros datos de ese contenido. Está bien, así que los datos serán esos datos de acordeón. Ahora tenemos que copiar eso.
and we are going to be grabbing our data from that content. Okay, so the data will be that accordion data. Now we have to copy that.
4:38:38
Tenemos que crear nuestro div con una clase de acordeón. Y dentro de este div, vamos a iterar sobre todos esos datos.
We have to create our div with a class of accordion. And inside this div, we are going to be iterating over through all of that data.
4:38:45
Porque ya sabemos que esto es un arreglo. Así que significa que podemos usar el método map allí. Así que voy a usar el método map aquí.
Because we already know that this is an array. So which means like we can use the map method on there. So I'm going to use the map method right here.
4:38:52
Y vamos a estar desestructurando el título. Y también aquí puedes ver que para cada objeto, tenemos el título y también el contenido aquí.
And we are going to be destructuring the title. And also here you can see for each object, we have the title and also the content right here.
4:39:00
Así que vamos a estar desestructurando eso. Y la siguiente cosa que quiero hacer es que quiero llamar a mi componente de acordeón aquí.
So we are going to be destructuring that. And the next thing that I want to do is that I want to call my accordion component right here.
4:39:05
Y vamos a estar pasando dos props a él. Así que vamos a estar pasando el título como la prop a este componente de acordeón.
And we are going to be passing two props to it. So we're going to be passing the title as the prop to this accordion component.
4:39:14
También vamos a estar pasando un contenido allí. Y vamos a estar pasando este contenido como una prop.
We're going to be also passing a content to there. And we're going to be passing this content as a prop.
4:39:19
Así que ahora estamos obteniendo todo el título y todo el contenido de estos datos de acordeón.
So we are now getting all of the title and all of the content from this accordion data.
4:39:24
Y ahora estamos pasando eso a nuestro componente de acordeón. Así que voy a entrar en mi componente de acordeón aquí. Y ahora déjame reestructurarlo.
And we're now passing there to our accordion component. So I'm going to go into my accordion component right here. And now let me just restructure there.
4:39:31
Así que voy a usar el título y también el contenido. Así que así es como vamos a estar reestructurándolo.
So I'm going to use like title and also the content. So this is how we're going to be restructuring there.
4:39:36
Pero lo primero que tenemos que hacer es que tenemos que obtener nuestro use state y también tenemos que obtener nuestra hoja de estilos.
But the first thing that we have to do is that we have to grab our use state and we also have to grab our style sheet.
4:39:41
Así que voy a ir a mi style.css y eso va a ser todo. OK, así que sí.
So I'm going to go ahead and go to my style.css and that's going to be it. OK, so yeah.
4:39:47
Ahora la siguiente cosa que quiero hacer es que quiero simplemente crear un estado. Así que eso nos dará algo como is active y luego set is active.
Now the next thing that I want to do is that I want to just make a state. So which will give us like is active and then set is active.
4:39:55
Eso va a ser igual al use state. Y para el valor inicial, vamos a proporcionar un estado falso al final.
That's going to be equals to the use state. And for the initial value, we're going to be providing a false state to the end.
4:40:00
Y ahora para esta declaración de retorno voy a eliminar este acordeón y
and now for this return statement i'm going to remove this accordion and
4:40:03
cambiar este div a o sección y
change this div to or section and
4:40:06
ahora aquí para esta sección vamos a estar primero proporcionando un nombre de clase
now here for this section we're going to be first of all providing a class name
4:40:09
y eso va a ser la tarjeta de acordeón que
and that's going to be the accordion card we
4:40:13
también proporcionaremos la clave y la clave será math.random, puedes básicamente proporcionar cualquier cosa allí, como puedes usar el uuid si quieres. Ahora dentro de allí vamos a estar creando nuestro div con la clase de encabezado y cuando alguien
will also provide the key and key will be math.random you can like basically provide anything there like you can use the uuid if you wanted to now inside there we are going to be creating our div with the class of header and when somebody
4:40:25
haga clic allí, vamos a estar disparando nuestra función que dirá como set is active
clicks on there we are going to be firing our function which will say like set is active
4:40:31
cambiando eso a como is active, una vez más eso
changing that to like is active like once again that
4:40:34
ahora está configurado en falso, así que ahora aquí si eso está configurado
is now set to false so now here if that is set
4:40:37
en falso, va a cambiar a verdadero y si eso está configurado en verdadero
to false it's going to change there to true and if that is set to true
4:40:40
va a cambiar a falso, está bien, y ahora dentro de este
it's going to change there to false okay and now inside this
4:40:44
div vamos a estar creando otro div que simplemente dirá como mi título y ahora debajo de este título vamos a estar proporcionando nuestro
div we are going to be creating yet another div which will just say like my title and now underneath this title we are going to be providing our
4:40:50
párrafo con la clase de icono y aquí si
paragraph with the class of icon and here if
4:40:53
está activo, así que en comando si está
it is active so in command if it
4:40:56
es cola en esa situación vamos a estar usando esto
is tail in that situation we are going to be using this
4:40:59
guion, pero si ese no es el caso vamos a estar usando esto
dash but if that's not the case we are going to be using this
4:41:03
símbolo más aquí déjame solo guardar eso y
plus symbol right here let me just save that and
4:41:06
aquí puedes ver que tenemos nuestro acordeón aquí, así que si hago clic en
here you can see we have our accordion right here so if i click on
4:41:09
eso, va a cambiar el ícono a menos y si hago clic allí una vez más, va a cambiar allí a más, está bien, así que este paso ya está hecho, lo siguiente que quiero hacer es ocuparme de este contenido también.
that it's going to change the icon to minus and if i click on there once again so it's going to change there to plus okay so this step is now done the next thing that i want to do is that I want to take care of this content as well.
4:41:20
Así que quiero mostrar el contenido y también quiero ocultar el contenido.
So I want to show the content and I also want to hide the content.
4:41:23
Así que solo voy a crear un div con una clase de contenido y dentro de este contenido vamos a estar verificando si está activo y luego vamos a estar creando nuestro párrafo.
So I'll just create a div with a class of content and inside this content we're going to be checking if it is active and then we're going to be creating our paragraph.
4:41:33
Déjame solo crear mi párrafo aquí. Voy a proporcionar un nombre de clase de información de tarjeta y para esta información de tarjeta vamos a estar renderizando nuestro contenido, pero si ese no es el caso, no vamos a ver nada.
Let me just create my paragraph right here. I'm going to provide a class name of card info and for this card info we're going to be rendering our content but if that's not the case we're not going to see anything.
4:41:45
está bien, así que ahora déjame solo mostrarte, tenemos que hacer clic aquí
okay so now let me just show you there we have to click over here
4:41:48
puedes ver cómo se ve mi interfaz de usuario, pero si quiero ver el contenido
you can see this is how my ui looks like but if i want to see the content
4:41:51
de lo que es react js, así que puedo hacer clic allí y
of like what is react js so i can totally click on there and
4:41:54
puedo leer el contenido, puedo totalmente expandir allí
i can read the content i can totally uncollapse there
4:41:57
y así sucesivamente, así que sí, este es
and so on and so forth so yeah this is
4:42:01
nuestro componente de acordeón básico o el más básico en react js, es hora del noveno proyecto, así que ahora en este vamos a estar construyendo la validación de formularios, así que solo voy a crear un formulario
our basic or the most basic accordion component in react js time for the ninth project so now in this one we're going to be building the form validation so i'll just create a form
4:42:12
dot jsx y solo vamos a usar nuestro rafc semi
dot jsx and let's just use our rafc semi
4:42:15
archivo y renderizar mi formulario correctamente
file and render my form right
4:42:18
en este archivo semi, solo vamos a ir a nuestra hoja de estilos
in here semi file let's just go ahead and go to our style sheet
4:42:21
y eliminar cada cosa de allí y proporcionar nuestro nuevo estilo
and remove every single thing from there and provide our new style
4:42:24
aquí y mira esto, nuestro
right here and check this out our
4:42:28
formulario se ve genial, pero nuestro código no se verá genial porque vamos a tener que crear mucho estado y luego tenemos que hacer un seguimiento de todo
form is looking cool but our code will not look cool because we're going to have to create a lot of state and then we have to keep track of all of
4:42:36
la prueba y eso es porque no estamos usando una biblioteca de validación de formularios que aprenderemos en este curso, pero no ahora.
test and that's because we are not using a form validation library which we will learn in this course but not right now.
4:42:43
Se llama react-hook form. Aprenderemos allí muy pronto, pero no ahora.
It's called the react-hook form. We will learn there very soon but not right now.
4:42:47
Así que lo primero que quiero hacer es importar mi uso de prueba, guardar mi archivo, pero no sé, aquí puedes ver que estamos obteniendo estos datos
So the first thing that I want to do is that I want to import my use test, save my file but I don't know here you can see we are getting this data
4:42:57
maldita sea, ¿qué demonios estoy haciendo? Dios, ve a mi amp, comenta esta línea en el archivo semi.
god damn it what the hell am I doing god go to my amp, comment this line out semi-filed.
4:43:05
Así que lo primero que quiero hacer es crear mucho estado. Como el primer estado sería para el nombre de usuario y luego establecer nombre de usuario.
So the first thing that I want to do is I want to create a lot of state. Like the first state would be for the username and then set username.
4:43:13
Eso va a ser igual al estado usado y el valor inicial será solo una cadena vacía.
That's going to be equals to the used state and the initial value will be just empty string.
4:43:17
Vamos a crear para el correo electrónico y luego establecer correo electrónico, establecer correo electrónico. Eso va a ser igual al estado usado.
Let's create for the email and then set email, set email. That's going to be equals to the used state.
4:43:24
Esto va a ser igual al estado usado y el valor inicial será una cadena vacía. Crear para la confirmación de contraseña.
And once again, empty string. Let's create for the password and then set password.
4:43:31
Así que la confirmación de contraseña y luego establecer confirmación de contraseña va a ser igual al estado usado y simplemente proporcionemos nuestra cadena vacía aquí.
This is going to be equals to the used state and the initial value will be empty string. Create for the confirm password.
4:43:37
Así que la confirmación de contraseña y luego establecer confirmación de contraseña va a ser igual al estado usado y simplemente proporcionemos nuestra cadena vacía aquí.
So confirm password and then set confirm password is going to be equals to the used state and let's just provide our empty string right here.
4:43:46
A continuación, tenemos que crear mucho estado para los errores.
Next we have to create a lot of state for the errors.
4:43:49
Así que crearé un estado para el error de nombre de usuario, nombre de usuario y luego también crearé uno más para el error mencionado.
So I'll create like a state for the username error, username and then also create one more for the said error.
4:43:59
nombre de usuario y va a ser igual al estado usado y el valor inicial será una cadena vacía
username and it's going to be equals to the use state and the initial value will be empty string
4:44:04
bien, vamos a crear para el correo electrónico así que error de correo electrónico
okay let's just create for the email one so error email
4:44:07
y también establecer error de correo electrónico
and also set error email
4:44:10
y va a ser igual al estado usado y el valor inicial
and it's going to be equals to the use state and the initial value
4:44:13
será una cadena vacía crear para el error de contraseña y luego establecer error de contraseña va a ser igual al estado usado y el valor inicial
will be empty string create for the error password and then set error password it's going to be equals to the use state and the initial value
4:44:22
será una cadena vacía vamos a crear uno más para el error
will be empty string let's just create one more for the error
4:44:25
confirmar contraseña c
confirm password c
4:44:28
o n f i r m sí, eso es correcto, nosotros
o n f i r m yep that's correct we
4:44:32
también tenemos que usar lo que se dijo error de confirmar contraseña
also have to use what said error confirm password
4:44:35
aquí va a ser igual al estado usado y el valor inicial será una cadena vacía. Bien, ahora debajo de todos ellos también vamos a crear para el color así que solo proporcionaré como const
right here it's going to be equals to the use start and the initial value will be empty string okay now underneath all of them we're going to be also creating for the color so i'll just provide like const
4:44:46
color de usuario y luego establecer color de usuario va a ser igual al estado usado y el valor inicial será una cadena vacía.
user color and then set user color is going to be equals to the use state and the initial value will be empty string.
4:44:55
Bien, vamos a crear para el color del correo electrónico y también establecer color de correo electrónico va a ser igual al estado usado y ese valor inicial será una cadena vacía.
Okay, let's create for the email color and also set email color is going to be equals to the used state and that initial value will be empty string.
4:45:06
Vamos a crear para el color de la contraseña y también establecer color de contraseña y va a ser igual al estado usado y una cadena vacía.
Let's create for the password color and also set password color and it's going to be equals to the used state and empty string.
4:45:14
Vamos a crear para el último que será un color de confirmación de contraseña y va a ser igual a establecer color de confirmación de contraseña.
Let's just create for the final one which will be a confirm password color and it's going to be equals to set confirm password color.
4:45:25
Eso va a ser igual al estado usado y el valor inicial será una cadena vacía. Bien, eso fue mucho estado.
That's going to be equals to the used state and the initial value will be empty string. Okay, that was a lot of states.
4:45:32
Bien, así que ahora vamos a hacer un seguimiento de todos esos estados. Pero primero, tenemos que construir nuestra interfaz de usuario. Luego vamos a saltar a todas esas cosas.
Okay, so now let's just keep track of all of those states. But first of all, we have to build our UI. Then we're going to be jumping into all of that stuff.
4:45:39
Así que voy a cambiar eso a fragmentos de react. Y dentro de estos fragmentos de react, vamos a crear nuestro div con el nombre de clase de tarjeta.
So I'm going to just change that to like a react fragments. And inside these react fragments, we're going to be creating our div with the class name of card.
4:45:46
Bien, así que ahora dentro de esta tarjeta, vamos a crear nuestra imagen de tarjeta. Y sí, supongo que eso estará bien.
Okay, so now inside this card, we're going to be creating our card image. And yeah, I guess that's going to be fine.
4:45:53
ahora debajo de esta imagen de tarjeta vamos a crear nuestro formulario y
now underneath this card image we are going to be creating our form and
4:45:56
no vamos a proporcionar ninguna acción hoy porque no queremos enviar nuestros datos
we are not going to be providing any action today because we don't want to send our data
4:45:59
a ningún servidor y vamos a estar usando nuestro campo de entrada
to any server and we are going to be using our input field
4:46:03
este campo de entrada tendrá el texto y también el marcador de posición
this input field will have the text and also the placeholder
4:46:06
de nombre está bien así que el estilo lo pondré como
of name okay so the style i'll just put like
4:46:09
el estilo se establecerá en el color del borde y el color del borde será igual al color del usuario que ya hemos especificado aquí está bien y para el valor.
the style will be set to border color and the border color will be equal to the user color which we've already specified right in here okay and for the value.
4:46:20
voy a proporcionar el nombre de usuario como el valor. Y también voy a proporcionar el propio controlador de eventos de cambio cuando alguien cambie o escriba algo dentro de ahí.
I'm going to provide the username as the value. And I'm going to also provide the own change event handler when somebody change or type something inside there.
4:46:26
así que vamos a estar usando nuestro establecer nombre de usuario. Vamos. Establecer nombre de usuario.
So we're going to be using our set username. Come on. Set username.
4:46:31
y aquí tenemos que especificar nuestro event.target.value.
And here we have to specify our event.target.value.
4:46:36
así que si guardo mi archivo y reviso esto.
So if I save my file and check this out.
4:46:40
así que aquí puedes ver que ahora estamos obteniendo nuestra imagen y también estamos obteniendo este campo de entrada aquí, que se ve increíble.
So here you can see we are now getting our image and also we are getting this input field right here, which is looking amazing.
4:46:45
así que lo siguiente que quiero hacer es mostrar mi error. Si tenemos uno
So the next thing that I want to do is that I want to show my error. If we have one
4:46:48
error, está bien así que solo usaré mi párrafo con la clase de error
error, okay so i'll just use my paragraph with the class of error
4:46:52
y aquí vamos a estar usando como error
and here we are going to be using like error
4:46:55
nombre de usuario está bien y ahora debajo de eso
username okay and now underneath that
4:46:58
vamos a estar creando nuestro campo de entrada así que solo crearé un input
we are going to be creating our input field so i'll just create an input
4:47:01
campo con el tipo de texto y también el marcador de posición dirá
field with the type of text and also the placeholder will
4:47:04
correo electrónico y vamos a estar proporcionando algún
say email and we are going to be providing some
4:47:07
tipo de estilo y ese estilo dirá como un borde
sort of a style and that style will say like a border
4:47:10
color y el borde vamos, color del borde y el color del borde será igual al color del correo electrónico está bien que hemos
color and the border come on border color and the border color will be equals to the email color okay which we've
4:47:18
ya especificado arriba y para el valor vamos a
already specified up above and for the value we are going
4:47:21
estar pasando un correo electrónico como valor y cuando alguien escribe
to be passing an email as a value and when somebody types
4:47:25
algo dentro de esto vamos a estar obteniendo este evento y también
something inside this we are going to be getting this event and also
4:47:28
vamos a estar usando nuestro establecer correo electrónico event.target.value
we are going to be using our set email event.target.value
4:47:31
dentro de ahí de la misma manera archivo así que ahora aquí puedes ver que tenemos nuestro correo electrónico
inside there same way file so now here you can see we have our email
4:47:35
campo justo aquí y ahora debajo de eso una vez más vamos
field right here and now underneath that once again we
4:47:38
a estar creando otro campo de entrada y eso va
are going to be using our paragraph the class of error and let's just render or error email right here we are going
4:47:44
a ser exactamente lo mismo pero en este caso vamos a proporcionar
to be creating yet another input field and that's going
4:47:47
una contraseña y también tenemos que cambiar eso a contraseña
to be exactly the same thing but in this case we're going to be providing
4:47:50
y este a correo electrónico correcto
a password and we also have to change that to password
4:47:53
aquí así que para el estilo voy a proporcionar el estilo
and this one to email right
4:47:56
del color del borde de venir
here so for the style i'm going to provide the style
4:48:00
en color del borde ahí vamos y
of the border color of come
4:48:03
en el color del borde ahí vamos y
on border c-o-l-o-r there we go and
4:48:06
el color del borde será igual al color de la contraseña y ahora vamos a proporcionar un valor y el valor se establecerá en contraseña está bien así que cuando
the border color will be equals to the password color and now we're going to be providing a value and the value will be set to password okay so when
4:48:14
alguien escriba algo dentro de ahí vamos a usar nuestro
somebody types something inside there we're going to be using our
4:48:17
establecer contraseña y aquí tenemos que especificar nuestro event.target.value
set password and here we have to specify our event.target.value
4:48:21
guardar mi archivo y aquí puedes ver que tenemos nuestro campo de contraseña
save my file and here you can see we have our password field
4:48:24
también y ahora debajo de eso vamos a estar una vez más
as well and now underneath that we're going to be once again
4:48:27
renderizando nuestro error así que crearé un párrafo con la clase
rendering our error so i'll create a paragraph with the class
4:48:30
de error que dirá como error de contraseña y
of error and which will say like error password and
4:48:34
ahora debajo de este párrafo finalmente vamos a crear un campo de entrada para la contraseña confirmada así que solo voy a
now underneath this paragraph finally we are going to be creating an input field for the confirmed password so i'll just
4:48:40
para la contraseña una vez más y estamos
for the password once again and we are
4:48:43
vamos a poner un marcador de posición que dirá como confirmar contraseña y
going to be porting a placeholder which will say like confirm password and
4:48:48
también el estilo será igual a ese color de borde
also the style will be equals to that border color
4:48:52
una vez más así que usaré como color de borde así que l o
once again so I'll use like border color so l o
4:48:55
r y el valor será un color de contraseña confirmada
r and the value will be a confirm password color
4:48:59
estaría bien ahí vamos y también voy a poner el valor de la contraseña confirmada y aquí vamos a poner el controlador de eventos on change cuando alguien intente cambiar algo.
would be fine there we go and also I'm going to port the value of confirm password and here we're going to be porting the on change event handler when somebody tried to change something.
4:49:10
Así que vamos a llamar a esta función que es como establecer contraseña confirmada y proporcionar nuestro event.dot target.dot value dentro de ahí.
So we are going to be calling this function which is like set confirm password and provide our event dot target dot value inside there.
4:49:17
Ahora debajo de eso vamos a crear nuestro párrafo con una clase de errores una vez más o simplemente error y aquí vamos a renderizar para el error de contraseña confirmada así.
Now underneath there we are going to be creating our paragraph with a class of errors once again or just error and here we are going to be rendering for error confirm password like so.
4:49:29
Ahora debajo vamos a crear nuestro botón con la clase de submit btn y también vamos a proporcionar el onclick
Now underneath there we are going to be creating our button with the class of submit btn and also we are going to be providing the onclick
4:49:36
manejador de eventos cuando alguien intente hacer clic en esto vamos a
event handler when somebody try to click on this we're going to be
4:49:39
usar nuestra función de validación que vamos a crear en unos segundos así que
using our validate function which we are going to be creating in a few seconds so
4:49:43
vamos a crear esta función de validación y eso va a estar aquí voy a
let's just create this validate function and that's going to be here i'm going
4:49:46
ir a la parte superior y crear mi función de validación correctamente
to go to the top and create my validate function right
4:49:49
aquí const validate va a tomar el evento y dentro de ahí vamos a usar como event dot prevent default vamos
here const validate is going to take the event and inside there we are going to be using like event dot prevent default come on
4:49:57
a prevenir el default
prevent prevent default
4:50:00
así y proporcionar nuestra verificación así que si tenemos como un
like so and provide our check so if we have like a
4:50:03
nombre de usuario dot link se crea entonces añadir así
username dot link is created then add so
4:50:06
en esta situación vamos a usar como set error username
in this situation we're going to be using like set error username
4:50:10
y vamos a establecerlo en una cadena vacía y
and we're going to be setting there to empty string and
4:50:13
también para el color del usuario establecido vamos a proporcionar un color verde allí si no es el caso así que en esta situación
also for the set user color we're going to be providing a green color to there if that's not the case so in this situation
4:50:20
vamos a usar como set error username y para
we're going to be using like set error username and for
4:50:23
el error vamos a especificar como el nombre de usuario debe
the error we're going to be specifying like username must
4:50:26
tener letras de largo o
be at letters long or
4:50:30
letras y también para el color del usuario establecido
letters and also for the set user color
4:50:33
vamos a cambiarlo a rojo así que si guardo mi archivo y
we're going to be changing there to red so if i save my file and
4:50:37
verifica esto así que si solo proporciono como dos s's y
check this out so if i just like provide like two s's and
4:50:40
hago clic allí nos va a dar como el usuario debe ser o el nombre de usuario debe tener letras de largo está bien así que si solo pongo algunas cosas aleatorias y hago clic allí no nos va a dar eso
click on there it's going to give us like user must be or username must be at letters long okay so if i just put like some random stuff and click on there it's not going to give us that
4:50:49
error y ahora la línea está configurada en verde está bien eso es genial
error and now the line is set to green okay that's cool
4:50:52
ahora también tenemos que proporcionar una validación para el correo electrónico así que
now we also have to provide a validation for the email so
4:50:55
debajo vamos a verificar como si email dot
underneath there we're going to be checking like if email dot
4:50:58
incluye este add gmail.com
includes this add gmail.com
4:51:02
así que si ese es el caso vamos a usar como set error email
so if that's the case we're going to be using like set error email
4:51:05
y establecer eso en una cadena vacía y también establecer el correo electrónico
and set that to empty string and also set email
4:51:09
el color se establecerá en totalmente verde, pero si ese no es el caso en esta situación, vamos a usar como establecer el color del correo electrónico y tenemos que establecer eso en totalmente
color will be set to totally green but if that's not the case in this situation we're going to be using like set email color and we have to set that to totally
4:51:17
rojo una vez más y tenemos que usar nuestro establecer error
red once again and we have to use our set error
4:51:22
correo electrónico y cambiar eso a como el correo electrónico debería
email and change that to like email should
4:51:25
ser o debería tener en gmail.com
be or should have at gmail.com
4:51:28
o sí, en gmail estaría bien, así que si yo
or yeah at gmail would be fine so if i
4:51:31
guardo mi archivo y si solo especifico algo y aquí
save my file and if i just specify something and here
4:51:34
puedes ver que ahora estamos obteniendo este error aquí mismo, así que si solo uso como gmail.com o algo, haz clic allí y ahora nos dará esa línea verde aquí.
you can see we are now getting this error right here so if i just use like at gmail.com or something click on there and now it's going to give us that green uh green line right here.
4:51:45
Ahora, debajo de eso, lo siguiente que tenemos que hacer es que también tenemos que ocuparnos de la contraseña.
Now underneath that, the next thing that we have to do is that we have to also take care of the password.
4:51:48
Así que usaré como si la longitud de la contraseña es mayor que agregar caracteres, agregar caracteres no asteriscos.
So I'll use like if password.length is greater than add characters, add characters not asterisks.
4:51:57
Así que usaré como establecer error contraseña y cambiar eso a cadena vacía y también establecer el color de la contraseña y cambiar eso a totalmente verde.
So I'll use like set error password and change that to empty string and also set password color and change that to totally green color.
4:52:07
Y si ese no es el caso, vamos a usar como establecer error contraseña y proporcionar
And if that's not the case, we're going to be using like set error password and provide
4:52:12
como la contraseña debería estar
like password should be at
4:52:15
letras de largo y debajo de eso vamos
letters long and underneath that we're
4:52:18
a usar como establecer contraseña y cambiar eso a rojo, así que
going to be using like set password and change that to red so
4:52:21
si guardo mi archivo y si solo proporciono como uno, dos, tres y
if i save my file and if i only provide like one two three and
4:52:25
ahora si envío esto, este es este error como la contraseña debería estar
now if i submit this is this error like password should be at
4:52:28
letras de largo, así que si solo especifico algo más, haz clic
letters long so if i just specify something else click
4:52:31
en, entonces ahora nos dará el verde y ahora para la validación final vamos a verificar la contraseña confirmada, así que si nuestra contraseña no es igual a
on then now it's going to give us the green and now for the final validation we're going to be checking the confirmed password so if our password is not equal to
4:52:42
esta cadena vacía y la contraseña es igual a la contraseña de confirmación
this empty string and password is equal to the confirm password
4:52:48
bien, así que vamos a usar como establecer error confirmar contraseña
okay so we are going to be using like set error confirm password
4:52:52
y tenemos que cambiar eso a cadena vacía y también tenemos que usar nuestro color de contraseña de confirmación
and we have to change that to empty string and also we
4:52:55
y tenemos que cambiar eso a totalmente verde, bien, así que ahora debajo de eso
have to use our set confirm password color
4:52:58
también vamos a señalar la clase else, si ese no es el caso, vamos a usar como establecer error confirmar contraseña, maldita sea, establecer
and we have to change that to totally green okay so now underneath that
4:53:02
error confirmar contraseña, tenemos que
we are going to be also pointing the else class if that's not the case we are going to be using like set error confirm password god damn it set
4:53:10
proporcionar este error como las contraseñas no coincidieron
error confirm password we have to
4:53:13
proporcionar este error como que las contraseñas no coinciden
provide this error like passwords didn't match
4:53:17
ah, maldita sea, tenemos que
ah god damn it we have to
4:53:20
encerrar eso entre comillas dobles así de lo contrario
wrap that in double quotes like so otherwise
4:53:23
vamos a obtener un error, cambia eso y
we are going to be getting an error change that and
4:53:26
también vamos a usar como establecer la contraseña de confirmación
we are going to be also using like set confirm password password
4:53:29
y proporcionar nuestro color rojo aquí, así que si guardo mi archivo, déjame refrescar eso y si escribo como
and provide our red color right here so if i save my file let me just uh refresh that and if i just write like
4:53:35
123 y también si escribo como 222
123 and also if i just write like 222
4:53:38
haz clic en eso, nos va a dar un error y ahora si escribo
click on that it's going to give us an error and now if i write
4:53:41
como uh 123 y también 123 dentro de ahí
like uh 123 and also 123 inside there
4:53:44
no nos va a dar ningún error por el último, pero
it's not going to give us any error for the last one but
4:53:48
nos dará un error por este porque la contraseña debe
it will give us error for this one because the password should
4:53:51
tener caracteres, así que sí, así es como se verá nuestra validación
be add characters okay so yeah this is how our validation
4:53:54
así que si hago clic ahí, nos va a dar un error y ahora
will look like so if i click on there it's going to give us an error and now
4:53:57
si especifico algún tipo de nombre como mi propio nombre Hosan o Hosan desarrollador web, más bien prueba en
if i specify like some sort of a name like my own name hosan or hosan web dev rather test at
4:54:04
gmail.com y luego prueba uno dos tres
gmail.com and then test one two three
4:54:07
prueba uno dos tres
test one two three
4:54:10
cuatro cinco y prueba uno dos tres cuatro cinco, nos va a dar líneas verdes aquí, así que sí, esa fue nuestra validación básica de formularios en react.js.
four five and test one two three four five it's going to give us a green lines right here so yeah that was our basic form validation in react.js.
4:54:21
Hola chicos, Hussain y Walker canal de YouTube, así que en este video vamos a crear este proyecto usando solo react.js, lo que significa que no vamos a usar ningún backend
Hey guys Hussain and Walker YouTube channel so in this video we're going to be creating this project by just using react.js which means like we're not going to be using any backend
4:54:30
servicios como mongodb mongoose y
services like mongodb mongoose and
4:54:33
expressjs y todas esas cosas buenas, pero
expressjs and all of that kind of good stuff but
4:54:36
en lugar de eso, vamos a construir este proyecto usando
instead we are going to be just building this project by just using
4:54:39
reactjs, así que este no es un gran proyecto para ser
reactjs so this is not a huge project to be
4:54:42
honestos, pero vamos a renderizar algunos componentes y
honest but we are going to be rendering a few components and
4:54:45
vamos a aprender cómo podemos hacer un filtrado
we are going to be learning about how we can do a filtering
4:54:48
en reactjs, así que podemos filtrar elementos a través de búsqueda
in reactjs so like we can filter items through search
4:54:52
y también podemos filtrar a través de estos botones aquí y también estos, eh, ¿cómo los llamamos? botones de radio personalizados
and we can also filter through these buttons right here and also these uh what do we call it custom radio buttons
4:54:59
y todo ese tipo de cosas, así que déjame mostrarte de qué se trata este proyecto
and all of that kind of stuff so let me just show you what this project is
4:55:02
así que supongamos que quiero buscar un producto específico
all about so let's suppose if i want to search for a specific product
4:55:06
como no sé, voy a buscar este, así que si solo escribo
like i don't know i'm going to search for this one so if i just type
4:55:09
nike, así que voy a escribir como nike, así que aquí puedes ver que no usará todos los productos que nike tiene, así que voy a escribir un espacio y luego voy a escribir para zoom
nike so i'm going to just write like nike so here you can see it will not use all of the products right here which nike has so i'm going to just write space and then i'm going to just write for zoom
4:55:21
y aquí puedes ver que ahora nos da este producto específico que estoy buscando, ¿de acuerdo?
and here you can see it will now gives us this specific product which i'm searching for okay
4:55:25
así que voy a borrar eso y aquí puedes ver que ahora nos da sus productos una vez
so i'm going to just clear that and here you can see it will now gives us their products once
4:55:29
más, y ahora si hago clic en este nike y
again and now if i just click on this nike and
4:55:32
aquí puedes ver que ahora nos da todos los productos que nike tiene
here you can see it will now gives us all of the products which nike has
4:55:35
y ahora si hago clic en, y por cierto, todos estos datos son totalmente
and now if i click on and by the way all of this data is totally
4:55:38
aleatorios y no son específicos de nike y edidas, y puedes proporcionar productos específicos para ellos, pero para
random and they aren't specific nike and edidas and you can provide a specific products for them but for
4:55:45
mí, solo puse imágenes aleatorias de zapatos y sandalias
me i just put a random images of shoes and sandals
4:55:49
y cosas, así que encontrarás un enlace en la descripción
and stuff okay so you will find a link in the description
4:55:52
abajo, si haces clic en él, te llevará a mi repositorio de gmail
below if you click on it it will bring you to my gmail repository
4:55:55
y puedes descargar todo el código o puedes
and you can download all of the code or you can
4:55:58
descargar su archivo db.js y
download their um db.js file and
4:56:01
entonces puedes obtener todas esas matrices de datos, ¿de acuerdo? así que si hago clic en este editar, ahora nos dará todos los productos de edds y una vez más, todos estos productos son totalmente aleatorios, como si ni siquiera supiera los nombres de estos
then you can grab like all of that arrays of data okay so if i just click on this edit as it will now give us all of the products of edds and once again all of these products are totally random like i don't even know the names of these
4:56:13
y aquí puedes ver que solo especificamos la cantidad de estrellas que
and here you can see we just specified the amount of stars they
4:56:17
obtienen y también las reseñas que obtienen y el
get and also the reviews they get and the
4:56:20
precio anterior y el nuevo precio y puedes cambiar eso como quieras, y también te mostraré cómo puedes proporcionar esa funcionalidad en
previous price and the new price and you can change that however
4:56:23
esta aplicación también, si haces clic en la furgoneta, no usará todos
you want and i'm going to also show you how you can provide that functionality in
4:56:27
esta aplicación también si haces clic en la furgoneta, así que no usará todo
this app as well if you click on the van so it will not use all
4:56:30
del producto que tienen estas furgonetas, está bien, así que este es el segundo filtrado, este es el primero, este es el segundo filtrado, déjame hacer clic en todos los productos aquí y aquí, aquí puedes ver que ahora nos dará todos los productos.
of the product which these vans have okay so this is the second filtering this is the first one this is the second filtering let me just click on this all products right here and here here you can see it will now gives us all of the products.
4:56:41
Si haces clic en este todos una vez más, aquí puedes ver que ahora nos dará todos estos productos.
If you click on this all one more time, so here you can see it will now gives us all of these products.
4:56:45
Si haces clic en las zapatillas, aquí puedes ver que solo nos dará sus zapatillas. Si haces clic en los planos, nos dará planos.
If you click on the sneakers, and here you can see it will just gives us their sneakers. If you click on the flats, it will gives us flats.
4:56:52
Si haces clic en las sandalias, nos dará estos zapatos. No son sandalias.
If you click on the sandals, and it will gives us these shoes. They aren't sandals.
4:56:58
Como dije, todos los datos son totalmente aleatorios, pero puedes especificar diferentes tipos de imágenes para las sandalias.
As I said, like all of the data is totally random, but you can specify like different kind of images for the sandals.
4:57:04
y también te voy a mostrar cómo puedes hacer eso si
and i'm going to also show you how you can do that if you
4:57:07
haces clic en los tacones, así que aquí puedes ver que no nos dará tacones y
click on the heels so here you can see it will not give us heels and
4:57:10
también puedes filtrar a través de diferentes tipos de precios como
you can also filter through different kind of prices like
4:57:13
si hago clic en esto, no nos dará todos estos productos
if i click on this all it will not give us all of these products
4:57:17
los cuales estos precios son como precios aleatorios
which these prices like random prices
4:57:20
tenemos si haces clic de cero a 50, eso
we have if you click on from zero through 50 it
4:57:24
nos dará todos sus productos que tienen este precio de 50, déjame hacer clic en 50 a 100, ahora nos dará
will give us all of their products which has this 50 uh what do we call a 50 price right here let me click on 50 through 100 it will now give
4:57:32
todos los productos que están entre 50 y 100 y
all of the products which are 50 through 100 and
4:57:35
tenemos 150 y también tenemos más de
we have 150 and we also have over
4:57:38
150, así que aquí puedes ver los precios y también puedes
150 so here you can see the prices and you can also
4:57:41
cambiar eso como quieras, está bien, así que
change that however you want all right so
4:57:44
eso es, ahora también puedes filtrar por los colores
that's that now you can also filter through the colors
4:57:47
si quieres, así que voy a hacer clic en todo y aquí puedes ver
if you want to so i'm going to just click on all and here you can see
4:57:50
cuando nos da todos los colores, pero si solo quiero obtener el color negro, voy a hacer clic en negro y aquí puedes ver que nos da todos estos colores negros y yo erróneamente
it when it gives us all of the colors but if i want to just get the black color i'm going to just click on black and here you can see it when it gives us all of these black color and i mistakenly
4:57:59
puse este aquí dentro de un color negro también. Pero de todos modos, eso también es increíble.
put this one right here inside a black color as well. But anyways that's also awesome.
4:58:05
También puedes cambiar eso si quieres y ahora voy a hacer clic en un azul.
You can also change that if you want to and now I'm going to click on a blue.
4:58:09
Ahora solo nos usará productos azules y ahora si haces clic en un rojo, solo nos usará productos rojos aquí.
It will now just use us blue products and now if you click on a red it will just use us red products right here.
4:58:13
Si haces clic en verde, solo nos usará estos productos verdes aquí.
If you click on green it will just use us these green products right here.
4:58:17
Y finalmente, si haces clic en un blanco, así que aquí puedes ver que ahora nos usará todos los productos blancos aquí.
And finally if you click on a white so here you can see it will now use us all of the white products right here.
4:58:22
Voy a hacer clic en este de todos los productos una vez más. Ahora nos dará todos estos productos aquí y así esto
I'm going to click on this all products one more time. It will now give us all of these products right here and so this
4:58:28
será una buena construcción y este proyecto te ayudará
will be a good build and this project will help you
4:58:31
a dominar diferentes tipos de técnicas en react js como diferentes
master different kind of techniques in react js like different
4:58:35
tipos de formas de filtrar a través de datos usando solo
kind of ways to filter through a data using just
4:58:38
react js así que no vamos a usar ningún redix
react js so we are not going to be using any redix
4:58:41
toolkit y todo ese tipo de cosas, pero solo vamos a usar
toolkit and all of that kind of stuff but we are going to be just using
4:58:44
uh react js y también react icons para estos íconos y no vamos a usar tampoco ningún um bootstrap
uh react js and also react icons for these icons and we are not going to be also using any um bootstrap
4:58:52
react bootstrap y tampoco vamos a usar lo que llamamos talento css y todo eso
react bootstrap and also we are not going to be using what do we call it talent css and all of
4:58:57
ese tipo de cosas para el estilo, voy a usar css solo un
that kind of stuff for styling i'm going to be using css just a
4:59:00
css puro si no quieres escribirlo, así que también puedes obtener
pure css if you don't want to write it so you can also get
4:59:03
todo el estilo de mi repositorio de gihub y por
all of the styling from my gihub repository and by
4:59:07
la forma en que todo el código estará disponible en el
the way all of the code will be available in the
4:59:10
descripción a continuación, solo tienes que hacer clic en ese enlace que te llevará a
description below you just have to click on that link which will bring you to
4:59:13
mi repositorio de gihub y allí puedes simplemente uh buscar a través de diferentes commits o también puedes obtener todo el código si quieres o si quieres seguir junto con este video
my gihub repository and there you can just uh search through different commits or you can also get all of the code if you want or if you want to follow along with this video
4:59:23
siéntete libre de hacerlo, regresa primero y solo voy a escribir código
feel free to do that go back first of all and i'm going to just write code
4:59:26
y luego solo voy a escribir filtrado avanzado y
and then i'm going to just write advanced filtering and
4:59:30
ahora voy a presionar enter, así que aquí puedes ver que ahora abrirá este proyecto
now i'm going to hit enter so here you can see it will now open this project
4:59:33
justo aquí dentro de esta ventana, está bien, así que voy
right here inside this window right here okay so i'm
4:59:36
a hacer un poco de zoom para que ustedes puedan ver todo un poco mejor
going to just zoom in a bit so that you guys can see everything a bit better
4:59:39
y voy a ocultar eso arriba de allí, está bien
and i'm going to just hide that up above from there all right
4:59:42
así que aquí puedes ver que mi barra lateral está justo aquí si te molesta
so here you can see my sidebar is right here if there annoys
4:59:46
así que puedes simplemente no sé, puedes hacer clic derecho sobre ella y enviarla justo aquí, sabes que voy a quedarme con esto porque para muchos desarrolladores eso sería preferido donde ir.
you so you can just i don't know you can just right click on it and send it right here you know i'm going to just stick with this because for a lot of developers that would be preferred where to go.
4:59:55
Y lo que haré es que voy a eliminar este archivo app.css
And what I will do is that I'm going to just remove this app.css file
5:00:00
y también este index.css y
and also this index.css and
5:00:03
no este archivo index.js, sino solo este
not this index.js file but just this
5:00:06
logo svgs y todo ese tipo de cosas malas, no
logo svgs and all of that kind of bad stuff not
5:00:09
cosas malas, para ser honesto, así que ahora voy a entrar y
bad stuff to be honest so now i'm going to just go inside and
5:00:13
voy a eliminar este jsx de aquí y
i'm going to remove this jsx from here and
5:00:16
voy a escribir h1, déjame escribir h1
i'm going to just write h1 let me just write h1
5:00:20
aquí de hola mundo aquí está bien y también voy a quitar este logo de arriba y también este archivo app.js o app.css.
right here of hello world right here okay and i'm going to also remove this logo from up above and also this app.js or app.css file.
5:00:29
Voy a quitar los web vitals de aquí y también el modo estricto de react.
I'm going to remove the web vitals from here and also the react strict mode as well.
5:00:36
Quita este y también este. Ahora voy a guardar mi archivo y lo que haré es cerrar este y solo escribir npm start para iniciar mi proyecto aquí.
Remove this one and also this one. Now I'm going to save my file and now what I will do is that I'm going to close this one out and I'm going to just write npm start to start my project right here.
5:00:46
Está bien, así que voy a esperar a que inicie mi proyecto. No lo hará. Está bien, ¿te gustaría ejecutar la aplicación en otro puerto?
Okay so I'm going to just wait for it to start my project. It will not. Okay would you like to run the app in another port?
5:00:53
Está bien, ya hemos abierto este, así que voy a cerrarlo en un momento.
Okay we've already opened this one so I'm going to just close that in a few
5:00:56
segundo, así que voy a cerrarlo en un segundo y luego volveré ahora.
second so i'm going to just close that in a second then i'll come back now
5:01:00
déjame cerrar eso, presiona ctrl c, ahora voy a usar npm.
let me just close that hit ctrl c now i'm going to just use npm
5:01:03
iniciar, así que ahora solo vamos a iniciar este proyecto aquí dentro de este.
start so we'll now just start this project right here inside this
5:01:07
ventana y lo que estamos viendo es este hola mundo aquí.
window and what we are seeing is this hello world right
5:01:10
aquí que hemos escrito dentro de este archivo app.js.
here which we've wrote inside this app.js file
5:01:13
aquí está bien, voy a cerrar este desde aquí, está bien, así que eso es lo primero que haría, voy a crear una carpeta aquí y le voy a dar un nombre como DB.
right here okay i'm going to just close this one right here from here all right so that's that the first thing which i would do is that i'm going to create a folder right here and And I'm going to just give a name of like DB.
5:01:24
Y dentro de esta carpeta DB, voy a crear un nuevo archivo. Le voy a dar un nombre como data.js.
And inside this DB folder, I'm going to just create a new file. I'm going to give a name of like data.js.
5:01:30
Y dentro de este archivo data.js, voy a agarrar muchas cosas. Así que solo voy a agarrar eso.
And inside this data.js file, I'm going to grab a lot of things. So I'm going to just grab that.
5:01:36
Y te voy a mostrar dónde puedes encontrar eso. Aquí puedes ver que tengo todos estos datos aquí dentro de este proyecto.
And I'm going to show you where you can find that. Here you can see I have all of this data right here inside this project.
5:01:41
Y puedes encontrar todos estos datos en mi repositorio de GitHub. Así que no es mucho.
And you can find all of this data in my GitHub repository. So it's not much.
5:01:46
Pero aquí puedes ver que solo estamos obteniendo este array de datos.
But here you can see we are just getting this data array.
5:01:49
y dentro de este array de datos tenemos solo unos pocos objetos aquí.
and inside this data array we have just a few objects right here
5:01:52
y estamos almacenando la propiedad de imagen y solo estamos especificando.
and we are storing the image property and we are just specifying
5:01:56
diferentes tipos de imágenes para ello y también estamos proporcionando.
different kind of images to it and we are also providing
5:01:59
un título para un producto específico y tenemos una estrella que es solo.
a title for a specific product and we have a star which is just
5:02:02
un ícono que vamos a instalar aquí y solo proporciono.
an icon which we are going to be installing right here and i just provide
5:02:05
una clase de estrella de calificación y aquí también puedes ver que tenemos reseñas y solo proporciono como uno, dos, tres, puedes proporcionar cuántos quieras, luego tenemos un.
a class of like rating star and here you can also see we have reviews and i just provide like one two three you can provide how many you want then we have a
5:02:14
precio anterior y el precio anterior es este o usado.
previous price and the previous price is this one or used
5:02:17
ser este y el nuevo precio es $200 o.
to be this one and the new price is $200 or
5:02:21
algo así y tenemos diferentes tipos de empresas como.
something like that and we have a different kind of companies like
5:02:24
Nike y tenemos, no sé, diferentes tipos de empresas
Nike and we have I don't know different kind of companies
5:02:27
como Vans y Puma y cosas así, y luego tenemos diferentes tipos
like Vans and Puma and stuff like that and then we have different kind
5:02:30
de colores y también diferentes tipos de categorías como zapatillas y tacones, y no sé, había muchas de ellas, así que lo que haría es copiar todo su contenido
of colors and also different kind of categories like sneakers and heels and I don't know there was a lot of them so what I would do is that I'm going to copy all of their content
5:02:41
y lo voy a colocar dentro de este proyecto aquí, así que solo voy a guardar
and i'm going to place it inside this project right here so i'm going to just save
5:02:44
este archivo y esto es un montón de elementos
this file and this is a lot of items
5:02:47
aquí y puedes especificar más si quieres
right here and you can specify more if you want to
5:02:50
y ahora solo voy a cortar este archivo data.js
and now i'm going to just cut this data.js file
5:02:54
aquí y voy a cerrar esta base de datos y qué más tenemos que
right here and i'm going to close this db and what else do we have to
5:02:57
hacer, lo primero que haría es crear una carpeta de componentes
do the first thing i would do is that i'm going to just create a components folder
5:03:00
donde vamos a almacenar nuestros componentes personalizados, lo verás en un segundo, así que solo voy a escribir componentes, ahí vamos, y vamos a crear algunos componentes aquí
where we are going to be storing just or custom components you'll see that just in a second so i'm going to just write components there we go and we are going to be creating a few components right here so
5:03:11
así que solo voy a escribir button.js y también voy a crear un
i'm going to just write button.js and i'm going to also create a
5:03:14
nuevo componente, le voy a dar un nombre como car.js, luego tenemos otro
new component i'm going to give a name of like car.js then we have another
5:03:17
que es input mayúscula input.js
one which is input uppercase input.js
5:03:20
ahí vamos y también estoy usando esta extensión car
there we go and i'm also using this extension car
5:03:24
déjame abrir esa extensión, uh, esta es7
let me just open that extension uh this es7
5:03:27
y react y redex, uh, así que déjame hacer clic ahí
and react and redex uh so let me just click on there
5:03:30
y también estoy usando esta extensión, si ustedes no saben sobre eso, uh, siéntanse libres de revisar mi curso de react.js o pueden simplemente buscar en Google como
and i'm also using this extension if you guys don't know about that uh so feel free to check on my react.js course or you can just click google search like
5:03:38
qué es esa extensión de la que estaba hablando, así que ahora voy
what is that extension I was talking about so now I'm going
5:03:41
a cerrar ahí y también voy a colocar esta declaración de importación
to just close there and I'm going to also place this import statement
5:03:44
aquí y déjame importarlo aquí, así que déjame
right here and let me just import it right here so let me just
5:03:47
acercar un poco para que puedan ver todo un poco mejor, voy a usar
zoom in a bit so you guys can see everything a bit better I'm going to use
5:03:50
RFC y solo voy a cortar ahí
RFC and I'm going to just cut there
5:03:54
simplemente me gusta de esa manera, si quieres ponerlo aquí
I just like it that way if you want to put it right here
5:03:57
como esta declaración de importación aquí, así que siéntete libre de hacerlo, pero en mi caso solo quiero trabajar con este tipo de estructura
like this import statement right here so feel free to do that but in my case I just kind of want to work with this kind of structure
5:04:03
así que me gusta esta estructura, prefiero esta estructura, uh
so i like this structure i prefer this structure uh
5:04:07
y sí, puedes elegir como declaración de exportación solo en una línea
and yeah you can choose like export statement just in one liner
5:04:10
pero en mi caso voy a usarlo así y ahora estoy
but in my case i'm going to be using like this and now i'm
5:04:13
simplemente voy a escribir como rfc y voy a
going to just write like rfc and i'm going
5:04:16
eliminar eso, déjame copiarlo y voy a
to remove that let me just copy it and i'm going to
5:04:19
colocar esta entrada justo aquí en la parte inferior, así que ahora hemos creado con éxito este componente de tarjeta, componente de entrada y ese componente de botón, pero no lo vamos a usar ahora mismo, así que despídete de estos componentes
place this input right here at the bottom so now we successfully created this card component input component and that button component but we are not going to be using it right now so say goodbye to this components
5:04:31
carpeta justo aquí, así que ahora lo siguiente que vas a crear es
folder right here so now the next thing which you are going to be creating is
5:04:34
que vamos a crear una sección de navegación, luego
that we are going to be creating a navigation section then
5:04:38
vamos a crear una sección de productos, luego recomendados y dentro
we are going to be creating a product section then recommended and inside
5:04:41
ahí o no dentro, pero también vamos a crear una barra lateral
there or not inside but we are going to be also creating a sidebar
5:04:44
así que déjame crear una nueva carpeta, le voy a dar un nombre como
so let me just create a new folder i'm going to give a name of like
5:04:47
navegación, ahí vamos y ahora dentro de esta navegación, primero voy a crear un componente nav.js y voy a
navigation there we go and now inside this navigation i'm going to first of all create a nav.js component and i'm going to
5:04:55
también escribir como un nav.css aquí como
also write like a nav.css right here as
5:04:58
bueno, así que solo escribiré como ra o
well okay so i'll just write like uh ra or
5:05:02
rfce y voy a eliminar eso y
rfce and i'm going to remove that and
5:05:06
voy a escribir mi navegación justo aquí, está bien y
i'm going to just write my navigation right here okay and
5:05:09
también voy a importar mi css
i'm going to also import my css
5:05:12
dentro de este archivo una vez más también
inside this file one more time as well
5:05:15
así que solo iré un nivel y luego nav.css, así que
so i'll just go one level and then nav.css so
5:05:19
vamos a colocar todo nuestro css aquí dentro, así que
we're going to be placing all of our css inside here so
5:05:22
lo que haré es que voy a renderizar este componente en el navegador
what i I will do is that I'm going to render this component to the browser
5:05:25
así que solo lo usaré aquí, eliminar eso
so I'm going to just use it right here remove that
5:05:28
y voy a escribir un nav aquí, presiona
and I'm going to just write a nav right here hit
5:05:31
enter y ahora tomará este nav de la navegación
enter and it will now grab this nav from the navigation
5:05:34
componente justo aquí y también voy a cambiar su nombre a navegación
component right here and I'm going to also change the name of it to like navigation
5:05:38
ahí vamos, voy a presionar enter aquí y lo cerraré manualmente, así que ahora si guardas un archivo, aquí puedes ver que ahora solo estamos obteniendo nav aquí
there we go I'm going to hit enter right here and I'm going to close it manually so now if you save a file so here you can see we are now just getting nav right here
5:05:48
está bien, así que todo está funcionando como esperamos y
okay so everything is working the way we expect them to work and
5:05:51
sí, eso está bien, pero ¿qué más tenemos que hacer? tenemos que crear
yeah that's cool but what else do we have to do we have to create
5:05:54
otro componente u otra carpeta para
another component or another folder for
5:05:57
productos, así que solo voy a escribir productos dentro de estos productos
products so i'm going to just write products inside this products
5:06:00
voy a crear dos pilas, la primera será solo products.js
i'm going to create two piles the first one will be just products.js
5:06:04
y la segunda será products.css, así que las mismas cosas se aplicarán aquí también, elimínalas, voy a cortar este componente exportar productos, ahí vamos
and the second one will be products.css so the same things will apply right here as well remove them i'm going to cut this component export products there we go
5:06:17
y ahora también voy a importar esto, ¿cómo lo llamamos?
and now i'm going to also import this um what do we call
5:06:20
productos, no este, sino products.css
it products not this one but products dot css
5:06:23
ahí vamos, está bien, así que eso también está bien, pero
there we go okay so that's also cool but
5:06:26
ahora lo que haré es que voy a usar mis fragmentos de react
now what i will do is that i'm going to use my react fragments
5:06:29
porque voy a estar renderizando muchos componentes aquí y
because i'm going to be rendering a lot of components right here and
5:06:33
solo voy a usar productos, está bien, y eso
i'm going to just use products okay and it will
5:06:36
solo lo importará por defecto si estás usando un codificador de historias visual, así que eso va a ser increíble, así que aquí puedes ver que tenemos navegación y productos y probablemente
just import it by default if you're using a visual story coder so that's going to be awesome so here you can see we have navigation and products and you probably
5:06:43
conoces todas estas cosas y voy a cerrar este como
know all of this stuff and i'm going to close this one as
5:06:47
bueno, ahora déjame crear uno más que será recomendado, así que
well now let me just create one more which will be recommended so
5:06:50
recomendado, ahí vamos, r-e-c-o-m-e-n-d-e
recommended there we go r-e-c-o-m-e-n-d-e
5:06:54
ahí vamos, voy a copiar este nombre porque es
there we go i'm going to copy this one name because it's
5:06:57
un nombre algo largo, así que tenemos recommended.js
kind of a long name so we have recommended.js
5:07:01
y tenemos el archivo recommended.css, así que
and we have recommended.css file so
5:07:04
solo escribiré rfc, eliminaré eso, lo copiaré
i'll just write rfc remove there copy it
5:07:07
y luego tenemos un recomendar, oh
and then we have a recommend oh
5:07:11
vamos, recomendado, ahí
come on recommended there
5:07:14
vamos, también voy a obtener mi declaración de importación de
we go i'm gonna also get my import statement of
5:07:17
uh, déjame copiar este nombre, es un nombre algo largo para escribir, sabes a lo que me refiero, así que solo voy a escribir recommended.css
uh let me just copy this name it's kind of a long name to type you know what i'm saying so i'm gonna just write recommended.css
5:07:24
y también déjame agarrarlo de rickham, no de react, sino de recomendar, ah, r-e-c-o-m-e-n-d-e-d
and also let me just grab it from rickham not react down but recommend ah r-e-c-o-m-e-n-d-e-d
5:07:36
está bien, no me está ayudando en este caso, así que voy a tener que importarlo, importar recomendar
okay it's not helping me in this case so i'm going to have to import it import recommend
5:07:42
ahí vamos, recomendado, vamos desde
there there we go recommended come on from
5:07:46
subir de nivel y recomendarlo y tenemos recomendado
go up level and recommend it and we have recommended
5:07:49
así que voy a enviar mi archivo y aquí puedes ver que tenemos este recomendado, ¿verdad?
so i'm going to send my file and here you can see we have this recommended right
5:07:52
de todos modos, eso es genial, no sé por qué cerré este archivo, pero ahora déjame crear una barra lateral y dentro de esa barra lateral vamos a crear diferentes tipos de carpetas, así que voy a escribir
here anyway so that's cool i don't know why i just closed this file but now let me just create a sidebar and inside that sidebar we are going to be creating different kind of folders so i'm going to just write
5:08:03
barra lateral dentro de esta barra lateral voy a estar
sidebar inside this sidebar i'm going to be
5:08:06
creando diferentes tipos de carpetas dentro de esas carpetas que tenemos
creating different kind of folders inside that folders we are
5:08:09
tendremos diferentes tipos de categorías de componentes
going to be having different kind of categories of components
5:08:12
así que voy a escribir categoría y dentro de esta categoría
so i'm going to just write category and inside this category
5:08:15
voy a escribir categoría.css o
i'm going to just write category.css or
5:08:19
no solo css, js estaría bien, voy a copiarlos y también vamos a crear category.css, así que yo
not just css js would be fine i'm going to copy them and we are going to be also creating category.css as well so i will
5:08:27
solo escribiré rfc, quita eso y vamos, corta eso y categoría y sí, déjame tomar mi
just write rfc remove that and come on cut that and category and yep let me just grab my
5:08:38
gato, vamos, category.css
cat come on category dot css
5:08:42
ahí vamos, envía mi archivo, elimina ambos y
there we go send my file remove both of them and
5:08:46
ahora dentro de esta carpeta de barra lateral voy a crear una más
now inside this sidebar folder i'm going to be creating one more
5:08:49
carpeta y voy a darle un nombre como colores
folder and i'm going to just give a name of like colors
5:08:52
colores en mayúsculas, ahí vamos y dentro de esto
uppercase colors there we go and inside this
5:08:55
carpeta de colores, lo que haré es que voy a crear dos carpetas, una para componentes y otra será para estilos como colors.js
colors folder what i will do is that i'll going to be creating two folders or one component and one will be for styling like colors.js
5:09:02
y tenemos otro colors.css
and we have another colors.css is
5:09:05
ese color, sí, escribí un color ahí
that color yeah i i write a colors there
5:09:09
así que genial, de todos modos, voy a eliminar eso
we go so cool anyway so i'm going to just remove that
5:09:12
copia la declaración y luego tenemos colores
statement copy it and then we have colors
5:09:15
está bien, es un poco desafiante para escribir
okay it's kind of a little bit challenging for typing
5:09:19
y hablar, así que a veces es un poco
and talking so sometimes kind of it's
5:09:22
desafiante, así que voy a guardar mi archivo, eliminar
kind of challenging so i'm going to just save my file remove
5:09:25
ambos bien, así que déjame guardar ese archivo, déjame
both of them okay so let me just save that file let
5:09:29
crear una carpeta más dentro de ahí y le voy a dar un nombre de
me just create one more folder inside there and i'm going to give a name of
5:09:32
como precio y dentro de este precio le voy a dar un nombre
like price and inside this price i'm going to just give a name
5:09:35
de como precio.js precio.css
of like price.js price.css
5:09:38
ahí vamos, ahora déjame escribir rfc eliminar
there we go now let me just write rfc remove
5:09:42
eso y déjame cortarlo de aquí, darle un nombre de precio, déjame importar mi, uh, uno, vamos
that and let me just cut it from here give a name of price let me just import my uh one let's just go
5:09:51
un nivel arriba de price.css, ahí vamos y ahora vamos a eliminar, y ahora aquí puedes ver
one level up above price.css there we go and now let's just remove there and now here you can see
5:09:57
nuestra estructura de carpetas ahora está totalmente completa.
our folder structure is now totally complete.
5:10:00
Dentro de esta sección de navegación, primero que nada, voy a empezar desde JSX.
Inside this navigation section, first of all, I'm going to start from JSX.
5:10:05
Así que solo escribiré navegación como la etiqueta de navegación.
So I'll just write navigation as the navigation tag.
5:10:10
Y dentro de esta navegación, solo escribiré un div con la clase de contenedor nav. Porque vamos a colocar nuestra entrada dentro del contenedor.
And inside this navigation, I'm going to just write a div with the class of nav container. Because we are going to be placing our input inside the container.
5:10:17
Y como tipo se establecerá en texto. Vamos a cambiar eso.
And as a type will be set to text. We are going to be changing that.
5:10:21
y también nos ocuparemos de eso en el evento on change
and we are going to be also taking care of that on change event
5:10:24
manejador y cosas más adelante, pero en esta sección
handler and stuff later on but in this section
5:10:27
ingresa tu búsqueda búsqueda
enter your search search
5:10:30
uh, los zapatos estarán bien
uh shoes will be fine
5:10:33
está bien, eso es genial, pero también le voy a dar una clase de
all right that's cool but i'm going to also give a class of
5:10:36
algo así para estilizarlo, le voy a dar una clase
something like to style it i'm going to just give a class
5:10:39
nombre de como elemento de búsqueda o entrada de búsqueda estaría bien, así que eso será para este div y dentro
name of like search item or search input would be fine rather okay so that's going to be for this div and inside
5:10:46
de este div solo ponemos nuestra etiqueta de entrada aquí y ahora
this div we just put or input tag right here and now
5:10:49
debajo de este div lo que tenemos que hacer es que tenemos que crear otro
underneath this div what we have to do is that we have to create another one
5:10:53
así que será un contenedor de perfil, así que esto es un poco un
so which will be a profile container so this is kind of a
5:10:56
inútil, pero hey, también lo vamos a poner y
useless one but hey we are going to be also putting it and
5:10:59
olvidé instalar los íconos de react, aquí vamos a usar íconos
i forgot to install react icons here we are going to be using icons
5:11:02
así que solo crearé una nueva terminal, voy a abrir una nueva terminal y solo usaré npm install, si pueden verlo, npm, vamos hombre, lo que haré es que
so i'll just create a new terminal i'm going to open new terminal and i'm going to just use npm install if you guys can see it npm come on man what i will do is that
5:11:14
déjame volver para que puedan verlo, voy a
let me just go back so you guys can see it i'm going to
5:11:17
simplemente arrastrarlo aquí y decirle adiós a este
just drag it right here and say goodbye to this one
5:11:20
ahora déjame acercar un poco, así que voy a instalarlo usando
now let me just zoom in a bit so i'm going to just install it by using
5:11:23
esta terminal de PowerShell, voy a usar npm install react react
this power shell i'm going to use npm install react react
5:11:27
iconos, bien, presiona enter para que instalemos
icons okay hit enter so we'll just install
5:11:30
en unos segundos, bien, así que aquí pueden ver que
in a few seconds all right so here you can see we
5:11:34
hemos instalado con éxito estos iconos de react, así que voy a cerrar esta terminal de PowerShell y ahora lo primero que tienes que hacer es que vas a
successfully installed this react icons so i'm going to just close this power shell and now the first thing that you have to do is that you're
5:11:40
agarrar algunas fuentes, así que solo voy a agarrar como
going to be grabbing a few fonts so i'll just grab like
5:11:43
fi y luego corazón y voy
fi and then heart and i'm
5:11:46
a importarlo primero como fi
going to just import it first of all as fi
5:11:50
corazón, un nombre bastante horrible de react
heart kind of awful name from react
5:11:53
um iconos y vamos a agarrar este de fi y también necesitamos importar estas fuentes que son ai minúscula i
um icons and we are going to be grabbing this one from fi and we would also need to import these fonts which is ai lowercase i
5:12:04
y luego tenemos contorno y
and then we have outline and
5:12:08
luego tenemos carrito de compras y
then we have shopping cart and
5:12:11
luego tenemos ai contorno usuario ad
then we have ai outline user ad
5:12:15
bien, así que voy a agarrar eso de react icons
okay so i'm going to just grab that from react icons
5:12:18
y voy a ai, así que voy a
and go to ai so i'm going to
5:12:21
vender mi archivo y lo voy a usar aquí, así que aquí
sell my file and i'm going to use it right here so here
5:12:24
pueden ver que tenemos esta primera etiqueta de anclaje aquí, la voy a usar aquí, así que tenemos fi corazón, bien, solo voy a usarlos y voy a cerrarlo no
you can see we have this first anchor tag right here i'm going to use it right here so we have fi heart okay i'm going to just use them and i'm going to close it not
5:12:34
así, pero solo déjame escribir una barra diagonal y
like that but just let me write a forward slash and
5:12:37
aquí lo que haré es que voy a darle una clase de nav
here what i will do is that i'm going to just give a class of nav
5:12:40
y también iconos también y
and also icons as well and
5:12:43
ahora déjame guardar eso debajo de esta etiqueta de anclaje, voy a
now let me just save that underneath this anchor tag i'm going
5:12:46
crear una etiqueta de anclaje más y no irá a ningún lado y
to create one more anchor tag and it will go to nowhere and
5:12:50
dentro de ahí lo que haré es que voy a usar mi ai contorno
inside there what i will do is that i'm going to use my ai outline
5:12:53
editar usuario o cualquier tipo de fuente que tengas, está bien, así que ahora voy a añadir allí, solo voy a escribir, uh, supongo que esto no debería ser una edición de usuario, pero
user edit or whatever kind of font you have okay so now i'm going to add there i'm going to just write uh i guess this shouldn't be a user edit but it
5:13:02
debería tener un carrito de compras, ahí vamos, y voy a
should have to be a shopping cart there we go and i'm going to
5:13:05
también proporcionar un grupo como íconos de navegación, está bien, así que
also provide a cluster like nav icons okay so
5:13:08
voy a duplicarlos y ahora voy
i'm going to just duplicate them and now i'm going
5:13:11
a cambiar el nombre de este ícono a usuario de esquema de IA
to change this icon name to ai outline user
5:13:14
editar, ahí vamos, está bien, así que si voy a ninguna parte
edit there we go okay so if i go to nowhere
5:13:18
voy a escribir una barra diagonal hacia la derecha
i'm going to just write a forward slash right
5:13:21
aquí y voy a guardar mi archivo y qué estamos
here and i'm going to save my file and what are we
5:13:24
obteniendo, está bien, el carrito de compras de esquema de IA no está definido
getting okay ai outline shopping cart is not defined
5:13:27
vamos a los íconos de react, todos
let's go to the react icons all
5:13:30
así que aquí puedes ver que tenemos estos íconos de react aquí, estoy
right so here you can see we have this react icons right here i'm
5:13:34
simplemente buscando un carrito de compras, ahí vamos
going to just search for a shopping cart there we go
5:13:37
y ahora déjame tomar eso y voy a
and now let me just grab that and i'm going to
5:13:40
ponerlo aquí, está bien, así que el nombre era totalmente
put it right here okay so name was totally
5:13:43
horrible y el segundo que tenemos es, uh, yo
awful and the second one we have is uh i
5:13:47
no sé, esquema de usuario editar o algo así
don't know outline user edit or something like that
5:13:50
uh, supongo que este estaría bien, así que
uh i guess this this one would be fine so so
5:13:53
voy a hacer clic en él y lo voy a colocar aquí, guardar mi archivo
i'm going to just click on him and i'm going to place it right here save my file
5:13:56
y ahora déjame verificar cómo y tenemos, está bien
and now let me check how and we have okay
5:13:59
así que solo estoy escribiendo meta, voy a copiarlo de allí y
so i'm just meta type i'm going to copy it from there and
5:14:03
voy a colocarlo aquí, guardar mi archivo y aquí puedes ver que ahora estamos
i'm going to place it right here save my file and here you can see we are now
5:14:06
obteniendo estos íconos y tenemos esta caja de importación
getting these icons and we have this import box
5:14:09
aquí, está bien, así que ahora déjame proporcionar un poco de estilo a esto, así que
right here all right so now let me just provide a little bit of styling to it so
5:14:12
voy a cerrar este y dentro de este src lo que yo
i'm going to just close this one and inside this src what i
5:14:15
haré es que voy a crear un archivo index.css solo para una investigación, así que lo que haré es que voy a proporcionar diferentes tipos de investigación, puedes avanzar rápido si quieres, así que voy a proporcionar margen
will do is that i'm going to just create index.css file for just a research so what i will do is that i'm going to just provide different kind of research you can fast forward if you want to so i'm going to just provide margin
5:14:28
el tamaño de la caja se establecerá en totalmente caja de fuente
box sizing will be set to totally board box font
5:14:31
la familia de fuentes se establecerá en serif y vamos a seleccionar
family will be set to send serif and we are going to be selecting
5:14:34
todas nuestras etiquetas de anclaje y la decoración del texto se establecerá ahora en ninguno
all of our anchor tags and text decoration will be now set to none
5:14:37
y color uh voy a pasar como
and color uh i'm going to just pass like
5:14:40
rgb de cero no cero sino 97 si
rgb of zero not zero but 97 if
5:14:44
puedo obtener 97 voy a copiar eso y colocarlo dos veces así que voy a eliminar esa coma de abajo y ahora voy a seleccionar cada
i can get 97 i'm going to copy that place it two times so i'm going to remove that comma from from the bottom and now i'm going to select every
5:14:52
aliado que tenemos dentro de esta aplicación y voy a eliminarlos como el tile de lista será solo eliminar y luego voy a crear esta clase de botones para
ally which we have inside this app and i'm going to just remove them like the list tile will be just remove and then i'm going to be creating this buttons class for
5:15:01
botones más tarde una vez que vayamos a saltar a los botones así que
later buttons once we are going to be jumping into the buttons so
5:15:04
vamos a usar esta clase y eso sería magia
we are going to be using this class and that would be magic
5:15:07
así que voy a proporcionar un fondo transparente y
so i'm going to just provide a background of transparent and
5:15:11
luego tenemos un borde voy a establecer eso en ninguno y
then we have a border i'm going to set that to none and
5:15:14
borde de 0.6 píxeles sólido y totalmente ccc solo un borde más claro y también voy a proporcionar un radio de borde no este sino el radio de borde
border 0.6 pixels solid and totally ccc just a lighter border and i'm going to also provide a border radius not this one but border radius
5:15:24
se establecerá ahora en cinco píxeles y luego tenemos un color de
will be now set to five pixel and then we have a color of
5:15:28
uh tres tres dos tres dos tres
uh three three two three two three
5:15:31
dos una vez más está bien así que este va a ser el color y cursor
two one more time okay so this is going to be the color and cursor
5:15:34
será un puntero no vamos a usar este rebote no correcto
will be a pointer we are not going to be using this bounce not right
5:15:37
ahora y luego tenemos que ir a
now and then we have to go to
5:15:40
en este archivo nav.css déjame resaltar
in this nav.css file let me just highlight
5:15:43
esto voy a entrar en este archivo nav.css voy a hacer clic en ellos y voy a comenzar desde la navegación primero voy a seleccionar esta navegación
this i'm going to just go inside this nav.css file i'm going to click on them and i'm going to just start from the navigation first of all i'm going to be selecting this navigation
5:15:53
contenedor justo aquí así que voy a seleccionar eso y
container right here okay so i'm going to just select that and
5:15:56
voy a proporcionar una visualización de totalmente flex y borde para
i'm going to provide display of totally flex and border for
5:15:59
no el radio de borde sino el borde para la parte inferior voy a
the not border radius but border for the bottom i'm going
5:16:02
proporcionar dos píxeles de sólido f3 f3
to provide two pixel of solid f3 f3
5:16:05
f3 así que este va a ser el color que voy a proporcionar justificar
f3 so this is going to be the color which i'm going to be providing justify
5:16:08
el contador se establecerá ahora en espacio sí
counter will be now set to space yeah
5:16:11
el espacio alrededor estaba totalmente bien y la alineación de los elementos estaba totalmente centrada y también voy a proporcionar un poco de padding por todos lados y
space around was totally fine and align items was totally set to center and i'm going to also provide a little bit of padding all around and
5:16:19
entonces tenemos un índice z de 999 porque
then we have a z index of 999 because
5:16:22
vamos a usar una visualización de lo que llamamos una visualización de
we are going to be using a display of what do we call a display of
5:16:25
flex así que ahora déjame escribir un margen de dos píxeles
flex so now let me just write margin of two pixel
5:16:29
y ahora déjame guardar eso y aquí puedes ver
and now let me just save that and here you can see
5:16:32
ahora solo estamos obteniendo estos íconos aquí y
we are now just getting these icons right here and we
5:16:35
solo estamos obteniendo esta caja de entrada así que ahora déjame volver y
are just getting this input box so now let me just go back and
5:16:38
100 estará bien, así que puedes aumentar o disminuir si
100 will be fine okay so you can increase or decrease if
5:16:41
quieres, pero en mi caso eso va a estar totalmente bien, ahora déjame obtener todas las entradas que tenemos actualmente
you want to but in my case that's going to be totally fine now let me get all of the inputs which we currently have
5:16:48
déjame quitar esta de aquí y
let me just remove this one from here and
5:16:51
voy a proporcionar un padding de 12 píxeles que estará bien
i'm going to provide a padding of 12 pixel will be fine
5:16:54
y luego 20 píxeles y el borde que voy a quitar
and then 20 pixel and border i'm going to remove
5:16:58
todos los bordes de aquí y luego tenemos un fondo
all of the borders from here and then we have a background
5:17:01
de este um f7 uh
of this um f7 uh
5:17:04
f6 f vamos f6
f6 f come on f6
5:17:07
una vez más, así que luego tenemos el
one more time okay so then we have the
5:17:10
contorno de ninguno y luego tenemos un margen para la derecha
outline of none and then we have a margin for the right
5:17:13
de 20 píxeles y el radio del borde que voy a proporcionar es como cinco píxeles estará bien y la posición se establecerá totalmente relativa y el ancho será de 14 píxeles
of 20 pixel and border a radius i'm going to provide is like five pixel be fine and position will be set to totally relative and width will be 14 pixel
5:17:25
tipo de voz que acabo de hacer 14 ir
kind of voice i just made 14 go
5:17:30
de regreso, así que eso es genial y ahora déjame
back all right so that's cool and now let me just
5:17:33
obtener mis íconos de navegación que son todos estos íconos
get my nav icons which are all of these icons
5:17:36
a los que les proporcionamos estas clases, probablemente notaste eso, pero no sé por qué les mostré 1.5 para ram y luego más alto será 1.5 para ram
which we provide these classes to it you probably noticed that but i don't know why i showed them 1.5 for ram and then higher will be 1.5 for ram
5:17:46
y tenemos un margen para la izquierda y ahora se establecerá en dos
and we have a margin for the left and it will be now set to two
5:17:49
rems si guardas nuestro archivo y eso se ve más que
rems if you save our file and that's looking more than
5:17:52
increíble aquí puedes ver que tenemos nuestro campo de búsqueda de entrada y
awesome here you can see we have our input search field and
5:17:55
entonces tenemos esto, no sé por qué no especificamos el color, tenemos
then we have this i don't know why we didn't specify color to it we
5:17:59
que proporcionar algún tipo de color, uh, entrada
have to provide some sort of a color to it uh input
5:18:03
y olvidé incluir algún tipo de color para
and i forgot to include some sort of a color to
5:18:06
esto, de todos modos, lo cambiaremos más tarde, no tenemos que preocuparnos por eso, oh sí, podemos cambiarlo de inmediato, no
this anyways we will change that later we don't have to worry about that oh yeah we can change it right away not
5:18:14
entrada, pero íconos, déjame cambiar el color de ellos
input but icons let me just change the color of them
5:18:17
a no sé, sí
to i don't know yep
5:18:21
eso se ve bien, sí, está bien, eso está totalmente bien, así que
that's looking yeah that's fine that's totally fine so
5:18:24
esta es nuestra primera sección de navegación, así que eso fue
this is our first navigation section so that was
5:18:28
lo que hay sobre esta sección de navegación, así que lo siguiente que tienes que hacer es
it about this navigation section so the next thing which you have to do is
5:18:31
que tenemos que saltar a esta sección de productos y este producto
that we have to jump into this product section and this product
5:18:34
la sección será responsable de todos los productos donde vamos
section will be responsible for all of the products where we
5:18:37
a renderizar todos nuestros productos dentro de los
are going to be rendering all of our products inside the
5:18:40
tarjetas y cosas, así que más tarde vamos a crear
cards and stuff so we later we are going to be creating
5:18:43
un componente para tarjetas, pero para este caso estamos
a component for cards but for this case we are
5:18:46
simplemente renderizando algunos elementos, así que
going to be just uh rendering a few items so
5:18:50
voy a escribir una sección aquí y les voy a dar una cláusula de como
i'm going to just write a section right here and i'm going to just give them a clause of like
5:18:53
contenedor de tarjetas, uh, c-n-t-i-n-e-r
card container uh c-n-t-i-n-e-r
5:18:56
a veces cometo muchos errores, así que por eso estoy
sometimes i made a lot of mistakes so that's why i'm
5:18:59
simplemente revisando estas ortografías, muy bien, así que esa es la
just double checking these spellings all right so that's the
5:19:02
sección de tarjetas, así que lo siguiente que tienes que hacer es que tenemos que crear una sección para una tarjeta, así que ahora dentro de esta sección de tarjeta tenemos
card section so the next thing which you have to do is that we have to create a section for a card so now inside this card section we have
5:19:09
que renderizar nuestra imagen, así que para este caso voy a ir a mi
to render our image so for this case i'm going to go to my
5:19:13
base de datos aquí, mi base de datos, mi
database right here my database my
5:19:16
archivo db, así que voy a copiar esta imagen de aquí y
db file so i'm going to just copy this image from here and
5:19:19
voy a colocar esa imagen aquí como texto alternativo, voy a
i'm going to just place that image right here as alternative text i'm going
5:19:22
escribir como un zapato y ahora debajo
to just write like a shoe and now underneath
5:19:26
que tenemos que hacer, también tenemos que crear un componente
that what do we have to do we also have to create a component
5:19:29
o no un componente, sino detalles de la tarjeta
or not a component but card details
5:19:32
sección y ahora dentro de esta sección de detalles de la tarjeta voy a escribir h3 del título de la tarjeta, también le daré mi
section and now inside this card details section i'm going to just write h3 of the card title i'm going to also give my
5:19:39
clase de título de tarjeta y ahora solo voy a
class of like card title and now I'll just
5:19:42
poner algún tipo de título como no sé, zapato y ahora
put some sort of a title like I don't know shoe and now
5:19:45
debajo de eso, también voy a proporcionar un tipo diferente de sección, eh, no un tipo diferente de sección, sino solo una sección con la clase de reseñas de tarjeta r-e-v-i-e-w-s, ahí vamos
underneath there I'm going to also provide different kind of section uh not different kind of section but just a section with the class of card reviews r-e-v-i-e-w-s there we go
5:19:57
y ahora dentro de las reseñas de esta tarjeta, vamos a tener una sección de reseñas de tarjeta
and now inside this card's reviews we're going to have a section of card reviews
5:20:00
tenemos que hacer, tenemos que obtener o empezar, así que voy
we have to do we have to get or start so i'm
5:20:03
a hacer clic aquí y voy a escribir empezar, está bien
going to just click here and i'm going to just write start okay
5:20:06
así que déjame obtener este, supongo que este será
so let me just get this one i guess this one will be
5:20:09
bien, está bien, voy a copiar eso y lo voy a colocar
fine okay i'm going to copy that and i'm going to just place it
5:20:12
justo aquí y así, y ahora
right here and like so and now
5:20:15
qué tenemos que hacer, tenemos que también obtenerlo de
what do we have to do we have to also grab it from
5:20:18
o componentes de react, así que no un componente de react, sino de
or react components so not react component but from
5:20:22
iconos de react, así que voy a escribir de y luego react
react icon so i'm going to just write from and then react
5:20:25
iconos y ahora voy a ir a la IA
icons and now i'm going to go to the ai
5:20:28
está bien, así que ahora si vendes nuestro archivo aquí, puedes ver que ahora estamos obteniendo
okay so now if you sell our file here you can see we are now getting
5:20:31
nuestro zapato, estamos obteniendo el título y también estamos obteniendo nuestro
our shoe we are getting the title and we are also getting our
5:20:34
estrella, pero necesitaríamos cuatro estrellas para este, así que
star but we would need four star for this one so
5:20:37
uno, dos, tres, cuatro, y ahora si vendes eso aquí
one two three four and now if you sell that here
5:20:41
puedes ver que ahora estamos obteniendo cuatro estrellas justo aquí, está bien, así que eso es
you can see we are now getting four stars right here okay so that's
5:20:44
genial también y también voy a proporcionar un span de reseña total, así que solo daré un nombre como, no un nombre, sino una clase
cool as well and i'm going to also provide a span of total review so i'll just give a name of like not name but class
5:20:50
de reseñas totales y ahora solo voy a
of total reviews and now i'm going to just
5:20:53
poner como, no sé, cinco reseñas o cuatro reseñas estaría bien, está bien
put like i don't know five reviews or four reviews would be fine okay
5:20:57
así que debajo de esta sección, lo que tenemos que hacer, tenemos que
so underneath this section what we have to do we have to
5:21:00
crear una nueva sección con la clase de tarjeta y luego
create a new section with the class of card and then
5:21:03
precio y ahora dentro de este precio de tarjeta tenemos que poner orden
price and now inside this card price we have to put order
5:21:06
precio aquí está bien y ahora dentro de este precio vamos
price right here okay and now inside this price we
5:21:09
a escribir nuestro dell y vamos a renderizar algunos tipos diferentes de precio como no sé trescientos dólares serían tres
are going to be writing our dell and we are going to be rendering some like different kind of price like i don't know three hundred dollars would be three
5:21:18
cientos de dólares estarían bien así que ese precio es
hundred dollars would be fine so that price is
5:21:21
obsoleto ahora tenemos que agregar un nuevo precio así que voy
deprecated now we have to add a new price so i'm going
5:21:24
a simplemente agregar un nuevo precio de como doscientos dólares o algo así y
to just add new price of like two hundred dollars or something like that and
5:21:27
déjame poner un dólar así que sabes que no vamos a agregar ningún dólar
let me just put a dollar so you know we're not going to be adding any dollar
5:21:31
signo y cosas así ahora déjame conseguir mi bolsa así que
sign and stuff like that now let me just get my bag so
5:21:34
voy a simplemente escribir bolsa y ahora tenemos que buscar una bolsa que creo que esta bolsa estará bien así que voy a oh sabes que esta estaría bien
i'm going to just write bag and now we have to just search for a bag bag which is i guess this bag will be fine so i'm going to oh you know like this one would be fine
5:21:45
copia eso voy a pegarlo aquí como
copy that i'm going to paste it right here like
5:21:49
componente de react menos que vamos menos
react component less than come on less
5:21:52
oh Dios mío signo menor que y ahora tenemos que agarrarlo de
oh my goodness less than sign and now we have to grab it from
5:21:55
un íconos de react así que solo escribiré importar
a react icons okay so i'll just write import
5:21:58
y luego obtener esto de react
and then get this from react
5:22:02
iconos barra bs así que ahora si guardas nuestro archivo y ahora déjame refrescar mi navegador para renderizar ese componente así que aquí puedes ver que este fue un
icons forward slash bs so now if you save our file and now let me just refresh my browser to render that component so here you can see this was a
5:22:11
precio anterior este es un nuevo precio tenemos cuatro reseñas
previous price this is a new price we have four reviews
5:22:14
y tenemos esto hacia atrás aquí así que ahora es hora de estilizar
and we have this backward here so now it's time to style
5:22:17
este componente y luego sí eso va a ser todo para el estilo
this component and then yeah that's going to be it for style
5:22:21
así que eso va a ser todo así que voy a simplemente entrar en este
so that's going to be it so i'm going to just go inside this
5:22:24
producto iniciar css y primero voy a seleccionar mi carro
product start css and i'm going to first of all select my car
5:22:28
contenedor así que solo escribiré una visualización de
container okay so i'll just write a display of
5:22:31
flex flex wrap ahora se establecerá en wrap el margen para la izquierda se establecerá ahora en 20 rim y ahora también proporcionaré un margen para la parte superior
flex flex wrap will be now set to wrap margin for the left will be now set to 20 rim and now i'm going to also provide a margin for the top
5:22:39
de 2 ram y también el índice z se establecerá ahora
of 2 ram and also the z index will be now set
5:22:42
en menos dos aquí voy a seleccionar también
to minus two right right here i'm going to also select
5:22:45
mi tarjeta voy a proporcionar un margen de 20 píxeles y
my card i'm going to provide a margin of 20 pixel and
5:22:49
el borde ahora se establecerá no solo ven, ¿qué demonios más?
border will be now set not just come on what the hell more
5:22:52
será suficiente, vamos b-o-r-d-e-r será
will be enough come on b-o-r-d-e-r will
5:22:56
también será de dos píxeles sólido e-d-e-d-e-d está bien
be also to two pixel solid e-d-e-d-e-d okay
5:23:00
y también voy a proporcionar un relleno de 20 píxeles y el cursor será puntero y también voy a seleccionar la imagen de mi tarjeta.
and i'm going to also provide a padding of 20 pixel and cursor will be pointer and also i'm I'm going to just select my card image.
5:23:09
Está bien, ¿proporcioné un nombre de imagen de tarjeta? No lo hice. Así que déjame proporcionar una imagen de tarjeta.
Okay, so did I provide a card image name to it? I didn't. So let me just provide a card image.
5:23:16
Así que voy a guardar este archivo. También voy a guardar esto. Oh, ¿sabes qué? No voy a guardar este archivo ahora mismo.
So I'm going to save this file. I'm going to also save this. Oh, you know what? I'm not going to save this file right now.
5:23:21
Voy a proporcionar un ancho de 13 rems.
I'm going to provide a width of 13 rims.
5:23:26
Y también voy a proporcionar un margen para la parte inferior de un rem. Ahí vamos. Eso es genial. Y también voy a seleccionar el título de mi tarjeta.
And I'm going to also provide a margin for the bottom of one rim. There we go. That's cool. And I'm going to also select my card title.
5:23:34
y el margen para la parte inferior voy a proporcionar solo un rem
and the margin for the bottom i'm going to just provide one rem
5:23:37
también y ahora debajo de eso voy a seleccionar mi auto
as well and now underneath that i'm going to select my car
5:23:40
reseñas ahí vamos reseñas déjame
reviews there we go revi ews let
5:23:44
solo verificar a veces cometí muchos
me just double check sometime i made a lot
5:23:47
errores tipográficos así que por eso estoy verificando dos veces, así que voy a proporcionar un margen
of typos so that's why i'm double checking it so i'm going to just provide margin
5:23:50
para la parte inferior como un rem estaría bien y también voy a
for the bottom like one rem would be fine and i'm going to also
5:23:53
proporcionar una visualización totalmente flexible y debajo de eso voy a seleccionar mi estrella de calificación que olvidé incluir pero lo haremos
provide a display of totally flex and underneath that i'm going to be selecting my rating star which i forgot to include but we will
5:24:01
proporcionar diferentes tipos de colores para ello, como el color amarillo
provide different kind of colors to it so like yellow color
5:24:04
definir d5 a b55 esto
define d5 a b55 this
5:24:08
va a ser el color que voy a usar para una estrella, voy a
is going to be the color which i'm going to be using for a star i'm going to
5:24:11
copiar esta clase de aquí y olvidé incluir
copy this class from here and i forgot to include
5:24:14
aquí porque, eh, vamos a
it right here because uh we are
5:24:17
poner todos estos íconos dentro de nuestro archivo de datos
going to be putting all of these icons inside our data file
5:24:21
ya lo tenemos, pero nos ocuparemos de eso más tarde
we already have that but we will take care of that later
5:24:24
en la sección de refactorización, así que ahora dejemos solo eliminar, eh
in the refactor section so now let just remove uh
5:24:27
las cosas de aquí como
the stuff from here like
5:24:31
así que y solo proporcionamos este armario para ello, sí, eso es
so and we just provide this closet to it yep that's
5:24:34
genial, guarda mi archivo y ahora voy a actualizarlo y
cool save my file and now i'm going to refresh it and
5:24:37
no sé por qué no está funcionando, eso es porque no importamos
i don't know why it's not working that's because we didn't import
5:24:41
correctamente, supongo que sí lo importamos
it correctly i guess we did import it
5:24:44
pero no sé qué está pasando, simplemente actualicemos nuestro navegador
but i don't know what's going on let's just refresh our browser
5:24:47
por qué no está funcionando, sí, eso es porque no guardamos este archivo, así que tenemos que guardarlo y aquí puedes ver que tenemos nuestro zapato recomendado y tenemos este cartón aquí.
why it's not working yep that's that's because we didn't save this file so we have to save it and here you can see we have our recommended shoe and we have we have this cardboard here.
5:24:57
Está bien, así que ahora eso es genial. Tenemos estos colores amarillos y nos ocupamos de todos ellos.
Okay, so now that's cool. We have this yellow colors and we take care of all of them.
5:25:02
Ahora, déjame encargarme de sus reseñas totales, que son estas reseñas totales.
Now, let me just take care of their total reviews, which is this total reviews.
5:25:09
¿Dónde está eso? Reseñas totales. Muy bien, ahí vamos. Así que nos vamos a encargar de eso, y solo voy a proporcionar un tamaño de fuente de 0.9
Where is that? Total reviews. All right, there we go. So, we are going to be taking care of that, and I'm going to just provide a font size of 0.9
5:25:18
rem recto, y también voy a proporcionar un margen para la izquierda de 10 píxeles.
rem straight, and I'm going to also provide a margin for the left of 10 pixel.
5:25:22
Está bien, así que entonces solo voy a escribir el precio de la tarjeta
Okay, so then I'm going to just write card price
5:25:26
y la visualización será totalmente flexible y justificará el contenido
and display will be totally flexed and justify content
5:25:29
se establecerá ahora en espacio alrededor y
will be now set to space around and
5:25:32
y alinear elementos se establecerá ahora en
and align items will be now set to
5:25:35
centro, está bien, así que finalmente tenemos que ocuparnos de esta bolsa
center okay so finally we have to take care of this bag
5:25:38
uh, no esta bolsa, pero tenemos que ocuparnos
uh not this bag but we have to take care
5:25:42
de, déjame proporcionar una clase de ícono de bolsa o ícono, solo un singular, voy a guardar este archivo y tenemos que obtener ese ícono justo aquí
of let me just provide a class of bag icon or icon just a singular i'm going to save this file and we have to get that icon right here
5:25:52
y solo tenemos que proporcionar un color de 535353
and we just have to provide a color of 535353
5:25:56
así que si vendes un archivo, déjame guardarlo y aquí puedes
so if you sell a file let me just save it and here you can
5:25:59
ver, así es como se verá nuestro componente justo aquí, así que podemos duplicar
see this is how our component will look like right here so we can duplicate
5:26:02
ese componente una y otra vez, así que déjame volver
that component again and again so let me just go back
5:26:06
así que ustedes pueden ver todo un poco mejor, voy a simplemente
so you guys can see everything a bit better i'm going to just
5:26:09
seleccionar esta sección justo aquí y voy a
select this section right here and i'm going to
5:26:12
simplemente proporcionar un poco de elementos a ello, así que voy a duplicar eso, no tienes
just provide a little bit of items to it so i'm going to just duplicate that you don't
5:26:15
que hacer eso, no tienes que hacer eso, pero aquí puedes ver que todos mis elementos estarán colocados justo aquí, déjame seleccionar todos los
have to do that you don't have to do that but here you can see all of my items will be placed right here let me just select all of
5:26:21
estos elementos, uh, a través de aquí solo quiero
these items uh through here i just kind
5:26:24
mostrarles cómo se verán todos mis elementos como duplicados
of want to show you like how all of my items will look like duplicate
5:26:27
ahí y ahora déjame refrescar mi navegador y aquí puedes
there and now let me just refresh my browser and here you
5:26:30
ver cómo se verán todos mis productos, ¿verdad?
can see this is how all of my products will look like right
5:26:34
aquí está bien y todo está funcionando como esperamos
here okay and everything is working like the way we expect them
5:26:37
que funcione, todo está bien, pero ahora
to work everything is a-okay but now
5:26:40
tenemos que refactorizar, no vamos a refactorizar nuestro código, no ahora, uh, pero refactorizaremos todo nuestro código más tarde, pero solo quiero
we have to refactor we are not going to be refactoring our code not right now uh but we will refactor all of our code later but i just kind of want to
5:26:48
renderizar algunos elementos para que podamos ver algo primero que nada y
render some items so that we can see something first of all and
5:26:51
sí, y eso será todo por esta
yeah and that's going to be it for this
5:26:54
sección y una vez más vamos a refactorizar todo
section and once again we are going to be refactoring all of
5:26:58
este código al final de este valor, no al final, sino
these code at the end of this value not at the end but just
5:27:01
en unos segundos, pero uh, tenemos que ocuparnos de los
in a few seconds but uh we have to take care of the
5:27:04
otros asuntos, pero no podemos trabajar con todos a la vez, tendremos que ocuparnos de ellos uno por uno, así que vamos a eliminar todo este jsx de aquí y solo vamos a proporcionar un resultado
other stuff but we cannot work with them all at once we'll have to take care of them one by one so we are going to be removing all of these jsx from here and we are going to be just providing a results
5:27:15
solo una variable de resultados y eso será todo, prometo que
just results variable and that's going to be it i promise we
5:27:19
vamos a eliminar todo este jsx de aquí de todos modos
are going to remove all of these jsx from here anyway
5:27:22
así que esa es la sección de productos, muy bien, así que eso fue un producto
so that's the product section all righty so that was a product
5:27:25
sección, así que voy a cerrar ambos desde aquí y
section so i'm going to just close both of them from here and
5:27:28
voy a ir a mis recomendados, así que voy a abrir mi
i'm going to go to my recommended so i'm going to just open my
5:27:31
recommended.js y también este css aquí
recommended.js and also this css right here
5:27:34
así que lo que haría es que voy a eliminar esta sección recomendada de aquí y déjame acercar un poco para que puedan ver
so what i would do is that i'm going to just remove this recommended section from here and let me just zoom in a bit so you guys can see
5:27:40
todo un poco mejor y lo que haré es que primero
everything a bit better and what i'll do is that i'm going to first
5:27:43
usaré mis fragmentos de react y luego usaré
of all using my react fragments and then i'm going to be using
5:27:46
mi div aquí y luego solo pondré algún tipo de título a
my div right here and then i'll just put some sort of a title to
5:27:49
esto como h2 de recome r-e-c-o-m-e-n-d-e-d
it like h2 of recome r-e-c-o-m-e-n-d-e-d
5:27:55
voy a copiar esto y lo voy a colocar justo
i'm going to copy this and i'm going to place it right
5:27:58
aquí y debajo de este h2 lo que haré es que voy a usar mis botones recomendados justo aquí está bien y ahora dentro de ahí vamos a colocar algunos botones así que solo escribiré botón
here and underneath this h2 what i'll do is that i'm going to use my recommended buttons right here okay and now inside there we are going to be placing a few buttons so i'll just write button
5:28:10
y no vamos a proporcionar nada o
and we are not going to be providing any stuff or
5:28:13
sabes que solo voy a dar una etiqueta como todos los productos
you know what i'm going to just give a label like all products
5:28:16
está bien, así que tenemos todos los productos, luego tenemos nike añadido s
okay so we have all products then we have nike added s
5:28:19
y puma los voy a quitar, voy a proporcionar nike
and puma i'm going to remove them i'm going to provide nike
5:28:22
o nike, algunas personas lo llaman nike y
or nike some people call nike and
5:28:26
algunas personas lo llaman nike, lo que sea, luego
some people call it nike whatever then
5:28:29
tenemos un puma y luego tenemos unas vans, ahí vamos, también voy a proporcionar un diferente
we have a puma and then we have a vans vans there we go i'm going to also provide a different
5:28:36
tipo de no diferente, pero vamos a proporcionar un grupo y
kind of not different but we are going to be providing a cluster and
5:28:39
el grupo será solo botones
the cluster will be just buttons
5:28:42
justo aquí, veamos si guardamos nuestro archivo y tú
right here see if we save our file and you
5:28:45
no verás eso, no sé por qué no lo verás, déjame solo refrescar
will not see that i don't know why you will not see it let me just refresh
5:28:48
mi navegador y tienes que ver eso en algún lugar
my browser and you have to see that somewhere i
5:28:52
no sé por qué no está funcionando, arruinamos algo, apuesto a que sí, y sí, lo hicimos, está bien, estamos obteniendo esa sección recomendada justo aquí en la parte inferior, pero no deberíamos haberla leído aquí
don't know why it's not working we messed up something i bet and yep we did okay we are getting that recommended section right here at the bottom but we shouldn't have read it right here
5:29:03
voy a ir a mi aplicación y luego lo que haré es que voy a
i'm going to go to my app and then what i'll do is that i'm
5:29:07
simplemente colocar esta sección recomendada arriba de esto
going to just place this recommended section up above this
5:29:10
sección de producto o tipo de componente completo, así que voy a
product section or kind of whole component so i'm
5:29:13
vender mi archivo y aquí puedes ver que ahora estamos obteniendo todos estos
going to sell my file and here you can see we are now getting all of these
5:29:16
botones justo aquí y también este título justo aquí también, así que
buttons right here and also this title right here as well so
5:29:20
ahora lo siguiente que tienes que hacer es que tenemos que encargarnos del estilo, así que lo que haré es que voy a seleccionar mi recomendado r-e-c-o-m-e-n-d-e-d
now the next thing that you have to do is that we have to take care of the styling so what i'll do is that i'm going to just select my recommended r-e-c-o-m-e-n-d-e-d
5:29:29
y luego vamos a proporcionar recomendado flex y display
and then we are going to be providing recommended flex and display
5:29:32
de piernas y también voy a proporcionar un margen a la izquierda o
of legs and i'm going to also provide a margin to the left or
5:29:35
como 20 rims y también solo seleccionaré mi
like 20 rims and also i'll just select my
5:29:38
título recomendado y también voy a
recommended title and also i'm going
5:29:41
proporcionar un margen para la izquierda de como 20 rims y
to provide a margin for the left of like 20 rims and
5:29:44
margen para la parte inferior voy a proporcionar 20 sí píxeles estará bien y también voy a poner un margen para la parte superior 20 píxeles y el tamaño de fuente ahora se establecerá en 20 píxeles también.
margin for the bottom i'm going to provide 20 yep pixel be fine and i'm going to also put a margin for the top 20 pixel and and font size will be now set to 20 pixels as well.
5:29:56
Así que si guardas nuestro archivo, lo actualizas, no pasará nada
So if you save our file, refresh it, nothing is going to happen
5:29:59
porque no usamos estas cláusulas así que
because we didn't use these clauses so
5:30:02
solo copiaré este nombre de clase que se recomienda flex y
i'll just copy this class name which is recommended flex and
5:30:05
voy a colocarlo justo aquí dentro o
i'm going to just place it right here inside or
5:30:08
sabes no dentro sino dentro de estos elementos así que solo
you know not inside but inside these items so we just
5:30:12
proporcionar botones recomendados no sé por qué hice eso yo
provide recommended buttons i don't know why i did that i
5:30:15
no tengo idea de por qué hice eso pero debería haber
don't have any idea why i did that but it should have
5:30:18
ser un flex recomendado así que ahora si guardas eso y
to be a recommended flex so now if you save that and
5:30:21
aquí puedes ver que ahora solo empujará todos nuestros elementos justo aquí y
here you can see it will now just push all of our items right here and
5:30:25
qué más tenemos que hacer es que también tenemos que proporcionar un recomendado
what else do we have to do is that we have to also provide a recommended
5:30:28
título justo aquí así que solo escribiré una clase de recomendado
title right here so i'll just write a class of recommended
5:30:32
títulos así que si vendemos un archivo y aquí puedes ver que también
titles so if we sell a file and here you can see it will also
5:30:35
empujará este título justo aquí pero eso no se ve tan
push this title right here but that's not looking that
5:30:38
genial uh déjame entrar en este archivo index.css justo aquí y voy a desplazarme hacia abajo y no sé por qué eso no se aplicó así que voy a cortar este estilo de aquí
cool uh let me just go inside this index.css file right here and i'm going to just scroll down and i don't know why that didn't apply it so i'm going to just cut this styling from here
5:30:50
y voy a colocarlo justo aquí así que voy a guardar mi archivo y
and i'm going to just place it right here so i'm going to just save my file and
5:30:53
aquí puedes ver cómo se ven mis botones y también podemos
here you can see this is how my buttons look like and we can also
5:30:56
cambiar esta familia de fuentes si quieres así que solo iré a mi
change this font family if you want to so i'll just go to my
5:31:00
fuente cómo lo llamas index.css y voy a
font what do you call index.css and i'm going
5:31:03
seleccionar todo lo que proporcionamos familia de fuentes de sensor
to just select everything we did provide font family of sensor
5:31:06
pero no sé por qué no está funcionando sabes voy a cerrarlo desde
but i don't know why it's not working you know i'm going to just close it from
5:31:09
aquí y voy a proporcionarlo justo aquí así que solo proporcionaré la familia de fuentes de
here and i'm going to provide it right here so i'll just provide font family of
5:31:16
serif enviada justo aquí enviar mi archivo y solo actualicemos
send serif right here send my file and let's just refresh
5:31:19
está bien solo lo puse de la manera equivocada voy a cortarlo y estoy
it okay i just put it in the wrong way i'm going to cut it and i'm
5:31:22
voy a colocarlo justo aquí así que la familia de fuentes de serif enviada y eso se ve
going to place it right here so font family of send serif and that's looking
5:31:26
genial y aquí puedes ver que tenemos nuestros botones, tenemos nuestra búsqueda
cool and here you can see we have our buttons we have our search
5:31:29
y tenemos algunos elementos aquí, todos
fields and we have a few items right here all
5:31:33
bien, eso fue todo sobre la sección recomendada, así que ahora lo siguiente que
right so that was it about recommended section so now the next thing which
5:31:36
tienes que hacer es que dentro de esta barra lateral voy a crear uno
you have to do is that inside this sidebar i'm going to be creating one
5:31:39
componente llamado sidebar.js, voy
component given name of like sidebar.js I'm
5:31:43
a escribir también un sidebar.css
going to be also writing a sidebar.css
5:31:46
archivo también aquí, así que dentro de este componente
file as well right here okay so inside this component
5:31:49
quiero decir, dentro de esta carpeta pero fuera de esto
I mean like inside this folder but outside from this
5:31:52
categoría, color y componentes de precio aquí, así que también voy a
category color and price components right here so I'll just also
5:31:55
escribir rfc, eliminarlos y voy a cortarlo de aquí y luego déjame agarrar mi barra lateral aquí, voy a acercar un poco y ahora voy a
write rfc remove them and I'm going to just cut it from here and then let me just grab my sidebar right here I'm going to zoom in a bit and now I'm going to go
5:32:05
sabes, primero que nada déjame también obtener mi declaración de importación de aquí
you know first of all let me also get my import statement from here
5:32:09
como sidebar.css y
like sidebar.css and
5:32:12
ahora voy a entrar en esta barra lateral, quiero decir, en esta aplicación aquí
now i'm going to go inside this sidebar i mean like this app right here
5:32:15
y tenemos que usarlo aquí y
and we have to use it right here and
5:32:18
voy a colocarlo en la parte superior, así que solo le daré
i'm going to be placing it at the top so i'll just give
5:32:21
un nombre como sidebar y ahora voy a guardar mi archivo, voy a entrar aquí y aquí puedes ver que tenemos esta barra lateral aquí, así que vamos a colocar todo nuestro contenido aquí, así que qué más tenemos que hacer
a name of like sidebar and now i'm going to save my file i am going to go inside here and here you can see we have this sidebar right here okay so we are going to be placing all of our content right here so what else do we have to do
5:32:33
sabes qué, primero que nada voy a escribir mi, ¿cómo lo llamamos?
you know what first of all i'm going to be writing my uh what do we call
5:32:36
se me olvidó el nombre de este, ¿qué
it um kind of forgot the name of this one what
5:32:39
lo llamamos? Bien, fragmentos, ahí vamos, se me olvidó el nombre de
do we call it okay fragments there we go i forgot the name of
5:32:42
esto, ahora déjame crear una sección, voy a darle mi nombre como sidebar
it now let me just create a section i'm going to give my name of like sidebar
5:32:45
y ahora dentro de esta barra lateral voy a crear un div con
and now inside this sidebar i'm going to be creating a div with
5:32:48
una clase de contenedor de logo y aquí vamos a
a class of logo container and here we are going to be
5:32:51
simplemente escribir h1 y voy a colocar algo como carrito
just writing h1 and i'm going to just place like cart
5:32:54
logo o algo así, lo voy a colocar aquí y
logo or something like that i'm going to place it right here and
5:32:58
eso estará bien, debajo de este div voy a crear oh
that's going to be fine underneath this div i'm going to be creating oh
5:33:01
sabes qué, solo voy a obtener mi categoría, mira
you know what let just get my category see
5:33:05
vamos, c-i-t-e-g-o-r-y si puedes
it come on c-i-t-e-g-o-r-y if you
5:33:08
no podemos, así que tenemos que importarlo manualmente
can get we can't so we have to import it manually
5:33:11
así que solo voy a ir y categoría
so i'm going to just go and category
5:33:15
vamos, no me está ayudando en esto
come on it's not helping me in this
5:33:18
no sé por qué, pero vamos a entrar en esta categoría
case i don't know why but let's go inside this category
5:33:21
y luego categoría, voy a copiar eso, copiar esta categoría y qué más tienes que hacer, solo tenemos que colocarla aquí mismo, así que tenemos nuestra categoría
and then category i'm going to copy that copy this category and what else do you have to do we have to just place it right here so we have our category i'm
5:33:30
voy a duplicar eso tres veces, solo dos veces, no tres veces
going to duplicate that three times just two times not three times
5:33:33
y voy a cambiar eso a precio y luego
and i'm going to change that to price and then
5:33:37
tenemos que cambiar eso a precio
we have to change that to price
5:33:40
y tenemos que ir al precio, voy a cambiar eso a
and we have to go to the price i'm going to change that to
5:33:43
colores y voy a eliminarlos
colors and i'm going to remove them
5:33:46
y déjame poner mis colores, y dentro de estos colores vamos a proporcionar ese color, así que solo copiaré este precio de aquí
and let me just put my colors uh and inside these colors we are going to be just providing that color so i'll just copy this price from here
5:33:57
y voy a colocar eso justo aquí y
and I'm going to just place it right in here and
5:34:00
también voy a copiar estos colores y los voy a pegar
I'm going to also copy these colors and I'm going to paste it
5:34:03
aquí mismo, así que solo voy a alejarme un poco para que puedan ver
right here so I'm going to just zoom out so you guys can see
5:34:06
todo un poco mejor, así que ahora, si lo guardas aquí, puedes ver que ahora estamos obteniendo
everything a bit better so now if you save it here you can see we are now getting
5:34:09
categoría, también estamos obteniendo un componente de precio y también
category we are also getting a price component and also
5:34:12
nuestro componente de colores aquí y aquí también estamos obteniendo
our colors component right here and here we are also getting
5:34:15
nuestros logos, así que ahora lo siguiente que tienes que hacer es que tenemos que estilizar nuestro componente, así que eso es genial, voy a ir
our logos so now the next thing which you have to do is that we have to style our component so that's cool I'm going to go
5:34:22
dentro de esta barra lateral y solo voy a estilizar aquí, así que solo escribiré barra lateral
inside this sidebar and i'm going to just style here so i'll just write sidebar
5:34:26
título de guion, acerquémonos un poco y solo voy a proporcionar fuente
dash title zoom in a bit and i'm going to just provide font
5:34:29
tamaño de 22 píxeles y también voy a proporcionar un peso de fuente
size of 22 pixel and i'm going to also provide a font weight
5:34:32
normal y margen para abajo, solo voy a
of normal and margin for a bottom i'm going to just
5:34:35
proporcionar como 20 píxeles, está bien, así que luego voy a
provide like 20 pixel okay so then i'm going to be
5:34:39
seleccionando mi barra lateral y solo voy a proporcionar un 15
selecting my sidebar and i'm going to just provide a 15
5:34:42
porciento de ancho para ello, puedes especificar como quieras y luego solo voy a proporcionar una posición de altura fija
percent of width to it you can just specify however
5:34:45
será del 100% y luego tenemos un borde
you want and then i'm going to just provide a position of fixed rate height will
5:34:49
a la derecha tenemos dos píxeles sólidos y
be 100% and then we have a border to
5:34:52
vamos a reutilizar E5 E5 E5
the right we have two pixel solid and
5:34:56
una vez más, está bien, así que las terminaciones z las voy a poner
we are going to be reusing E5 E5 E5
5:34:59
un tercio y la visualización se establecerá en poliflex
one more time okay so the z endings i'm going to just put
5:35:02
en este caso y la dirección de flexión se establecerá ahora en columna
a three-third and display will be set to polyflex
5:35:06
y alinear los elementos también se establecerá en el centro, está bien, así que
in this case and flex direction will be now set to column
5:35:09
eso es, ahora si configuramos nuestro archivo y así es como se ve aquí, uh, así es como actualmente se ve, pero tenemos
and align items will be also set to center okay so
5:35:12
que poner esto debajo, así que ahora tenemos que seleccionar
that's then now if we set our file and this is how it looks like right here uh this is how currently stuff looks like but we
5:35:18
nuestro contenedor de logotipo y tenemos
have to put this underneath so we have to now select
5:35:22
que poner nuestro margen margen
our logo container and we
5:35:25
uh, para la parte inferior solo vamos a escribir para rim
have to put our margin margin
5:35:29
y también tenemos que seleccionar nuestro logotipo
uh for the bottom we are going to be just writing for rim
5:35:32
contenedor una vez más y seleccionar nuestro h1 y margen
and also we have to select our logo
5:35:35
para la parte superior voy a proporcionar 1.3 rims para ello, así que si vendes nuestro archivo, eso se ve totalmente increíble aquí, así que aquí
container one more time and select our h1 and margin
5:35:38
puedes ver que casi estamos allí, tenemos nuestro qué
for the top i'm going to provide 1.3 rims to it so if you sell our file and that's looking totally awesome right here so here you
5:35:45
llamamos navegación, tenemos este componente, tenemos todos nuestros productos
can see we are almost getting there we have our what
5:35:48
aquí y luego tenemos todas nuestras categorías de precio
do we call navigation we have this component we have all of our products
5:35:52
y colores aquí, así que ahora tenemos que ocuparnos de cada uno de
right here and then we have all of our categories price
5:35:55
estos componentes uno por uno, así que ahora hemos terminado completamente con
and colors right here so now we have to take care of each of
5:35:58
estos componentes uno por uno, así que ahora hemos terminado completamente con
these components one by one so now we are totally done with
5:36:01
eso, así que ahora lo siguiente que tenemos que hacer es ocuparnos de este componente de categoría, así que voy a entrar en este componente de categoría y lo que haré es que primero
that so now the next thing which we have to do is that we have to take care of this category component so i'm going to go inside this category component and what i will do is that first of all
5:36:12
voy a simplemente eliminar esta categoría de allí y voy a escribir
i'm going to just remove this category from there and i'm going to just write
5:36:15
h2 con la clase de título de barra lateral
h2 with the class of sidebar title
5:36:18
aquí y voy a proporcionar categoría y
right here and i'm going to just provide category and
5:36:22
ahora voy a volver para que ustedes puedan ver todo un poco mejor dentro
now i'm going to go back so you guys can see everything a bit better inside
5:36:25
este div vamos a estar escribiendo una etiqueta etiqueta bien
this div we are going to be writing a label label right
5:36:28
aquí y también voy a proporcionar una etiqueta de barra lateral
here and i'm going to also provide a sidebar label
5:36:31
clase de contenedor a esto, está bien, así que no vamos a proporcionar ningún atributo html4 a esto dentro de este nivel, ¿qué tenemos que hacer?
container class to it okay so we are not going to be providing any html4 attributes to it inside this level what do we have to do we
5:36:40
tenemos que escribir solo input con un tipo de radio en lugar de
have to just write input with a type of radio instead of
5:36:43
texto y también tenemos que darles algún tipo de nombre como prueba
text and we also have to give them some sort of a name of like test
5:36:46
estaría bien, uh sí, eso va a estar bien y luego tenemos que encontrarlo, ¿verdad? o una clase, quiero decir, como gastar
would be fine uh yeah that's going to be fine and then we
5:36:49
con una clase de marca de verificación, ahí vamos y
have to find it right or a class i mean like spend
5:36:52
tenemos que especificar una etiqueta para ello, así que si solo guardas
with a class of check mark there we go and
5:36:56
nuestro archivo y aquí puedes ver que ahora estamos obteniendo este
we have to specify a label for it so if you just save
5:36:59
uh, ¿cómo lo llamamos, casilla de verificación o marca de verificación?
our file and here you can see we are now getting this one
5:37:02
aquí estamos especificando que, oh, pero
uh what do we call it check box or check mark
5:37:05
no lo estamos obteniendo, está bien, lo estamos obteniendo aquí, pero tenemos que tomar
right here we're specifying that oh but
5:37:08
cuidado con el estilo, pero antes de entrar en todos ellos, tenemos que
we are not getting it okay we are getting it right here but we have to take
5:37:11
duplicar este jsx aquí y una vez más estoy
care of the styling but before we're getting into all of them we
5:37:14
a punto de refactorizar todo el jsx en
have to duplicate this jsx right here and once again i'm
5:37:18
múltiples componentes, pero por ahora solo estoy escribiendo todo
going to be refactoring all of the jsx into
5:37:21
de este jsx para que podamos ver nuestro marcado aquí
multiple components but for now i'm just writing all
5:37:25
está bien, también vamos a estar formateando, quiero decir, refactorizando todo este código una y otra vez, así que solo duplicaré eso, no sé
of these jsx so that we can see our mark up right here
5:37:28
como tres veces, no tres veces, sino cuatro veces, así que uno, dos, tres, cuatro, está bien, y ahora voy a cambiar estas etiquetas a algo más, como no sé, tenemos todo, luego tenemos nuestras zapatillas
okay we're going to be also formatting i mean like refactoring all of this code again and again so i'll just duplicate that i don't know
5:37:34
uh s-n-e-a-n-e-a-k-e-r-s
like three times not three times but four times so one two three four okay and now i'm going to just change these labels to something else like i don't know we have all then we have our sneakers
5:37:47
uh z-a-p-a-t-i-l-l-a-s
uh s-n-e-a-n-e-a-k-e-r-s
5:37:50
ahí vamos y luego tenemos en lugar de zapatillas, quiero decir, en lugar de todo, también vamos a ofrecer zapatos planos y luego tenemos sandalias, así que sandalias, ahí vamos
there we go and then we have instead of sneakers i mean like instead of all we are going to be also providing flats and then we have a sandals so sandals there we go
5:38:00
y luego finalmente tenemos orden de tacones así que tacones
and then finally we have order heels so heels
5:38:04
guardar nuestro archivo y sí, eso se ve totalmente bien
save our file and yep that's looking totally a-okay
5:38:07
así que por ahora voy a estar escribiendo mucho
so for now i am going to be writing a lot
5:38:10
de css aquí, pero si no quieres escribir un css así
of css right here but if you don't want to write a css so
5:38:14
puedes ir a mi repositorio de github y puedes obtener todos los
you can just go to my github repository and you can grab all of
5:38:17
estos css desde allí si quieres, así que lo primero que haría es que voy a seleccionar mi barra lateral y luego barra lateral, quiero decir, título de la barra lateral y voy a proporcionar un tamaño de fuente de 22 píxeles
these css from there if you want to so the first thing which i would do is that i'm going to be selecting my sidebar and then sidebar i mean like sidebar title and i'm going to be providing a font size of 22 pixel
5:38:28
y el peso de la fuente será totalmente normal y el margen para la parte inferior
and font weight will be totally normal and margin for the bottom
5:38:31
voy a poner solo 20 píxeles aquí y luego
i'm going to just for 20 pixel right here and then i'll
5:38:34
simplemente proporcionaré mis elementos de la barra lateral aquí y yo
just provide my sidebar items right here and i
5:38:38
no sé qué demonios acabo de hacer, voy a cerrar eso
don't know what the hell i just i'm going to close that
5:38:41
y ahora dentro de eso voy a proporcionar un margen para la parte superior
and now inside there i'm going to be providing a margin for a top
5:38:44
de 20 píxeles y ahora simplemente
of 20 pixel and now i'll just
5:38:47
subir un poco hacia abajo y barra lateral un
go up a little bit down and sidebar a
5:38:50
contenedor de etiqueta dentro de eso, vamos
label container inside there we
5:38:53
a estar escribiendo display de bloque poligonal y tenemos
are going to be writing display of poly block and we have
5:38:56
posición relativa porque el otro era fijo y
position of relative because the other one was a fix and
5:38:59
luego tenemos padding para la izquierda y voy a proporcionar
then we have padding for left and i'm going to just provide
5:39:02
35 píxeles para el margen de padding izquierdo
35 pixel for the padding left margin for
5:39:05
para la parte inferior, voy a proporcionar 12 píxeles y luego
the bottom i'm going to provide 12 pixel and then we
5:39:08
tenemos cursor y configurado en puntero, luego tenemos, eh, solo
have cursor and set to pointer then we have uh just
5:39:12
un usuario de webcat, eh, ¿qué
one webcat uh user what
5:39:15
llamamos a eso? seleccionar, ahí vamos y vamos a configurarlo en ninguno, luego
do we call it select there we go and we're going to set that to none then
5:39:18
tenemos un moze para mozilla y usuario
we have a moze for mozilla and user
5:39:21
el select ahora se configurará en totalmente ninguno, está bien
select will be now set to totally none okay
5:39:25
queremos simplemente eliminar eso, luego tenemos un usuario ms y
we want to just remove that then we have an ms user and
5:39:28
entonces seleccionamos, también vamos a eliminar eso y finalmente estamos
then select we are going to be also removing that and finally we are
5:39:31
escribiendo una selección de usuario y eso se establecerá en totalmente ninguno, archivo de celda, estamos totalmente llegando allí, pero eso tomará un poco de tiempo o algo así.
going to be writing a user select and that will be set to totally none cell file we are totally getting there but that will take a bit of for a while or something.
5:39:43
Eso tomará un poco de tiempo. Así que solo escribiré una barra lateral y luego el contenedor de nivel una vez más.
That will take a little bit of a while. So I'll just write a sidebar and then level container one more time.
5:39:49
Y voy a seleccionar mi campo de entrada. Voy a proporcionar una posición de totalmente absoluta, opacidad de cero, el cursor se establecerá en totalmente puntero.
And I'm going to be selecting my input field. I'm going to be providing a position of totally absolute, opacity of zero, cursor will be set to totally pointer.
5:39:57
Y ahora déjame obtener mi marca de verificación.
And now let me get my check mark.
5:40:00
que supongo que la marca de verificación estaba allí una verificación
which is I guess check mark was there a check
5:40:03
marca o algo así, verificación verificación
mark or something check check
5:40:06
marca ahí vamos, la voy a colocar justo aquí para verificar dos veces
mark there we go I'm gonna place it right here for double checking
5:40:09
posición o totalmente absoluta, arriba cero, izquierda
position or totally absolute top zero left
5:40:12
cero, la altura será de 20 píxeles, el ancho será de 20 píxeles y
zero height will be 20 pixel width will be 20 pixel and
5:40:16
también el color de fondo se establecerá en totalmente eee
also the background color will be set to totally eee
5:40:20
tres veces eee y
three times eee and
5:40:23
el radio de la bola se establecerá en 50 por ciento, ahí vamos y
ball radius will be set to 50 percent there we go and
5:40:27
también nos ocuparemos de esa barra lateral
we are going to be also taking care of that sidebar
5:40:30
contenedor de etiqueta y una vez que pasemos el mouse sobre
label container and once we hover over
5:40:33
cada entrada que queremos seleccionar
each the input we want to select
5:40:37
o marca de verificación, está bien, entonces
or check mark okay so then we
5:40:40
también vamos a escribir un color de fondo de totalmente ccc
are going to be also writing a background color of totally ccc
5:40:43
está bien, duplica eso y qué
that's fine duplicate that and what
5:40:46
vamos a hacer es que una vez que verifiquemos, en lugar de pasar el mouse, voy a eliminar este hover de aquí y solo proporcionaré esto
we are going to be doing is that once we check instead of hover i'm going to remove this hover from here and i'm going to just provide this
5:40:54
marcado en la entrada, así que una vez que verifiquemos o la casilla de verificación
checked on the input so once we checked or checkbox
5:40:57
así que solo quieres cambiar el color a 219 qué
so you want to just change the color to 219 what
5:41:01
lo llamamos un 96 f3
do we call it a 96 f3
5:41:05
una especie de color azul, pero no tan azul y vamos a guardar
kind of a blue color but not that much blue and we're going to be saving
5:41:08
ellos y aquí puedes ver cómo actualmente las cosas
them and here you can see this is how currently things
5:41:11
se ve así aquí, así que si haces clic en él y sí, eso se ve totalmente
looks like right here so if you click on it and yep that's looking totally
5:41:14
bien, voy a volver y ahora déjame seleccionar mi marca de verificación una vez más y voy a usar mi selector de estudio superior así que
a-okay i'm going to just go back and now let me just select my check mark one more time and i'm going to be using my upper studio selector so
5:41:23
contenido nada posición absoluta y
content nothing position absolute and
5:41:26
tenemos una pantalla y vamos a eliminarla, está bien
we have a display and let's just remove it okay
5:41:30
y ahora voy a usar elementos de barra lateral
and now i'm going to just use uh sidebar items
5:41:33
no, lo siento, pero elementos, pero contenedor de etiqueta
not sorry but uh items but label container
5:41:36
voy a seleccionar mi marca de verificación, déjame conseguir
i'm going to be selecting my check mark let me just get
5:41:39
mi verificación si está marcada, así que lo que quieres hacer es
my check if that's checked so what you want to do you want to
5:41:42
seleccionar nuestra marca de verificación y queremos usar nuestro selector después
select our check mark and we want to use our after selector
5:41:46
en él y queremos proporcionar una visualización de totalmente bloqueado en este caso, en este caso posterior proporcionamos una marca de verificación de
on it and we want to just provide a display of totally blocked to it in this case in this after case we provide a check mark of
5:41:53
visualización de ninguno y aquí solo hemos especificado, quiero decir, como
display of none and here we are just specified i mean like
5:41:56
una vez que eso esté marcado, como esa entrada está marcada, así que solo quieres
once that's checked like that input is checked so you want to just
5:41:59
proporcionar visualización de bloque si vendes nuestro archivo, voy a
pour display of blockdue if you sell our file i'm going to
5:42:02
hacer clic en él, no puedes ver eso, lo verás en un segundo, pero déjame
click on it you cannot see that you will see that just in a second but let
5:42:05
conseguir la etiqueta de la barra lateral
me just get it sidebar label
5:42:08
contenedor, déjame conseguir eso, déjame conseguir mi marca de verificación
container let me just get that let me get my check mark
5:42:11
y voy a usar mi selector después aquí, la parte superior se establecerá como aquí, estoy especificando diferentes tipos de anchos, puedes aumentar o
and i'm going to be using my after selector right here the top will be set to like here i'm specifying different kind of widths you can increase or
5:42:18
disminuir eso como quieras, uh seis, uh qué
decrease that how you want uh six uh what
5:42:22
lo llamamos 6.4 píxeles y luego tenemos un ancho de siete píxeles, altura de totalmente siete píxeles y luego tenemos un radio de borde de un radio de borde de 50
do we call it 6.4 pixel and then we have a width of seven pixel height of totally seven pixel and then we have a border radius of a border radius of 50
5:42:34
totalmente redondeado, así que por eso estamos proporcionando eso
just a totally rounded so that's why we are providing that
5:42:37
y ahora si guardas un archivo y aquí puedes ver que ahora estamos obteniendo ese círculo blanco aquí, así que si haces clic en él y eso es
and now if you save a file and here you can see we are now getting that white circle right here so if you click on it and that's
5:42:44
más que aceptable, está bien, así que eso está bien, pero
looking more than okay okay so that's fine but
5:42:47
la última cosa que tienes que hacer es que tenemos que obtener esta
the final thing that you have to do is that we have to get this
5:42:50
línea aquí de algún lugar, así que vamos a escribir una línea
line right here from somewhere so we are going to be just writing a line
5:42:54
uh no vamos a usar esta línea ahora mismo
uh we are not going to be using this line right now
5:42:57
así que solo voy a proporcionar tres bordes y un borde
so i'm going to just provide three rims and border
5:43:00
uh el color ahora se establecerá como uh
uh color will be now set to just like uh
5:43:03
f7 f7 vamos f7 f7
f7 f7 come on f7 f7
5:43:06
ahí vamos y sí, eso está totalmente bien así que
there we go and yeah that's totally fine so
5:43:09
nuestro archivo no va a ser cambiado, está bien, así que eso
our file nothing is going to be changed all right so that
5:43:12
fue totalmente genial, estamos totalmente avanzando, pero el segundo
was totally cool we are totally getting there but the second
5:43:15
cosa que tienes que hacer es que tenemos que ocuparnos de ese componente de precio y
thing which you have to do is that we have to take care of that price component and
5:43:19
componente de color y luego vamos a estar refactorizando todo
color component and then we are going to be refactoring all
5:43:22
nuestro proyecto y finalmente vamos a estar proporcionando nuestra funcionalidad a
of our project and finally we are going to be providing our functionality to
5:43:26
este proyecto, está bien, así que eso es, ahora déjame ocuparme de su precio y luego vamos a ocuparnos de sus colores, así que no va a
this project all right so that's that now let me just take care of their price and then we are going to be taking care of their colors so it's not going
5:43:34
verse tan horrible, vamos a estar yendo
to be looking that awful we are going to be going
5:43:38
a estos colores, sabes que vamos a estar ocupándonos
into these colors you know we are going to be taking care
5:43:41
de sus colores un poco más tarde o sí
of their colors a little bit later or yeah
5:43:44
podemos hacer una llamada, no sé tú
can we take a call i don't know you
5:43:47
sabes que voy a ir con este precio y precio
know i'm going to go with this price and price
5:43:50
estará bien y ahora voy a quitar esto
will be fine and now i'm going to remove this
5:43:53
precio de allí y solo voy a proporcionar un nombre de clase de ml para ello, está bien, para margen izquierdo o sí, margen izquierdo
price from there and i'm going to just provide a class name of ml to it okay for marginal left or yeah margin left
5:44:01
estará bien y luego tenemos h2 de ese mismo título
will be fine and then we have h2 of that same title
5:44:04
lado uh barra lateral y título
side uh sidebar and title
5:44:07
y luego tenemos un título de precio también porque vamos
and then we have a price title as well because we
5:44:10
a estar proporcionando un poco de estilo a ese título de precio y
are going to be just providing a little bit of styling to that price title and
5:44:13
ahora sabes que voy a entrar allí y voy a copiar
now you know i'm going to go inside there and i'm going to copy
5:44:16
un poco de código de él, así que solo copiaré esta etiqueta de
a little bit of code from it so i'll just copy this label from
5:44:19
aquí y la voy a colocar justo aquí, así que esto va a ser para uno
here and i'm going to place it right here so this is going to be for one
5:44:23
vez y luego yo, sabes que voy
time and then i you know i'm
5:44:26
voy a duplicar esta etiqueta um lo que contamos JSX
going to just duplicate this label um what do we counted JSX
5:44:29
unas cuantas veces así que tenemos para todos luego tenemos
a few times so we have for all then we have
5:44:32
por $50 tenemos 400 150 y tenemos
for $50 we have 400 150 and we
5:44:35
200 está bien así que solo proporcionaré una prueba de
have 200 okay so I'll just provide a test of
5:44:38
no sé prueba de dos así que solo voy a seleccionar uno
like I don't know test of two so I'm going to just select one
5:44:42
presiona ctrl d ctrl d ctrl d o comando d lo que sea
hit ctrl d ctrl d ctrl d or command d whatever
5:44:45
y voy a cambiar la etiqueta quiero decir como el nombre a prueba total dos y aquí esta se establecerá en todos y ahora esta se establecerá en cero, sabes, solo proporcionaré cero
and I'm going to change the label I mean like to name to totally test two and here this one will be set to all and now this one will be now set to zero, you know, I'm going to just provide zero
5:44:57
dólares está bien así que solo 50 dólares estarán
dollars okay so just 50 dollars will
5:45:00
bien y voy a copiar su patrón y solo lo duplicaré aquí y solo cambiaré los valores a como 100 dólares uh 100 estará bien y esta se establecerá en 50 dólares
be fine and i'm going to copy them their pattern and i'm going to just duplicate it right here and i'm going to just change the values to like 100 dollar uh 100 will be fine and this one will be now set to 50 dollars
5:45:12
está bien y esta se establecerá en 100 dólares 1 000 y esta será 150 dólares y esta
okay and this one will be now set to 100 dollars 1 000 and this one will be 150 dollars and this
5:45:19
será finalmente uh sobre uh
one will be finally uh over uh
5:45:22
150 así que archivo de vendedor y
150 so seller file and
5:45:26
aquí puedes ver que ahora estamos obteniendo todos estos precios aquí totalmente
here you can see we're now getting all of these prices right here totally
5:45:29
bien uh pero sabes que voy a entrar en esto
fine uh but you know i'm gonna go inside this
5:45:32
ml quiero decir como este estilo de precio y solo voy a seleccionar
ml i mean like this price styling and i'm gonna just select
5:45:35
mi título de precio así y voy a proporcionar
my price title like so and i'm gonna provide
5:45:38
un margen para la parte superior de 20 píxeles y también voy a proporcionar quiero decir como voy a seleccionar el ml y voy a
a margin for a top of 20 pixel and i'm gonna also provide i mean like i'm gonna select the ml and i'm going
5:45:45
proporcionar margen para la izquierda de 20 píxeles nuestro archivo y
to provide margin for left of 20 pixels our file and
5:45:48
eso se ve un poco mejor está bien así que eso también está hecho así que
that's looking a bit better all right so that's also done so
5:45:51
ahora la siguiente cosa de la que tienes que encargarte es este color
now the next thing which you have to take care of this color
5:45:55
componente así que solo cerraré estos archivos desde aquí estoy
component so i'll just close these files from here i'm
5:45:58
voy a entrar en mi componente de color voy a seleccionar mi archivo color.css
going to go into my color component i'm going to select my color.css file
5:46:02
también y voy a hacer esa misma copia y pegar una vez más y una vez más voy
as well and i'm going to do that same copying and pasting one more time and once again i'm going
5:46:08
a estar refactorizando todo ese código desde
to be refactoring all of that code from
5:46:12
cero así que sabes aquí voy a
scratch so you know here i'm going to
5:46:15
quitar estos colores de aquí y luego lo que haría
remove these colors from here and then what i would
5:46:18
es que voy a pasar todos estos jsx justo aquí, está bien
do is that i'm going to just pass all of these jsx right here okay
5:46:21
así que tenemos esa misma etiqueta, voy a cambiar todo esto
so we have that same label i'm going to change this all
5:46:25
sabes que el primero será todo, sí, el primero será todo, el segundo será de color negro, déjame quitar estas etiquetas o
you know the first one will be all yep the first one will be all the second one will be black color let me just remove these labels or
5:46:33
podemos hacer eso, así que este ahora se establecerá en negro y
we can do that so this one will be now set to black and
5:46:36
este ahora se establecerá en azul, entonces
this one will be now set to blue then
5:46:40
tenemos una categoría roja así y luego
we have a red category like so and then
5:46:43
finalmente tenemos nuestras categorías blancas, tenemos
finally we have our white categories we
5:46:46
blanco, pero también tenemos uno verde como
have white but we also have a green one as
5:46:49
bueno, así que déjame escribir, uh, verde y
well so let me just write uh green and
5:46:53
entonces finalmente tenemos el archivo de celda blanca y veamos aquí, puedes ver que tenemos todas las categorías: negro, azul, rojo, verde y
then finally we have white cell file and let's just see here you can see we have all category black blue red green and
5:47:01
blanco finalmente y aquí también voy a pasar
white finally and here i'm going to be also passing
5:47:04
mi título de color, así que tenemos un título de color justo aquí
my color title so we have a color title right here
5:47:07
archivo semi y ahora voy a entrar en este título de color
semi file and now i'm going to go inside this color title
5:47:10
justo aquí voy a seleccionar este título de color y
right here i'm going to select this color title and
5:47:14
voy a proporcionar un margen para la parte superior de las rampas de herramientas y
i'm going to just provide a margin for the top of tool ramps and i'm
5:47:17
también voy a seleccionar todas las clases y aquí estamos
going to also select all class and here we are
5:47:21
no usando esta clase, pero lo haremos muy pronto, así que
not using this class but we will very soon so
5:47:24
voy a usar un degradado lineal y voy a proporcionar azul y carmesí, está bien, así que si tú
i'm going to just use linear gradient and i'm going to provide blue and crimson okay so if you
5:47:30
archivo de celda, no pasará nada excepto que aquí estamos obteniendo
cell file nothing will happen except here we are getting
5:47:33
justo todos estos componentes aquí, así que ahora
just all of these components right here so now
5:47:36
es hora, está bien, así que ahora hemos terminado totalmente con estos componentes
it's time all right so now we are totally done with these components
5:47:39
así que ahora es hora de hacer una gran reestructuración en todos
so now it's time to do a huge refactoring in all
5:47:42
de estos componentes porque actualmente nuestro código
of these components because currently our code
5:47:46
se ve más que desordenado, como si tuviéramos
is looking more than messy like we have
5:47:49
todos estos componentes aquí, pero confía en mí, esto es
all of these components right here but trust me this is
5:47:52
totalmente un desastre, tenemos que crear un componente, quiero decir, un componente separado para botones y solo estamos reutilizando
like totally a mess we have to create a component i mean like separate component uh for buttons and we are just reusing
5:47:58
esa entrada una y otra vez y también tenemos este color
that input again and again and we also have this color
5:48:02
lo estamos reutilizando aquí, lo estamos reutilizando, ¿verdad?
we are reusing it here we we are reusing it right
5:48:05
aquí y nuestro código es como totalmente
here and we our code is like totally
5:48:08
un desastre, así que ahora simplemente vamos a refactorizar todo nuestro código, así que antes
a mess so now let's just refactor all of our code so before
5:48:12
de entrar en la refactorización, primero tenemos que hacernos
we're getting into the refactor first of all we have to ask ourselves
5:48:15
unas cuantas preguntas, como dónde estamos
a few questions like where we are
5:48:18
repitiendo todo nuestro código, así que ahora lo que haré es que voy
repeating all of our code so now what i'll do is that i'm
5:48:21
a entrar en esta sección de producto aquí y aquí estamos reutilizando este componente, no un componente, sino este
going to go inside this product section right here and here we are reusing this component not a component but this
5:48:28
JSX, como muchas veces, como más
JSX like a lot of time like more
5:48:31
que muchas veces, aquí, así que, ¿qué tenemos que
than a lot of time right here okay so what do we have to
5:48:34
hacer? Primero que nada, voy a seleccionar este aquí
do first of all I'm going to just select this one right here
5:48:37
y voy a seleccionarlo a través de esta sección aquí
and I'm going to just select it through this section right here
5:48:40
así que voy a seleccionarlo y cortarlo, voy a cortarlo, solo haz clic derecho en él y presiona este botón de cortar aquí o también puedes usar este atajo que es
okay so I'm going to just select it and cut it I'm going to just cut it just right click on it and hit this uh cut button right here or you can also use this shortcut which is
5:48:50
control o comando o control o comando x, voy a eliminar todo el resto de este contenido
control or command or control or command x I'm going to remove all of the rest of this content
5:48:57
aquí, así que voy a eliminar todo este contenido
right here so i'm going to just remove all of this content
5:49:00
a través de esta sección aquí, así que ahora hemos
through this section right here okay so now we successfully
5:49:03
eliminado ese contenido de aquí, así que ahora lo siguiente que
remove that content from here so now the next thing which
5:49:06
tienes que hacer es que tenemos que entrar en esta carpeta de componentes
you have to do is that we have to go inside this component folder
5:49:09
y tenemos que encontrar este card.js aquí y
and we have to find this card.js right here and
5:49:12
tenemos que colocar todo nuestro jsx que copiamos aquí, está bien, y esto también es realmente
we have to just place all of our jsx which we copied right here okay and this is also like really
5:49:20
un mensaje todavía, pero ahora si vendes un archivo
message still but now if you sell a file
5:49:23
pero en lugar de copiar y pegar todo nuestro jsx uno
but instead of copying and pasting all of our jsx one
5:49:27
por uno, lo que vamos a hacer es que vamos a obtener esta tarjeta
by one what we are going to be doing is that we are going to be getting this card
5:49:30
y vamos a estar simplemente renderizando solo esta tarjeta, está bien
and we are going to be just rendering just this card okay
5:49:33
así que voy a guardar mi archivo y nos dará un error que
so i'm going to just save my file and it will give us an error that's
5:49:37
porque no lo copiamos y no lo colocamos
because we didn't copy it and we didn't place
5:49:40
esto aquí así que si vendes allí y aún nos dará un error porque tenemos que importar esa tarjeta desde ese componente de tarjeta. Así que si guardas eso y aquí puedes ver que la tarjeta no está definida.
this right here so if you sell there and it will still gives us error because we have to import that card from that card component card So if you save that and here you can see card is not defined.
5:49:51
La tarjeta no está definida. ¿Dónde está eso? Déjame refrescarlo. Y aquí puedes ver que ahora solo nos dará una tarjeta aquí.
Card is not defined. Where is that? Let me just refresh it. And here you can see it will now just gives us one card right here.
5:49:58
Así que en lugar de copiar y pegar todos estos jsx
So instead of copying and pasting all of these jsx
5:50:01
ahora convertimos todo ese código en un solo componente y
now we convert all of that coding into one component and
5:50:04
podemos reutilizar este componente cuántas veces queramos
we can just reuse this component like how many times we
5:50:07
así que si vendemos eso y aquí puedes ver que ahora nos usará
want so if we sell that and here you can see it will now use us
5:50:10
todos sus elementos aquí así que esto es solo un primer refactor, pero esto tampoco es un gran refactor, para ser honesto, volveremos aquí una vez más así que déjame refrescarlo
all of their uh items right here so this is just a first refactor but this is also not a great refactor to be honest we will come back here one more time so let me just refresh it
5:50:22
y así es como se ve aquí. Así que esto es solo un primer refactor para este componente de tarjeta.
and this is how it looks like right here. So this is just a first refactor for this card component.
5:50:27
Así que ya hemos creado este componente y solo estamos reutilizando ese componente una y otra vez. Así que este fue el primer refactor.
So we just already created this component and we are just reusing that component again and again. So this was the first refactor.
5:50:34
Así que ahora el siguiente refactor que vamos a hacer son estos campos de entrada aquí.
So now the next refactor which we are going to be doing is this input fields right here.
5:50:39
Así que eso va a ser totalmente simple y aquí déjame abrir esta categoría aquí.
So that's going to be totally simple and here let me just open this category right here.
5:50:44
Estamos repitiendo todas nuestras etiquetas aquí y entrada como etiqueta y entrada
We are repeating all of our labels right here and input like label and input
5:50:48
y todo ese tipo de cosas aquí y también estamos
and all of that kind of stuff right here and we are also
5:50:52
repitiéndolo dentro de estos colores, lo estamos repitiendo dentro
repeating it inside these colors we are repeating it inside
5:50:55
de este componente de precio también, así que ¿qué tenemos que hacer? tenemos que
this price component as well so what do we have to do we have
5:50:58
venir aquí y dentro de esta etiqueta de entrada, ¿qué queremos
to come up here and inside this input tag what do we want to
5:51:01
hacer? vamos a entrar en uno de ellos y
do we are going to be just going into one of them and
5:51:04
voy a copiar esta única etiqueta de allí y
i'm going to just copy this single label from there and
5:51:07
voy a reemplazarla con este div, está bien, así que voy a acercar un poco para que ustedes puedan ver un poco mejor y ahora voy a
i'm going to just replace it with this div okay so i'm going to just zoom in over so you guys can see a bit better and now i'm going to
5:51:14
archivo semi, así que aquí puedes ver que solo estamos obteniendo como, ¿qué
semi file so here you can see we are just getting like um what
5:51:17
llamas a eso? barra lateral y solo estamos proporcionando una barra lateral y
do you call it sidebar and we are just providing a sidebar and
5:51:21
por cierto, esto no va a ser el refactor final, vamos a
by the way this is not going to be the final refactor we are going to
5:51:24
todavía vamos a estar refactorizando este componente, pero solo quiero
be still refactoring this component but i just kind of want to
5:51:27
mostrarte la segunda forma de refactorizar o escribir este código
show you like the second way of refactoring or writing this code
5:51:30
bueno, todavía vamos a estar pasando muchas props y vamos a hacer eso una vez que entremos en la gestión del estado y todas esas cosas buenas, pero
okay so we are going to be still passing a lot of props and we are going to be doing that once we jump into state management and all of that kind of good stuff but
5:51:39
por ahora aquí puedes ver que solo especificamos esta entrada
for now here you can see we just specify this input
5:51:42
y esta etiqueta justo aquí dentro de este contenedor de entrada, así que
and this label right here inside this input container so
5:51:45
lo que tenemos que hacer es que voy a simplemente obtener mi contenedor de entrada
what we have to do i'm going to just uh get my input container
5:51:48
pero antes de hacerlo, voy a eliminar todas estas entradas de
but before i do i'm going to remove all of these inputs from
5:51:52
aquí y esta entrada de aquí como
here and this input from here as
5:51:55
bueno, ahora no vamos a eliminar eso, pero aquí
well or now we are not going to be removing that but here
5:51:58
vamos a estar simplemente renderizando nuestro contenedor de entrada, así que ahora déjame guardar mi archivo y aquí puedes ver que estamos obteniendo todo y podemos duplicar
we are going to be just rendering or input container okay so now let me just save my file and here you can see we are just getting all and we can just duplicate
5:52:07
hay como unas cuantas veces, como tenemos cuatro veces
they're like a few times like we have four times
5:52:10
o cinco veces aquí y aquí puedes ver que ahora solo estamos repitiendo
or five times right here and here you can see we are now just repeating
5:52:14
todos nuestros componentes uno por uno aquí, está bien
all of our component one by one right here okay
5:52:17
así que eso está totalmente bien, pero tendremos que cuidar de
so that's totally okay but we will have to take care of
5:52:20
sus etiquetas y cosas, pero eso es totalmente normal, así que
their labels and stuff but that's totally normal so
5:52:24
ahora déjame usar ese componente como su componente de entrada, así que
now let me just use that component like their input component so
5:52:27
voy a usar simplemente input y lo voy a cerrar
i'm going to just use input and i'm going to close it
5:52:30
y no lo importará porque había dos niveles arriba, está bien, así que input así y luego tenemos que
and it will not import it because there was two level up above okay so input like so and then we
5:52:37
ir a la carpeta de componentes y luego tenemos que entrar en este
have to go to the components folder and then we have to go inside this
5:52:40
input, así que si guardas nuestro archivo, déjame duplicar, ahí
input so if you save our file let me just duplicate there we
5:52:43
nos ocuparemos de eso en unos segundos, así que
will take care about that a few in a few seconds so
5:52:47
aquí puedes ver que ahora estamos reutilizando ese componente aquí una vez más
here you can see we are now reusing that component right here one more
5:52:50
y ahora es hora de entrar en los colores
time and now it's time to go inside the colors
5:52:53
y tenemos que eliminar este jsx de aquí, así que
and we have to remove this jsx from here so
5:52:56
voy a seleccionarlo, guardar un byte para todos ellos y voy a obtener mi contenedor de entrada aquí, está bien, así que no así, pero déjame cerrar
i'm going to select it save a byte to all of them and i'm going to get my input container right here okay so not like so but let me just close
5:53:06
los archivos semi y aquí puedes ver uh-huh
them semi file and here you can see uh-huh
5:53:09
me equivoqué en algo porque quité la etiqueta y no debería haberlo hecho, así que tenemos este título de entrada, sabes que voy a dejar todo esto
i messed up something because i removed the label and i shouldn't have done that so we have this input title you know i'm going to leave this all
5:53:20
formulario aquí, uh, no especificamos
form here uh we didn't
5:53:23
un color para ello o una etiqueta para ello, dejemos
specify a color to it or label to it let
5:53:27
que especifique algún tipo de etiqueta para que podamos diferenciar entre
me just specify some sort of a label to it so we can differentiate between
5:53:31
componentes, así que título de la barra lateral y
components so sidebar title and
5:53:34
luego tenemos el título de color también, así que solo proporcionaré colores, venderé
then we have color title as well so i'll just provide colors sell
5:53:37
mi archivo y aquí puedes ver que tenemos todos estos colores, pero ahora voy a eliminar esta etiqueta de aquí y solo voy a obtener mi entrada
my file and here you can see we have all of these colors but now i'm going to just remove this label from here and i'm going to just get my input
5:53:47
de allí, venderé mi archivo y tenemos diferentes
from there sell my file and we have different
5:53:50
tipos de entradas y aquí puedes ver que todo es ahora totalmente reutilizable de todos modos, así que eso fue solo una pequeña mejora dentro de nuestro código, así que solo
kind of inputs and here you can see everything is now totally reusable anyways so that was just a little bit improvement inside our code so we just
5:53:59
realmente refactorizamos nuestro código un poco
like really refactor our code like a little
5:54:03
pero también habrá una gran refactorización dentro
bit but there is also going to be a huge refactor inside
5:54:06
de todo este componente de entrada y todo este botón
all of this input component and all of this button
5:54:09
componente y todo ese componente de tarjeta, así que tendremos una
component and all of that card component so we will have a
5:54:12
gran refactorización más tarde, pero por ahora
huge refactor later but for now we
5:54:16
solo quiero tomar todo ese código de un componente y
i just kind of want to grab all of that code from one component and
5:54:19
para que podamos reutilizar ese componente una y otra vez, así que ahora es el momento de agregar un poco de funcionalidad a nuestra aplicación y luego vamos a reutilizar, quiero decir, como
so that we can reuse that component again and again so now it's time to pour a little bit of functionality to our app and then we are going to be reusing i mean like
5:54:27
luego vamos a refactorizar todos nuestros componentes a la versión final de esa refactorización
then we are going to be refactoring all of our component to the final version of that refactoring
5:54:32
bien, de acuerdo, así que ahora es el momento de proporcionar funcionalidad a
okay all right so now it's time to provide functionality to
5:54:36
nuestra aplicación, así que aquí lo que haré es
our app so here what i will do is
5:54:39
que voy a hacer algo un poco extraño que a
that i'm going to do a little bit of weird thing which a
5:54:42
mucha gente no le gustará, pero lo haré de todos modos
lot of people won't like it but i will do it anyways
5:54:46
porque no quiero repetirme una y otra vez, así que lo que haré es que voy a tratar este componente de aplicación como una tienda, si vienes del mundo de redox, así que
because i don't want to repeat myself again and again so what i will do is that i'm going to treat this app component as a store if you are coming from a redox world so
5:54:57
lo que significa que voy a colocar todo mi estado dentro de este componente de aplicación y luego voy a proporcionar ese estado a estos componentes usando una prop.
which means like I'm going to be placing all of my state inside this app component and then I'm going to be providing that state to these components by using a prop.
5:55:06
Así que si no te gusta este enfoque, está totalmente bien, puedes ir a cada uno de estos componentes y luego puedes crear tu estado separado y luego puedes cambiarlo allí si quieres.
So if you don't like this approach totally a-okay like you can go to each of these components and then you can create your separate state and then you can change it there if you want to.
5:55:16
Pero para mí, voy a tratar este componente de la aplicación como una tienda si vienes de un mundo Redux.
But for me I'm going to treat this app component as a store if you're coming from a Redux world.
5:55:21
Así que lo primero que tenemos que hacer es que voy a escribir
So the first thing which we have to do is that i'm going to just write
5:55:24
primero una consulta seleccionada
first of all a selected query
5:55:27
aquí o no consulta sino categoría, está bien
right here or not query but category okay
5:55:31
así que luego vamos a escribir establecer seleccionado
so then we are going to be just writing set selected
5:55:34
categoría y ahora se establecerá
category and it will be now set
5:55:37
en el estado de uso aquí y por defecto voy
to the use stat right here and by default i'm
5:55:40
a proporcionar un valor nulo, así que solo voy a proporcionar un
going to be providing a null value to it so i'm going to just provide a
5:55:44
poco de espacio allí y ahora eso está, pero ahora lo siguiente que tienes que hacer es que vamos a escribir o filtrar la entrada
little bit of spacing in there and now that's there but now the next thing which you have to do is that we are going to be writing or input filter
5:55:51
primero vamos a encargarnos de ese filtro de entrada, luego
first of all we are going to be taking care of that input filter then
5:55:55
vamos a saltar a los botones de radio, así que lo que haré
we are going to be jumping into the radio buttons so what i will do
5:55:58
es que voy a crear mi consulta y luego solo
is that i'm going to just create my query and then i'll just
5:56:01
usar como establecer consulta y será igual a la
use like set query and it will be equal to the
5:56:05
usar pestaña y por defecto voy a proporcionar un
use tab and by default i'm going to be providing a
5:56:08
radio totalmente vacío para ello y ahora, ¿qué más hacemos?
like totally empty radio to it and now what else do
5:56:11
tengo que hacer, voy a crear una función que será realmente útil para muchas funciones, para muchas cosas, para ser precisos
we have to do i'm going to be creating a function which will be really useful for a lot of functions for a lot of uh things to be precise
5:56:18
así que solo voy a escribir manejar y cambiar la entrada, así que cada vez que esto
so i'm going to just write handle and put change so whenever this
5:56:22
cambie la entrada, como cada vez que el usuario pase algún
input changes like whenever user passes some
5:56:25
dato a este componente, a este campo de búsqueda
data into this component into this uh search field
5:56:29
así que, ¿qué quieres hacer? Queremos obtener nuestro evento
so what do you want to do we want to get our event
5:56:32
aquí, como lo que sea que el usuario escriba
right here like uh like whatever the user type
5:56:35
y vamos a pasar eso aquí, así que evento, déjame escribirlo, evento, vamos, evento punto objetivo punto valor, ahí
and we are going to be passing it right here so event let me just write it event come on event dot target dot value there
5:56:44
vamos, t-a-r-g-e-t, ahí vamos, así que
we go t-a-r-g-e-t there we go so
5:56:47
ahora hemos creado esto con éxito, así que ahora lo siguiente que tenemos que hacer
now we successfully create this one so now the next thing which we have to do
5:56:50
es que tenemos que obtener todos nuestros datos que tenemos dentro de esta carpeta db, está bien, así que estamos
is that we have to get all of our data which we
5:56:53
tenemos dentro de esta carpeta de base de datos aquí, así que estamos
have inside this db folder right here okay so we are
5:56:56
vamos a obtener todos esos datos y vamos
going to be getting all of that data and we
5:56:59
vamos a iterar sobre esos datos, así que
are going to be iterating over through that data all right so the
5:57:02
lo primero que tienes que hacer es que tenemos que importarlo, así que solo escribiré como una base de datos aquí y voy a importar mi pequeña base de datos
first thing that you have to do is that we have to import it so i'll just write like a data base right here and i'm going to just import my little database so we
5:57:11
tenemos un dato o sabes que le voy a dar un nombre como productos, está bien
have a data or you know i'm going to give a name of like products okay
5:57:14
así que productos estará bien y voy a ir un nivel
so products will be fine and i'm going to go one level
5:57:17
y voy a ir a mi carpeta db y luego tenemos
and i'm going to go to my db folder and then we have
5:57:20
nuestros datos aquí, puedes darle cualquier nombre que quieras, pero en mi caso
our data right here you can give any name you want but in my case
5:57:24
estamos almacenando un producto, así que por eso yo
we are storing a product so that's why i
5:57:27
le doy un nombre de productos aquí, puedes darle mi dato si
give a name of products right here you can give my data if
5:57:30
quieres, pero aquí vamos a estar iterando sobre todos estos elementos que actualmente tenemos dentro de este arreglo y luego vamos a
you want to but here we are going to be iterating over through all of these items which we currently have inside this array and then we are going to be
5:57:37
realizar diferentes tipos de filtrado en el título en
performing different kind of filtering on title on
5:57:41
cómo lo llamamos, en el precio anterior y también en
what do we call it on previous price and also on
5:57:44
una compañía y también en un color y en una categoría
a company and also on a color and on a category
5:57:47
también, está bien, así que eso va a ser increíble también
as well okay so that's going to be awesome as
5:57:50
así que ahora lo siguiente que tienes que hacer es que solo voy a escribir llenar, uh, tercer elemento, ahí vamos y ahora será igual a productos.puntos, no elementos, sino productos.filtrar
well so now the next thing which you have to do is that i'm going to just write fill uh third items there we go and it will be now equals to products dot items not items but products dot filter
5:58:03
porque filtrado, ahí vamos porque
because filtered there we go because
5:58:06
vamos a estar iterando sobre todos estos elementos, ¿verdad?
we are going to be iterating over through all of these items right
5:58:09
aquí, cada uno de estos elementos y qué queremos hacer con ellos
here each of these items and what do we want to do with them
5:58:12
vamos a estar especificando o cada producto y
we are going to be just specifying or each product and
5:58:15
solo voy a establecer eso como una línea, así que ese producto.titulo
i'm going to just set that to like one liner so that product.title
5:58:19
en este caso solo estamos iterando sobre
in this case we are just iterating over through
5:58:22
todos estos datos aquí, como todos estos elementos
all of these datas right here like all of these items
5:58:25
aquí y solo estamos ocupándonos de este título, como si estuviéramos obteniendo este título de todos estos
right here and we are just taking care of this title like we are just getting this title from all of these
5:58:32
elementos aquí que actualmente tenemos, está bien, así que solo estamos
items right here which we currently have okay so we are just
5:58:35
usando eso y luego déjame convertir eso
using that and then let me just convert that
5:58:38
a minúsculas también, así que no importa si
to lowercase as well so it doesn't matter if
5:58:41
proporcionas como mayúsculas, simplemente se convertirá por defecto
you provide like uppercase it will just by default convert
5:58:44
a minúsculas y ahora voy a proporcionar el índice de
it to lowercase and now i'm going to just provide index of
5:58:48
y luego aquí voy a especificar mi consulta como lo que sea
and then here i'm going to be specifying my query like whatever
5:58:51
el usuario escribe y también voy a convertir eso a
the user type and i'm going to be also converting that to
5:58:54
minúsculas también y si eso no es igual a menos uno, está bien, así que simplemente lo arruiné aquí, déjame
lowercase as well and if that's not equal to minus one okay so i just messed it up here let me
5:59:01
cortar eso de aquí, voy a pegarlo justo aquí, así que si eso es
just cut that from here i'm going to paste it right here so if that's
5:59:04
no igual a menos uno, así que queremos obtener todos sus elementos
not equal to minus one so we want to get all of their items
5:59:07
y simplemente lo almacenamos dentro de estos elementos filtrados
and we just store that inside this filter items
5:59:10
aquí, así que ahora debajo de eso, así que eso va a ser todo
right here okay so now underneath that so that's going to be it
5:59:13
para el filtro de entrada, así que simplemente especificaré
for the uh input filter so i'll just specify
5:59:17
diferentes tipos de separadores, aquí voy a copiar eso, estoy
different kind of separators right here i'm going to copy that i'm
5:59:20
y voy a pegarlo justo aquí y ahora vamos a encargarnos de sus filtros de radio, así que tenemos estos filtros de radio aquí
going to paste it right here and now let's take care of their radio filters so we have these radio filters right
5:59:27
así que ahora déjame filtrar todos los datos una vez
here okay so now let me just filter all of the data once
5:59:31
el usuario hace clic en esto, cada uno, ¿cómo lo llamamos?
the user click on this each uh what do we call
5:59:34
cada filtro de radio, así que ¿qué tenemos que hacer? Primero, voy a escribir const handleChange
it this each radio filter okay so what do
5:59:37
y ahora será igual a evento y aquí, ¿qué
we have to do first of all i'm going to be just writing const handle change
5:59:41
estamos haciendo? Vamos a establecer la categoría seleccionada que estamos especificando aquí, así que
and it will be now equals to event and here what
5:59:44
tenemos la categoría seleccionada, y luego tenemos un conjunto de categoría seleccionada, y por defecto, simplemente estamos especificando el valor nulo para eso.
are we doing we are going to be just setting the set category selected category which we are specifying right here so we
5:59:52
así que simplemente los ejecutaré y aquí, ¿qué quieres hacer? Solo estás especificando el evento
we have selected category, and then we have a set selected category, and by default, we are just specifying the null value to it.
6:00:00
punto objetivo punto valor justo aquí, está bien, como sea
okay so i'll just execute them and here what do you want to do you are just specifying event
6:00:05
como cualquier tipo de entrada que el usuario seleccione
dot target dot value right here okay like whatever
6:00:08
así que quieres obtener el valor de cada uno
like whichever kind of input the user selects
6:00:11
evento justo aquí, como cualquier tipo de, ¿cómo lo llamamos?
so you want to get the value from that each
6:00:14
evento justo aquí como cualquier tipo de, uh, ¿cómo lo llamamos?
event right here like whichever kind of uh what do we call
6:00:18
selector de radio personalizado que el usuario selecciona, así que quieres obtener el valor de ese selector, está bien, así que así es como podemos obtener eso y almacenamos ese valor dentro de este evento de cambio aquí mismo
it custom radio selector user selects so you want to get the value from that selector okay so that's how we can get that and we store that value inside this handle change event right here
6:00:29
así que eso va a ser increíble también, así que ahora lo siguiente que
so that's going to be awesome as well so now the next thing which
6:00:33
tenemos que hacer es que tenemos que crear un filtro para
we have to do is that we have to create a filter for
6:00:36
¿cómo lo llamamos? un botón, así que botones
what do we call it a button so buttons
6:00:40
así que una vez que hacemos clic en cada uno de estos botones, así que
so once we click on each of these buttons so
6:00:43
¿qué quieres hacer? queremos proporcionar un filtro para eso, está bien, así que const handle, estoy creando todas esas funciones aquí mismo, está bien, que vamos a pasar a nuestros componentes
what do you want to do we want to provide a filter for that okay so const handle i'm i'm just creating all of that functions right here okay which we are going to be passing into our components
6:00:54
usando props muy rápidamente, así que solo voy a escribir set
by using a props very quickly so i'm going to just write set
6:00:58
una categoría seleccionada, una vez más estamos
a selected category once again we
6:01:01
simplemente seleccionando esa categoría seleccionada aquí y
are just selecting that selected category right here and
6:01:04
simplemente estamos cambiando ese estado como cuando alguien hace clic
we are just changing that state like when when somebody clicks
6:01:07
en él, así que ¿qué quieres hacer? solo quieres obtener el valor de
on it so what do you want to do you want to just get the value from
6:01:11
ahí, así que solo escribiré como event.target.value, está bien, así que eso es simple, eso fue simple como filtrar datos y esto también es simple como cuando alguien hace clic en cada uno de estos elementos
there so i'll just write like event.target.value okay so that's simple that was simple like how to filter data and this is also simple like when somebody clicks on each of these items
6:01:23
así que quieres filtrar a través de todos esos datos, está bien, así que eso es
so you want to filter through all of that data okay so that's
6:01:26
totalmente bien, así que ahora la última cosa que tú
going to be totally fine so now the final thing which you
6:01:29
tienes que hacer, no es una última cosa, sí, esta va a ser la función final que
have to do not a final thing yeah this is going to be the final function which
6:01:32
vas a crear dentro de este componente de aplicación, así que solo escribiré
you are going to be creating inside this app component so i'll just write
6:01:35
como función y aquí esto va a ser el principal
like function and here this is going to be the main
6:01:38
función donde vamos a hacer todo nuestro filtrado, así que escribiré
function where we are going to be doing all of our filtering so i'll
6:01:42
simplemente datos filtrados, así que este va a ser el nombre de mi función y qué estamos
just write filtered data so this is going to be the name of my function and what are we
6:01:48
obteniendo, primero estamos obteniendo todos los productos y luego
getting we are first of all getting all of the products and then we
6:01:51
vamos a proporcionar un seleccionado, como cualquier tipo de cosa
are going to be providing a selected like whichever kind of thing
6:01:54
que está actualmente seleccionada, ¿estamos seleccionando algo dentro de esta categoría?
is currently selected are we selecting something inside this category
6:01:58
o dentro de este precio o dentro de este color
or inside this price or inside this color
6:02:01
o estamos haciendo clic en algo aquí o
or we are clicking on something right here or
6:02:04
estamos escribiendo algo dentro de este campo de entrada como qué estamos
we are typing something inside this input field like what are
6:02:08
haciendo, por eso proporcionamos este perímetro seleccionado, um, adecuado o como quieras llamarlo y luego estamos especificando nuestra consulta
we doing that's why we provide this selected um proper perimeter or whatever you want to call it and then we are specifying our query
6:02:15
aquí, está bien, así que ahora dejemos
right here okay so now let
6:02:18
que escriba como dejar filtrar datos, quiero decir, como llenar
me just write like let filter data i mean like fill
6:02:22
terceros productos, así que filtrar
a third products so filter
6:02:25
productos y filmina es igual a todos nuestros productos, está bien, así que
products and filmina equals to all of our products okay so
6:02:28
esto va a ser todo para nuestros productos, ahora aquí déjame escribir un comentario para mí mismo como filtrando, filtrando, uh, elementos de entrada
this is going to be it for our products now here let me just write a comment for myself like filtering filtering uh input items
6:02:38
está bien, así que ahora ocupémonos de ese elemento de filtrado, así que voy a especificar si tenemos algún
okay so now let's just take care of that filtering item so i'm going to just specify if we have some
6:02:42
tipo de consulta, como si seleccionamos algo, así que qué quieres
sort of a query like if we selected something so what do
6:02:45
hacer, solo vamos a seleccionar esos datos de filtro
you want to do we are we are just going to be selecting that filter data
6:02:48
no datos de filtro, sino estos productos de filtro, voy a especificar justo
not filter data but this filter products i'm going to just specify right
6:02:52
aquí y ahora será igual a elementos de filtro
here and it will be now equals to filter items
6:02:55
así que elementos filtrados aquí, está bien, así que los que
so filtered items right here okay so which we
6:02:59
estamos obteniendo de estos elementos de filtro, déjame volver
are getting from this filter items let me just go
6:03:02
para que ustedes puedan ver todo un poco mejor, así que aquí estamos, lo que estamos haciendo, si tenemos algún tipo de consulta, así que solo vamos a establecer
back so you guys can see everything a bit better so here we what we are doing if if we have some sort of a query so we are going to be just setting
6:03:10
estos datos de filtro como todos los productos a través de esto
this filter data like all of the product through this
6:03:13
nuevo arreglo que estamos obteniendo de estos elementos de filtro aquí
new array which we are getting from this filter items right here
6:03:16
como estamos iterando sobre todos sus elementos y nosotros
like we are iterating over through all of their item and we
6:03:19
solo lo estamos especificando aquí y este filtro
are just specifying it right here and this filter
6:03:22
datos como todos nuestros datos ahora se establecerán en eso
data like all of our data will be now set to that
6:03:25
datos de filtro si especificamos algo dentro
filter data if we specify something inside
6:03:29
de esta entrada, así que eso va a suceder, está bien, así que esto va a ser
this input so that's going to be happening okay so this is going
6:03:32
todo para los elementos de filtrado en elementos de entrada de filtrado
to be it for the filtering items in filtering input items
6:03:35
y luego debajo de eso también vamos a escribir
and then underneath that then we are going to be also writing
6:03:38
un filtro seleccionado también
a selected filter as well
6:03:41
así que déjenme acercar un poco para que puedan ver todo un poco mejor y
so let me just zoom in a bit so you guys can see everything a bit better and
6:03:45
ahora aquí lo que haré es que voy a escribir seleccionado
now here what i'll do is that i'm going to just write selected
6:03:48
está bien, si algo está seleccionado
okay if something is selected so
6:03:51
de dónde viene lo seleccionado, lo seleccionado está
where is there selected coming from there selected is
6:03:54
viniendo de aquí, vamos a ejecutar esta función
coming from right here we are going to be executing this function
6:03:57
y vamos a proporcionar o primero nuestros productos, luego vamos a especificar como qué tipo de cosa está seleccionada
and we are going to be providing or first of all our products then we are going to be specifying like whichever kind of thing is selected are we
6:04:05
estamos seleccionando algo de una categoría o de un precio
selecting something from a category or from a price
6:04:08
o de un color o como qué tipo de selector
or from a color or like which kind of selector
6:04:11
tenemos, así que este va a ser el filtro seleccionado que
do we have so this is going to be selected filter which
6:04:15
vamos a escribir, así que ya tenemos nuestros productos filtrados
we are going to be writing so we already have our filter products
6:04:18
que está aquí y ahora será igual a productos filtrados uno
which is right here and it will now equals to filter products one
6:04:22
más tiempo y luego vamos a usar nuestro filtro
more time and then we are going to be using our filter
6:04:25
método aquí, así que vamos a iterar a través de este método de filtro, aquí podemos especificar solo una cosa singular
method right here so we are going to be iterating over through this filter method right here we can specify just a singular thing right
6:04:32
aquí, pero aquí lo que haré es que voy a usar mi
here but here what I will do is that I am going to use my
6:04:35
magia ESX, así que desestructuración de perímetro
ESX magic so perimeter destructuring
6:04:39
así que solo escribiré categoría, vamos a obtener
so I'll just write category we are going to be getting
6:04:42
nuestra categoría de estos datos aquí, así que vamos
our category from this data right here so we are
6:04:45
a obtener nuestra categoría, vamos a obtener nuestro color
going to be getting our category we are going to be getting our color
6:04:48
también, como este color de todos estos elementos
as well like this color from all of these items
6:04:51
vamos a obtener también nuestra empresa, vamos a
we are going to be also getting our company we are going to
6:04:54
también obtener nuestro nuevo precio y también vamos a
be also getting our new price and we are going to be also
6:04:57
obtener nuestro título, así que ahora déjenme obtener todo eso de todos
getting our title so now let me get all of that from all
6:05:01
estos datos aquí, así que lo que haré es que ya hemos
of this data right here so what i'll do is we already
6:05:04
seleccionado o categoría, déjenme solo obtener mi color y déjenme proporcionar mi empresa, ahí vamos, c-o-m-p-a-n-y, deletreo empresa
selected or category let me just get my color and let me just provide my company there we go c-o-m-p-a-n-y-d-i spell company
6:05:14
correctamente o no, déjenme ponerlo aquí y eso es genial, así que eso es todo
correctly or no let me just put it right here and that's awesome okay so that's that
6:05:20
ahora también vamos a proporcionar un nuevo precio
now we are going to be also providing a new price to it
6:05:23
y luego también vamos a obtener mi título
and then we are going to be also getting my title
6:05:27
aquí tenemos, déjame mostrarte
right here so we have uh let me just show you
6:05:30
así que tenemos este nuevo precio aquí y también
so we have this new price right here and we also
6:05:33
tenemos este título aquí, de todos modos, eso se ve bien
have this title right here anyway so that's looking okay
6:05:36
oh, estamos escribiendo estas llaves como extra
oh we are writing this curly braces like extra
6:05:40
llave, no deberíamos haber hecho eso, vamos a escribir o signo igual y ahora lo que vamos a hacer es que solo vamos a escribir categoría
curly brace we should not have done that we are going to be writing or equal to sign and now what we are going to be doing is that we are going to be just writing category
6:05:49
y ahora será igual a seleccionado aquí, de acuerdo y
and it will be now equals to selected right here okay and
6:05:53
si no estuvieras haciendo esto, en su lugar
if you if you weren't doing this instead we
6:05:56
vamos a hacer como estábamos haciendo, como producto
are going to be just doing is like we were doing like product
6:05:59
punto, no sé, categoría y ahora será igual
dot i don't know category and it will be now equals
6:06:02
a eso seleccionado, así que tendremos que hacer eso, pero
to that selected so we will have to do that but
6:06:06
ahora ya hemos desestructurado nuestros datos aquí, así que no tenemos
now we already destructure our data right here so we don't
6:06:09
que proporcionar este producto punto categoría, producto punto título
have to provide this product dot category product dot title
6:06:12
producto punto color y cosas así, así que voy a quitar
product dot color and stuff like that so i'm going to just remove
6:06:15
perdón, así que voy a quitar ese producto y
excuse me so i'm going to just remove that product and
6:06:18
vamos a escribir, no sé por qué estamos obteniendo este error, no estoy seguro de eso
we are going to be writing i don't know why we are getting this error i'm not sure about that
6:06:21
ahora vamos a escribir nuestro código así, como categoría, uh
now we are going to be writing our code like this like category uh
6:06:25
es igual a, uh, triple igual a
is equal to uh triple equal to
6:06:28
seleccionado y luego también vamos a verificar las otras cosas, pero
selected and then we are going to be also checking the other stuff but
6:06:31
si no estuviéramos escribiendo este código, como si no estuviéramos desestructurando
if we weren't writing this code like if we weren't destructuring
6:06:34
o elementos aquí, así que tendríamos que escribir primero, producto
or items right here so we would have to write first of all product
6:06:38
productos, para ser precisos, y luego vamos a seleccionar nuestra categoría, luego escribiremos como productos.color y luego productos.empresa
products to be precise and then we are going to be selecting our category then we will write like products.color and then products.company
6:06:46
los productos son nuevo precio, los productos son título, no tenemos
products are new price products are title we don't have
6:06:49
que hacer eso, solo vamos a desestructurar todo eso, así que voy a quitar estos productos de aquí y ahora vamos a
to do that we are going to be just destructuring all of that so i'm
6:06:52
voy a eliminar estos productos de aquí y ahora vamos a
going to remove these products from here and now we are going to be
6:06:56
escribir nuestra declaración o y el color será ahora triple
writing our or statement and color it will be now triple
6:06:59
igual a seleccionado y ahora déjame escribir uno más o
equal to selected and now let me just write one more or
6:07:02
declaración entonces tenemos una empresa y la empresa será
statement then we have a company and company will be
6:07:05
también establecida como seleccionada y luego tenemos o declaración entonces tenemos un nuevo precio que también será establecido como seleccionado déjame
also set to selected and then we have or statement then we have a new price will be also set to selected let me just
6:07:12
escribir una declaración más de o y el título será igual
write one more statement of or and title will be equals
6:07:16
a seleccionado así que ahora si guardas nuestro archivo y
to selected so now if you save our file and
6:07:19
todavía no estoy entendiendo todo eso
i am still not getting all of that
6:07:22
no sé por qué estamos obteniendo algún tipo de error o algo así
i don't know why we are getting some sort of error or something uh
6:07:25
supongo que estamos obteniendo algún tipo de
i guess we are getting some sort of
6:07:29
error pero no estoy seguro sobre eso déjame cerrar esto aquí algo estaba mal aquí así que ahora finalmente voy a pasar este código aquí y ahora voy a guardar mi archivo.
error but i'm not sure about uh let me just close it right here something was wrong in here so i'm going to now finally pass this code right here and Now I'm going to save my file.
6:07:40
Y sí, eso será todo para un filtro seleccionado. Así que ahora lo último que tienes que hacer es que tenemos que devolver algo aquí.
And yeah, that's going to be it for a selected filter. So now the final thing which you have to do is that we have to return something right here.
6:07:47
Así que eso será todo para esta declaración F y también para este filtro seleccionado.
So that's going to be it for this F statement and also for this selected filter.
6:07:52
Lo último que tienes que hacer es que tenemos que devolver estos datos de filtro. Y vamos a iterar sobre esos datos.
The final thing which you have to do is that we have to return this filter data. And we are going to be iterating over through that data.
6:07:59
Así que tenemos estos productos de filtro. Voy a usar un método map aquí para iterar sobre todos esos artículos.
So we have this filter products. I'm going to use a map method right here to iterate over through all of that items.
6:08:04
y aquí lo que vamos a hacer es que vamos a desestructurar algunas propiedades.
and here what we are going to be doing is that we are going to be destructuring a few properties.
6:08:08
Así que voy a desestructurar esa IMG y por cierto estamos
So I'm going to just destructure that IMG and by the way we
6:08:11
desestructurando todas sus propiedades y sus propiedades vienen
are destructuring all of their properties and their properties are coming
6:08:15
de todos estos artículos como actualmente estamos iterando sobre todos estos artículos y estamos obteniendo la imagen, el título, las reseñas de estrellas y todo ese tipo de cosas.
from all of these items like we are currently iterating over through all of these items and we are getting the image, the title, the star reviews and all of that kind of stuff.
6:08:24
Estamos desestructurando aquí y vamos a reutilizarlo aquí dentro de este componente de tarjeta y vamos a refactorizar todo este componente de tarjeta en un segundo pero por ahora
We are destructuring right here and we are going to be reusing it right here inside this card component and we will refactor all of this card component in a second but for now
6:08:35
lo que voy a hacer es que voy a desestructurar esas cosas
what i'm going to do is that i'm going to just destructure that stuff
6:08:38
así que voy a escribir imagen título estrella y
so i'm going to just write image title star and
6:08:41
asegúrate de que la ortografía sea totalmente correcta también haré
make sure the spelling is totally correct i will also do
6:08:45
mi mejor esfuerzo para escribir la ortografía correcta así que solo escribiré
my best to write the spelling correct so i'll just write
6:08:48
un nuevo precio y luego tenemos un nuevo no
a new price and then we have a new not
6:08:51
no nuevo precio pero sí un nuevo precio
not new price but yep a new price
6:08:54
sí, el nuevo precio está totalmente bien y
yeah new price is totally okay and
6:08:57
entonces volveré de aquí y voy a usar mi
then i will go back from here and i'm going to use my
6:09:00
llaves de apertura y no sé por qué estamos obteniendo este error anidado y
curly braces but i don't know why we are getting this nested error and
6:09:04
aquí vamos a renderizar nuestro componente de tarjeta
here we are going to be rendering or card component
6:09:07
así que aquí puedes ver que ahora solo lo importará justo aquí en la parte superior
so here you can see it will now just import it right here at the top
6:09:10
del archivo, así que ahora es hora de proporcionar todos estos
of the file so now it's time to provide all of these
6:09:13
datos en este componente de tarjeta como una prop y
data into this card component as a prop and
6:09:16
entonces vamos a reutilizarlo dentro de este componente de tarjeta, así que
then we are going to be reusing it inside this card component so
6:09:19
primero comenzaré con el math.random y voy a cerrar este componente justo aquí y eso va
i'll just first of all start with the math.random and i'm going to just close this component right here and that's going
6:09:26
a estar bien, así que aquí voy a guardar
to be fine okay so here i'm going to just save
6:09:29
este archivo para que obtenga, eh, eso
this file so that i get uh that
6:09:33
formato, así que eso fue todo para la clave y no
formatting so that was it for the key and do not
6:09:36
escribas código así, pero en este caso no estoy usando ningún uu
write code like this but in this case i'm not using any uu
6:09:39
id y cosas así, así que solo leí el método aleatorio, estoy
id and stuff so i just read method random i'm
6:09:43
simplemente escribiendo imagen y ahora se establecerá en imagen y
going to just write image and it will be now set to image and
6:09:46
ahora, ¿qué más tenemos que hacer? También vamos a escribir un título y el título también se establecerá en el título y también voy a proporcionar una estrella y también se establecerá en empezar el
now what else do we have to do we are going to be also writing a title and title will be also set to title and i am going to also provide a star and it will be also set to start the
6:09:54
versión de desestructuración de eso, para ser precisos y
destructuring version of that start to be precise and
6:09:58
ahora déjame obtener estas reseñas y finalmente tenemos
now let me just get these reviews and finally we
6:10:01
nuestro nuevo precio justo aquí y vamos a
have our new price right here and we are going to
6:10:04
también proporcionar un nuevo precio para ello, ahora si
be also providing a new price to it now if
6:10:07
vendes nuestros archivos, así que, ¿qué estamos haciendo actualmente? Primero que nada, dejemos
you sell our files so what are we currently doing first of all let
6:10:11
me revisar todo eso que estamos haciendo actualmente, así que ahora aquí puedes ver que primero estamos obteniendo, eh, como estos dos, déjame cortar eso de aquí y lo voy a colocar justo aquí así
me just review all of that stuff which we are currently doing okay so now here you can see we are just first of all getting uh like these two let me just cut that from here and i'm going to place right here like so
6:10:23
primero estamos especificando este estado en esto
first of all we are specifying this state into this
6:10:26
usado, eh, gancho justo aquí, así que hemos seleccionado categoría y
used uh hook right here so we have selected category and
6:10:29
entonces tenemos que seleccionar la categoría y
then we have select set selected category then we have a query
6:10:32
y establecer la consulta y por defecto estamos proporcionando el valor predeterminado
and set query and by default we are providing the default value
6:10:36
de nulo y cadena vacía aquí así que
of null and empty uh string right here so
6:10:39
entonces estamos creando esa función para el filtro de entrada
then we are creating that function for the input filter
6:10:42
aquí así que como cuando alguien está bien así que nuevo
right here so like when somebody okay so new
6:10:45
el precio no está definido así que
price is not defined uh we
6:10:48
tenemos este nuevo precio déjame solo
do have this new price let me just uh
6:10:52
entrar aquí y luego está bien tenemos el precio previo
come in here and then okay we have pre price
6:10:55
ahora voy a establecer eso como precio previo
now i'm going to set that to preview price
6:10:58
y ahora déjame solo revisarlo el nuevo precio es
and now let me just check him out new price is
6:11:01
no definido déjame solo actualizar mi navegador aún no está definido
not defined let me just refresh my browser still not defined
6:11:04
así que está bien vamos a venir aquí desde aquí olvidé incluirlo envía mi archivo y ahora el nuevo precio será definido aquí de todos modos así que esa es una gran historia.
uh okay so we are going to be coming here from here i forgot to include it send my file and now new price will be defined right here anyway so So that's a great story.
6:11:16
pero oye, aquí puedes ver ahora si alguien escribe algo en la entrada, vamos a obtener su valor.
But hey, here you can see now if somebody types something in the input, we are going to be getting their value.
6:11:23
entonces aquí estamos iterando sobre cada carácter de ese usuario, como lo que sea que el usuario escriba dentro de esta caja de entrada aquí.
Then here we are iterating over to every single character of that user, like whatever the user type inside this input box right here.
6:11:31
estamos iterando a través de eso y solo estamos obteniendo nuestros elementos filtrados.
We are iterating over through that and we are just getting our filtered items.
6:11:35
entonces tenemos nuestro filtro de radio y solo estamos iterando a través de todos estos filtros, como si el usuario hace clic en este o en este o en este,
Then we have our radio filter and we are just iterating over through all of these filters, like if the user click on this one or in this one or in this one,
6:11:44
solo estamos obteniendo el valor de eso o y luego tenemos este manejo de clic que será responsable de estos límites
we are just getting the value of that or and then we
6:11:47
aquí y luego finalmente tenemos esta función correcta
have this handle click and which will be responsible for these bounds
6:11:50
aquí y dentro de ahí vamos a especificar solo tres
right here and then finally we have this function right
6:11:53
parámetros así que tenemos este parámetro de productos luego tenemos seleccionado
here and inside there we are going to be just specifying three
6:11:56
y parámetro de consulta y vamos a especificar los valores en un segundo pero aquí puedes ver que solo estamos declarando una variable y la estamos especificando
parameters so we have this products parameter then we have selected
6:12:00
en los productos como cualquier tipo de productos que el usuario proporcione
and query parameter and we are going to be specifying the values in a just just in a second but here you can see we are just declaring a variable and we are specifying it
6:12:09
y luego lo que estamos haciendo es que solo estamos proporcionando
into the products like whichever kind of products the user provide
6:12:12
ese filtro para todos los elementos de entrada y luego
and then what we are doing is that we are just providing
6:12:16
dentro de ahí tenemos estos productos filtrados así que ¿qué son los productos filtrados?
that filter for all input items and then
6:12:19
dentro de ahí tenemos este filtro de productos, así que ¿qué es un filtro de productos?
inside there we have this filter products so what is a filter products
6:12:22
los filtros de productos son todos los productos que estamos
filter products are all of the products which we
6:12:26
especificando aquí y ahora será igual a filtros
are specifying right here and it will be now equals to filters
6:12:29
elementos filtrados y luego estamos proporcionando un filtro para
filtered items and then we are providing a filter for
6:12:32
los elementos seleccionados como para este tipo de uh
the selected items like for these kind of uh
6:12:35
bollos aquí podemos simplemente escribir este código sin
buns right here we can just write this code without
6:12:38
una destructuración, pero escribo este código con destructuración
a destructuring but i write this code with destructuring
6:12:42
porque no quiero escribir un código como este, como
because i don't want to write like a code like this like
6:12:45
producto punto y cosas así, entonces no tenemos que
product dot and stuff like that then we don't
6:12:48
simplemente escribir un producto, así que luego podemos eliminar eso
have to just write a product so then we can just remove that
6:12:51
y podemos simplemente escribir como producto si quisieras
and we can just write like product if you wanted
6:12:54
podemos seguir escribiendo este código y eso será totalmente válido
to we can still write this code and that will be totally valid
6:12:57
código, pero no me gusta este enfoque, quiero usar destructuración
code but i don't like this approach i want to use destructuring
6:13:01
así que por eso desestructuro todo ese código aquí, está bien, esto puede parecer un poco confuso para algunos desarrolladores, pero para mí es totalmente increíble
so that's why i destructure all of that code right here okay so this is this might look a little bit confusing to for some developer but for me that's totally awesome
6:13:11
para mí está totalmente bien y luego finalmente solo estamos devolviendo
for me that's totally okay and then finally we are just returning
6:13:15
todos nuestros productos filtrados aquí, así que ahora es hora de llamar a esto
all of our filtered products right here so now it's time to call this
6:13:18
función, así que hemos creado esta función, voy a llamar
function so we've created this function i'm going to just call
6:13:21
esta función aquí, así que voy a llamar a esta función ahora
this function right here so i'm going to just call this function right
6:13:24
aquí y voy a proporcionar algunas formas de hacerlo, así que primero voy a proporcionar productos que es nuestra base de datos
here and i am going to provide a few ways to it so i am going to first of all providing a products which is our database
6:13:31
aquí, así que estamos obteniendo todos sus productos de esta base de datos
right here so we are getting all of their products from this database
6:13:34
aquí y ahora lo siguiente que tienes que hacer es que tenemos
right here and now the next thing which you have to do is that we
6:13:37
también que proporcionar esta categoría seleccionada y tenemos
have to also provide this selected category and we
6:13:40
esta categoría seleccionada aquí, está bien
have this selected category right here okay
6:13:44
así que como cualquier tipo de cosa que seleccionamos, así que vamos a
so like whichever kind of thing we selected so we are going to
6:13:47
especificarlo aquí y luego finalmente tenemos nuestra consulta y
be specifying it right here and then finally we have our query and
6:13:50
tenemos esta consulta aquí para este inicio aquí, así que ahora llamamos a esta función con éxito, así que ahora lo siguiente que tenemos que hacer es que tenemos que almacenar en algún tipo de variable de resultado
we have this query right here for this start right here okay so now we successfully call this function so now the next thing which we
6:13:57
tenemos que almacenar en algún tipo de variable de resultado
have to do is that we have to store in some sort of a result variable
6:14:01
puedes darle a esta variable cualquier nombre que quieras, pero para mí
you can give this variable like any name you want but for me
6:14:04
está totalmente bien, así que ahora dejemos
that's totally okay so now let
6:14:07
guardar mi archivo, eso fue mucho escribir y fue una
me just save my file that was a lot of writing and that was a
6:14:10
gran explicación, así que ahora la última cosa que tienes que hacer es que
lot of explanation so now the final thing which you have to do is that
6:14:13
tenemos que proporcionar todos esos valores de estado como estas funciones y todos esos tipos de datos en cada componente aquí para que podamos reutilizar todos esos datos dentro de este componente, así que
we have to provide all of that state values like these functions and all of that kind of data into this each component right here so that we can reuse all of that data inside this component so
6:14:26
para la barra lateral, ¿qué vamos a pasar? estamos
for sidebar what are we are going to be passing we are
6:14:29
pasando este manejar cambio aquí, así que ¿dónde está
going to be passing this handle change right here so where is
6:14:32
ese manejar cambio? vamos a especificar este manejar cambio para
that handle change we are going to be specifying this handle change for
6:14:36
la barra lateral, así que cada vez que hagamos clic en este botón o este
the sidebar so like whenever click on this button or this
6:14:39
botón o este botón, no me importa, como sea el tipo de botón
button or this button i don't care like whichever kind of button
6:14:42
en el que haga clic el usuario, queremos seleccionar y queremos obtener ese valor y lo estamos especificando dentro de la categoría seleccionada, así que lo que tenemos que hacer es que voy a pasar mi manejar cambio
the user click on we want to select and we want to get that value and we are specifying that inside the set selected category so what we have to do i am going to just pass my handle change
6:14:54
como una propiedad, así que ahora lo que haré es que voy a entrar en esta barra lateral aquí.
into handle change as a prop so now what i will do is that i'm going to come inside this sidebar right here.
6:15:00
Déjame entrar en esta barra lateral y puedo desestructurar esto.
Let me just go inside this sidebar and I can destructure this.
6:15:04
Así que voy a usar mi método de desestructuración aquí y podemos registrar eso en nuestra consola si quieres.
So I'm going to just use my destructuring method right here and we can log that into our console if you want to.
6:15:10
Así que solo escribiré manejar cambio y ahora déjame abrir mi consola aquí y ahora déjame refrescarlo y aquí puedes ver que ahora estamos obteniendo esa función aquí.
So I'll just write handle change and now let me just open my console right here and now let me just refresh it and here you can see we are now getting that function right here.
6:15:18
Así que tenemos event.target.value. podemos ejecutar eso
So we have event.target.value. we can execute that
6:15:21
pero no lo vamos a hacer, así que solo voy a
function but we are not going to okay so i'm going to just
6:15:24
eliminar eso de aquí, así que ahora lo siguiente que tienes que hacer es
remove that from here so now the next thing which you have to do is
6:15:27
que tenemos que pasar este manejar cambio desde
that we have to pass this handle change from
6:15:30
ahí, voy a copiarlo y voy a
there i'm going to copy there and i'm going to
6:15:34
colocarlo en ambas áreas como una propiedad
place it in both of these areas as a prop
6:15:37
así que solo lo pasaré como una propiedad aquí, así que ahora si
so i'll just pass it as a prop right here okay so now if
6:15:40
guardas un archivo, así que tenemos esa función disponible dentro de esta categoría, tenemos esa función dentro de este precio y también tenemos esa función dentro de
you save a file so we have that function available inside this category we have that function inside this price and we also have that function inside
6:15:48
estos colores así que supongamos que quiero ir a los colores
these colors so like let's suppose if i want to go to the colors
6:15:51
quiero ir a los colores
i mean like that price and we can destructure it right here
6:15:54
y también podemos registrar en la consola enviar mi archivo y
and we can also console log it send my file and
6:15:58
enviar mi archivo y
let's just refresh it open my uh console right here
6:16:01
aquí puedes ver que tenemos esa función disponible dentro
and here you can see we have that function available inside
6:16:04
cada uno de estos componentes aquí así que voy a eliminar eso
each of these components right here so i'm going to just remove that
6:16:07
de aquí y ahora tenemos esta función disponible en todos sus componentes así que ahora lo siguiente que tienes que hacer es que voy
from here and so now we have this function available in all of their components so now the next thing which you have to do is that i'm going
6:16:13
a eliminar eso de aquí y voy a eliminar
to remove that from here and i'm going to remove
6:16:17
eso de aquí no vamos a eliminarlo de aquí
it uh from we are not going to be removing it from here
6:16:20
pero ahora que sabes que solo estamos pasando ese estado
but now that you know that we are just passing that state
6:16:23
valor como cada vez que cambiamos algo así que solo estamos
value like whenever we change something so we are just
6:16:26
pasándolo dentro de la barra lateral y luego también estamos pasando
passing it inside the sidebar and then we are also passing
6:16:30
dentro de cada uno de estos componentes aquí está bien
it inside each of these uh components right here okay
6:16:33
así que ahora lo siguiente que tienes que hacer es que tenemos que venir
so now the next thing which you have to do is that we have to come
6:16:36
a nuestro contenedor de entrada
to or input container
6:16:39
aquí quiero decir como en el componente de entrada aquí
right here i mean like in input uh component right here
6:16:42
así que voy a acercar un poco y aquí lo que haré es que
so i'm going to just zoom in a bit and here what i will do is that i
6:16:45
voy a especificar algunos elementos como algunos parámetros
am going to specify a few items like a few parameters
6:16:49
así que solo proporcionaré como manejar el cambio primero que todo así que esto
so i'll just provide like handle change first of all so this
6:16:52
va a ser el primer caso voy a eliminar eso estoy
is going to be the first case i'm going to remove that i'm
6:16:56
voy a proporcionar este manejar el cambio aquí así que el siguiente parámetro
going to provide this handle change right here so the next parameter
6:17:00
que voy a proporcionar es el valor es como qué tipo de valor vamos a especificar dentro de este contenedor de entrada luego después de eso también voy a proporcionar el título como
i'm going to be providing is the value is like which kind of value we are going to be specifying inside this input container then after that i'm going to be also providing the title like
6:17:09
qué tipo de título vamos a usar dentro de este componente y
which kind of title we are going to be using inside this component and
6:17:12
luego el nombre y también el color está bien así que
then the name and also the color okay so
6:17:15
un color no vamos a usarlo por muchas razones pero
a color we are not going to be using it for that much reasons but
6:17:18
lo pasaremos justo aquí, está bien, así que tenemos
we will pass it right here okay so we have
6:17:21
este contenedor de etiquetas de barra lateral justo aquí, la siguiente cosa que
this sidebar label container right here the next thing which
6:17:25
haré es que voy a usar este manejador de cambio, voy a
i will do is that i am going to use this handle change i'm going to
6:17:28
copiar allí y ahora, una vez que cambiemos algo, vamos a estar llamando a este método como manejador de cambio justo aquí y tenemos
copy there and now once we change something so we are going to be calling this method like handle change right here and we have
6:17:36
el tipo de radio, eso está completamente bien, ahora tenemos
the type of radio that's completely fine now we have
6:17:39
¿cómo lo llamamos? controlar este componente
to uh what do we call it control this component
6:17:42
así que si quieres controlar este componente, también vamos a
so if you want to control this component so we are going to be also
6:17:45
pasar este valor a él, así que voy a pegar este valor justo aquí
passing this value to it so i'm going to just paste this value right here
6:17:49
y ahora la última cosa que tienes que hacer es que también tenemos
and now the final thing which you have to do is that we also have
6:17:52
que copiar este nombre de aquí y voy a colocarlo
to copy this name from here and i'm going to place it
6:17:55
justo aquí, así que déjame colocarlo justo aquí como un nombre y sí, eso está completamente bien, pero ahora la siguiente cosa
right here so let me just place it right here as a name and yeah that's completely okay but now the next thing
6:18:02
que tienes que hacer es que también tenemos que especificar esto
which you have to do is that we also have to specify this
6:18:05
color, así que voy a copiar eso y también voy a
color so i'm going to just copy that and i'm going to also
6:18:09
proporcionar un estilo a él y luego aquí lo que haré
provide a style to it and then here what i will
6:18:12
es que voy a proporcionar un color de fondo de este color
do is that i'm going to just provide a background color of this color
6:18:15
justo aquí y ahora la última cosa que tienes que hacer es
right here and now the final thing which you have to do is
6:18:18
que tenemos que eliminar todo esto de aquí y
that we have to remove this all from here and
6:18:21
voy a copiar este título de aquí y voy a pasarlo justo aquí al azar, así que si vendes un archivo, déjame eliminar este espacio de
i'm going to copy this title from here and i'm going to just pass it right here randomly so if you sell a file let me just remove this space from
6:18:29
aquí semi archivo y aquí puedes ver que estamos obteniendo
here semi file and here you can see we are getting
6:18:32
estas cosas, pero eso no está funcionando y
these things but that's not working and
6:18:35
eso no está bien, Hussain, así que ¿qué tenemos que hacer? tenemos
that's not cool hussain so what do we have to do we
6:18:38
que entrar primero en una barra lateral justo aquí y
have to go inside first of all a sidebar right here and
6:18:42
luego tenemos que ir a las categorías y estamos
then we have to go into the categories and we are
6:18:45
reutilizando estas entradas justo aquí, así que
reusing these inputs right here so
6:18:48
la primera cosa que tenemos que hacer es que, uh, sabes qué
the first thing which we have to do is that uh you know what
6:18:51
voy a quitar todos ellos de aquí y primero voy a escribir una etiqueta y la primera no podemos cambiarla
i am going to remove all of them from here and i am going to just first of all write a label and the first one we cannot change
6:18:58
por eso vamos a escribirlo manualmente así que barra lateral
that's why we are going to be writing it manually so sidebar
6:19:01
etiqueta puedes verificar eso en tu tiempo libre si quieres, pero no quiero revisarlo ahora mismo, pero no podemos cambiarlo como creo
label you can check that in your spare time if you want to but i don't want to check it right now but we can't change it like i i think
6:19:09
creo en cada posible manera, pero podemos
i think of every possible way but we
6:19:12
cambiarlo ahora mismo, pero voy a cambiar eso a radio así que
can change it right now but i'm going to change that to radio so
6:19:16
primero tenemos que especificar eso a
the first all we have to specify that to
6:19:19
como um, tenemos que especificar eso manualmente
like um we have to specify that like manually
6:19:23
así que tenemos este cambio de manejo que estamos obteniendo
so we have this handle change which we are getting
6:19:26
de esto uh como una prop aquí
from this uh as a prop right here
6:19:29
así que tenemos acceso a su cambio de manejo, ya sabes que ahí y
so we have access to their handle change you already know there and
6:19:33
ahora, ¿qué más tienes que hacer? vamos a especificar el valor de nada
now what else do you have to do we are going to be specifying the value of nothing
6:19:36
porque vamos a seleccionar todo y el
because we are going to be selecting everything and the
6:19:39
nombre ahora se establecerá en prueba, está bien, así que eso es, luego voy
name will be now set to test okay so that's then i'm
6:19:42
a proporcionar también una tasa de gasto con la clase de marca de verificación y ahora como etiqueta voy a proporcionar todo, está bien, así que si vendemos el archivo y vamos a refrescar.
going to be also providing a spend rate with the class of check mark and now as a label i am going to provide all okay so if we sell file and let's Let's just refresh.
6:19:52
Así que aquí puedes verlo, ahora nos da todo aquí. Así que ahora lo siguiente que tienes que hacer es que vamos a reutilizar nuestra entrada básica
So here you can see it now gives us all right here. So now the next thing that you have to do is that we are going to be reusing our basic input
6:20:00
así que solo escribiré entrada aquí y ahora déjame
so i'll just write input right here and now let me just
6:20:03
cerrar eso y aquí tenemos que especificar todas nuestras props
close that and here we have to specify all of our props
6:20:06
así que solo voy a proporcionar como manejar uh manejar
so i'm going to just provide like handle uh handle
6:20:09
cambio y voy a copiar este cambio de manejo de
change and i'm going to copy this handle change from
6:20:12
aquí y solo lo voy a colocar aquí, está bien
here and i'm going to just place it right here okay
6:20:16
está bien, así que ahora lo siguiente que tienes que hacer es que tenemos que proporcionar un valor para este uh campo de entrada, así que
okay so now the next thing which you have to do is that we have to provide a value for this uh input field so we
6:20:22
tenemos unas zapatillas aquí y también voy a
have a sneakers right here and i'm going to also
6:20:25
proporcionar un título de uh zapatillas como
provide a title of uh sneakers as
6:20:29
bueno, debajo de eso también voy a proporcionar un nombre como
well underneath there i'm going to be also providing a name of like
6:20:32
uh no sé, amigo, uh prueba estará bien y voy
uh i don't know man uh test will be fine and i'm
6:20:35
voy a duplicar este componente una vez y luego
going to just duplicate this component like one time then
6:20:39
dos veces y tres veces, está bien, así que no vamos a cambiar este, tampoco, vamos a cambiar este, así que tenemos que cambiar
two time and three time okay so we are not going to be changing this one we are also not uh we will change this one so we have to change
6:20:46
eso de zapatillas a planos y también
that from sneakers to flats and also
6:20:50
este a planos también, está bien, y
this one to flats as well okay and
6:20:53
la prueba estaría bien, así que solo tendrás que cambiar este valor a
test would be fine so you will have to just change this value to
6:20:56
simplemente, no sé, sandalias estaría
just um i don't know sandal would
6:21:00
bien y este también será sandalias de playa y
be fine and this one will be also sand dolls and
6:21:03
eso estará bien y luego finalmente tenemos tacones y tenemos tacones aquí, está bien, así que ahora si guardas un archivo y aquí puedes ver que ahora estamos obteniendo zapatillas
that's going to be fine and then finally we have a heels and we have a heels right here okay so now if you save a file and here you can see we are now getting sneakers
6:21:14
y sandalias planas y tacones, así que este componente es
and flat sandals and heels so this component is
6:21:17
ahora totalmente reutilizable, como podemos reutilizar este componente
now totally reusable like we can reuse this component
6:21:21
en cualquier lugar dentro de nuestro programa de todos modos
anywhere inside our program anyway
6:21:24
así que eso está hecho, ahora lo siguiente que tenemos que hacer es que
so that's done now the next thing which we have to do is that we
6:21:27
tenemos que ir dentro de una etiqueta de precio, así que esta
have to go inside a price tag so this
6:21:30
etiqueta de precio aquí y primero voy a obtener mi manejador de cambio aquí y voy a eliminar este componente de aquí, está bien
price one right here and first of all i am going to just get my handle change right here and i am going to just remove this component from here okay
6:21:41
y también voy a copiar, uh, tú
and i'm going to also copy uh you
6:21:44
sabes, acabo de eliminar eso aquí, así que voy a copiar
know i just removed that right here so i'm going to just copy
6:21:47
este componente porque no podemos hacer nada, tenemos
this component because we cannot do anything we have
6:21:50
que especificarlo manualmente y
to just specify it manually value and
6:21:54
cosas así, así que este será para todos, tenemos una prueba y
stuff like that so this one will be for all we have a test and
6:21:58
esta será la prueba dos y tenemos todo lo que
this one will be test two and we have everything we
6:22:01
necesitamos y eso está bien de todos modos, así que eso está bien, así que ahora lo siguiente que tienes que hacer es que tenemos que obtener nuestra etiqueta de entrada
need and that's cool anyway so that's cool so now the next thing which you have to do is that we have to just get our input tag
6:22:08
aquí, que ya hemos estado usando, pero solo la eliminé
right here which we've been already using but i just deleted
6:22:11
ahí, pero primero vamos a proporcionar un manejador de cambio y luego tenemos nuestro manejador de cambio aquí, luego tenemos un valor
there but we are going to be first of all providing a handle change and then we have our handle change right here then we have a value
6:22:18
y ahora se establecerá en 50, luego tenemos un título y
and it will be now set to 50 then we have a title and
6:22:21
como título voy a especificar la cadena de como
as a title i am going to just specify the string of like
6:22:24
cero dólares a 50, así que ahora finalmente
zero dollar to 50 okay so now finally
6:22:27
voy a proporcionar un nombre como, uh, prueba dos aquí, así que ahora voy a enviar mi archivo, voy a duplicar eso unas cuantas
i'm going to just provide a name of like uh test two right here okay so now i'm going to send my file i'm going to duplicate that a few
6:22:36
veces, así que déjame volver y voy a duplicar
times so let me just go back and i'm going to just duplicate
6:22:39
eso como, no sé, tres veces, así que uno, dos
that to like i don't know three times so one two
6:22:42
tres y voy a cambiar el valor dentro de ellos
three and i'm going to just change the value inside them
6:22:45
así que ahora se establecerá en 100 y este
so it will be now set to 100 and this
6:22:48
uno se establecerá ahora en 50, 100, así
one will be now set to 50 100 like so
6:22:51
y este se establecerá ahora en 150, este
and this one will be now set to 150 this
6:22:55
uno se establecerá en 100 y 150, así que finalmente tenemos un 200 aquí y luego déjame quitar
one will be set to 100 and 150 okay so then finally we have a 200 right here and then let me just remove
6:23:03
eso de aquí y voy a especificar
that from here and i'm going to just specify
6:23:06
más de 150 dólares, está bien
over 150 dollars okay
6:23:10
así que si vendes un archivo y ahora aquí puedes ver que ahora nos dará
so if you sell a file and now here you can see it will now gives us
6:23:13
todas sus etiquetas aquí y todos sus productos de todos modos, así que
all of their labels right here and all of their products anyway so
6:23:17
eso va a ser increíble también, así que eso está funcionando
that's going to be awesome as well so that's working
6:23:20
la forma en que expandimos para trabajar, así que ahora lo siguiente que tenemos que hacer es que
the way we expand to work so now the next thing which we have to do is that
6:23:23
también tenemos que ir a los colores también, así que
we also have to go to the colors as well so
6:23:26
voy a ir a los colores, así que iré al precio una vez más y voy a copiar eso de aquí y voy a
i'm going to just go to the colors so i'll go to the price one more time and i'm going to copy that from here and i'm going
6:23:33
simplemente reemplazarlo aquí, está bien, así que debajo de eso voy
to just replace it right here okay so underneath that i'm
6:23:36
a obtener mi entrada y déjame cerrarlo
going to get my input and let me just close it
6:23:39
manualmente, oh vamos, así y tenemos que especificar estos valores, así que tenemos un cambio de manejo que ahora se establecerá en cambio de manejo y estamos recibiéndolo o no, no lo estamos, así que tenemos que
manually oh come on like so and we have to specify these values so we have a handle change will be now set to handle change and are we getting it or not we are not so we have to
6:23:52
desestructurarlo desde arriba y ahora lo que tenemos que hacer es simplemente especificar el valor de negro
destructure it from a top and now what we have to do we have to just specify value of black
6:23:58
y el título también se establecerá en negro
and the tile will be also set to black
6:24:01
y luego tenemos un nombre de prueba uno
and then we have a name of test one
6:24:05
así que esto va a ser la prueba uno y luego tenemos un color
okay so this is going to be the test one and then we have a color
6:24:08
totalmente negro una vez más y ahora voy a duplicar
of totally black one more time and now i'm going to duplicate
6:24:11
eso um no sé, tal vez uh uno
that um i don't know maybe uh one
6:24:14
dos tres cuatro veces, tal vez así que solo escribiré uno dos tres cuatro, así que solo duplico ese componente cuatro veces aquí, así que este es un color negro
two three four times maybe so i'll just write one two three four so i just duplicate that component four times right here so this is a black color
6:24:25
voy a reemplazar eso por un color azul y también
i'm going to just replace that to blue color and also
6:24:28
este color totalmente azul también y
this color totally blue as well and
6:24:32
también el color se establecerá en azul y
also the color will be set to blue and
6:24:35
voy a cambiar eso de un negro a qué
i'm going to also change that to from a black to what
6:24:38
lo llamamos uh rojo estará bien
do we call it uh red will be fine
6:24:41
pero el título debería estar en mayúsculas y estoy
but the title should be uppercase and i'm
6:24:44
voy a seleccionarlo una vez más y este se establecerá en verde y este también se establecerá en verde y voy a
going to select it one more time and this one will be set to green and this one will be also set to green and i'm going to
6:24:51
finalmente seleccionado a no
finally selected to I don't
6:24:54
sé blanco
know white
6:24:59
estaría bien, así que solo lo seleccionaré en blanco, el título sería
would be fine so I'll just select it it white the title would
6:25:03
blanco, pero no podemos ver el título y
be white but we cannot see the title and
6:25:06
sabes que acabo de darme cuenta de que el final también tenemos
you know what i just realized that the final one we also have
6:25:09
que crearlo manualmente, así que no podemos hacer nada para
to create it manually so like we cannot do anything for
6:25:12
este también, así que tenemos una etiqueta con la clase de barra lateral y
this one as well so we have a label with the class of sidebar and
6:25:16
luego nivel y contenedor también, está bien, solo eliminemos el html de aquí y voy a
then level and container as well okay let's just remove the html from here and i'm going to
6:25:24
solo especificar cómo lo llamamos o área de entrada
just specify what do we call it or input area
6:25:27
aquí y voy a cambiar el tipo a
right here and I'm going to just change the type to
6:25:30
como radio y en
like radio and on
6:25:33
el cambio ahora se establecerá en manejar
change will be now set to handle
6:25:37
el cambio ahí vamos y ahora después de eso también voy a proporcionar un tipo de radio, ya proporcionamos un tipo de radio, ¿no? sí, lo hicimos
change there we go and now after that I'm going to also provide a type of radio we already provide type of radio to it didn't we yeah we did
6:25:47
el valor ahora se establecerá en totalmente blanco y también estoy
the value will be now set to totally white and also i'm
6:25:51
voy a proporcionar un nombre de prueba uno también
going to provide a name of test one as well
6:25:54
así que ahora debajo de esta área de entrada, ¿qué tenemos que hacer? tenemos que
so now underneath this input area what do we have to do we have to
6:25:57
escribir sobre el span con una clase de marca de verificación y
write over span with a class of check mark and
6:26:01
también tenemos que especificar algún tipo de estilo en él, así que como
we also have to specify some sort of a styling into it so like
6:26:04
un estilo en línea, así que solo escribiré que el fondo se establecerá
an inline styling so i'll just write background will be now set
6:26:07
en blanco total y también proporcionaré un borde de
to totally white and i'm going to also provide a border of
6:26:11
dos píxeles sólidos totalmente negros, está bien, así que ahora si guardamos nuestro archivo y aquí puedes ver
uh two pixels solid totally black okay so now if we save our file and here you can see
6:26:16
que ahora estamos obteniendo todos estos colores aquí, así que si haces clic en él y
we are now getting all of these colors right here so if you click on it and
6:26:20
todos esos colores aquí, pero no podemos ver ese blanco
all of that colors right here but we cannot see that white
6:26:23
podemos cambiar la etiqueta de eso si quieres, pero
one we can change the label of that if you want to but
6:26:27
sabes que voy a cambiar ese color a algo más como
you know i'm going to change that color to something else like
6:26:30
también voy a poner un color blanco en
i'm going to also put a color of white to
6:26:34
no blanco, pero negro estará bien, así que si vendes eso y sabes qué, voy a quitar
it not white but black will be fine so if you sell that and you know what i'm going to remove
6:26:41
eso de aquí y como una etiqueta donde
that from here and as a label where
6:26:44
está ese span de marca de verificación y
is that span check mark and
6:26:48
entonces tenemos un texto blanco o un blanco
then we have a white ways or white text
6:26:51
¿acaso solo pusimos un texto blanco o algo así, está bien?
did we just put a white text or something okay
6:26:54
tenemos que ponerlo aquí, así que solo voy a colocar mi texto blanco
we have to put it right here so i'm going to just place my white text
6:26:57
y ahora aquí puedes ver que ahora lo estamos obteniendo justo ahí, no sabía, como, está bien, así que ahora está funcionando totalmente, así que tenemos blanco, verde, azul, rojo y todo eso
and now here you can see we are now getting it right there i didn't know like okay so now it's totally working so we have white green blue red and all of that
6:27:07
pero también tenemos que especificar sobre todo aquí, así que solo proporcionaré el nombre de clase de, eh, el nombre de clase de
but we also have to specify over all right here so i'll just provide class name of uh class name of
6:27:14
todo aquí, está bien, así que solo voy a proporcionar todo
all right here okay so i'm going to just provide all
6:27:17
aquí, así que si guardas eso y aquí puedes ver que no usará eso
right here so if you save that and here you can see it will not use that
6:27:20
el degradado lineal aquí, ¿por qué es eso?, eso es
linear gradient right here why is that that's
6:27:23
porque ya declaramos el estilo dentro de todo esto, quiero decir, dentro de este archivo color.css y así es como podemos especificar
because we already declared the styling inside this all i mean like inside this color.css file and this is how we can specify
6:27:31
y así es como podemos proporcionar todo, así que eso
and this is how we can provide all righty so that
6:27:34
fue una gran refactorización, así que ahora lo siguiente que tenemos que hacer es que
was a huge refactor so now the next thing which we have to do is that
6:27:37
tenemos que encargarnos de esta tarjeta y renderizar
we have to take care of this card and render
6:27:41
tarjeta apropiada basada en la selección del usuario
appropriate card like based on the user selection
6:27:44
o cualquier tipo de filtro que el usuario realice
or whichever kind of filter the user perform all
6:27:47
bien, así que la siguiente cosa que tienes que hacer es que tenemos que pasar datos apropiados
right so next thing which you have to do is that we have to pass appropriate
6:27:51
a cada uno de estos componentes, así que lo que haré es que primero pasaré mi consulta a esta navegación, así que solo escribiré consulta y
data to each of these components so what i will do is that i'm going to first of all pass my query into this navigation so i'll just write query and
6:28:00
también voy a proporcionar como manejar el cambio de entrada
and i'm going to also provide like handle input change
6:28:03
así que solo voy a copiar eso y lo voy a colocar aquí mismo, así que
so i'm going to just copy that and i'm going to place it right here so
6:28:06
la siguiente cosa que tenemos que hacer es que también tenemos que proporcionar o manejar
the next thing which we have to do is that we also have to provide or handle
6:28:09
el evento de cambio aquí mismo en este componente, así que solo
change event right here into this component so i'll just
6:28:12
lo proporcionaré como un aviso, así que tenemos manejar cambio
provide it as a prompt so we have handle change
6:28:16
ahí vamos y no un manejar cambio, sino um
there we go and not a handle change but um
6:28:19
manejar clic para ser preciso, no un manejar cambio, sino manejar
handle click to be precise not a handle change but handle
6:28:22
clic, voy a copiar eso y lo voy a colocar aquí también, así que la última cosa que tienes que hacer es que vamos a pasar todos nuestros
click i'm going to copy there and i'm going to place it right here as well so the final thing which you have to do is that we are going to be passing all of our
6:28:29
datos de filtro a este componente de productos y luego
filter data into this products component and then we
6:28:32
vamos a iterar sobre ese componente y luego vamos a
are going to be iterating over through that component and then we are going to
6:28:36
renderizar cada uno de estos elementos aquí mismo, como la imagen apropiada
be rendering each of these items right here like the appropriate image
6:28:39
el título y todas esas cosas, así que aquí puedes ver
the title and all of that kind of stuff so here you can see
6:28:42
solo tenemos nuestros resultados aquí, voy a copiar eso y
we just have our results right here i'm going to copy that and
6:28:45
lo voy a colocar aquí como una propiedad, pero
i'm going to place it right here as a prop but
6:28:48
déjame mostrarte qué es este resultado, así que ya he
let me just show you like what is this result so i've already
6:28:51
escrito todo el código para ello, pero aquí lo que estamos haciendo es que estamos obteniendo todos esos datos de ese elemento, quiero decir, de su base de datos que tenemos
write all of the code for it but here what we are doing is that we are getting all of that data from that item i mean like from their database which we have
6:28:59
aquí, así que voy a abrir eso rápidamente, así que aquí puedes ver que
right here so i'm going to just open there real quickly so here you can see we
6:29:02
tenemos diferentes tipos de imágenes, diferentes tipos de títulos, tenemos estrellas
have different kind of images different kind of title we have star
6:29:05
reseñas, nuevo precio, quiero decir, precio anterior, nuevo precio
reviews new price i mean like previous price new price
6:29:08
compañía, color y todas esas categorías aquí
company color and all of that categories right here
6:29:12
así que aquí solo estamos desestructurando todos sus datos
so here we are just destructuring all of their data
6:29:15
de cada uno de esos componentes y estamos pasando todos sus
from each of that component and we are passing all of their
6:29:18
datos a este componente de tarjeta como una propiedad, así que aquí puedes
data to this card component as a prop so here you can
6:29:21
ver que tenemos imagen, tenemos título y todas esas cosas aquí estamos pasando todos sus datos dinámicamente a mi componente de tarjeta, así que tendremos acceso a todos esos datos dinámicamente dentro de mi componente de tarjeta.
see we have image we have title and all of that kind of stuff right here we are passing all of their data dynamically into my card component so we will have access to all of that data dynamically inside my card component.
6:29:33
Así que lo que haré es que voy a enviar mi archivo aquí. Y ahora lo siguiente que tienes que hacer es que voy a ir a mi sección de productos aquí.
So what I will do is that I'm going to just send my file right here. And now the next thing which you have to do is that I'm going to go into my products section right here.
6:29:41
Y voy a eliminar todas estas cosas de aquí. Voy a eliminar eso.
And I'm going to just remove all of this stuff from here. I'm going to remove that.
6:29:45
Lo siguiente que tienes que hacer es que ya pasamos este resultado aquí. Así que solo voy a copiar eso.
The next thing that you have to do is that we already passed this result right here. So I'm going to just copy that.
6:29:50
Y voy a desestructurarlo aquí.
And I'm going to destructure it right here.
6:29:54
Así que solo voy a desestructurar eso y lo voy a pasar aquí. Está bien.
So I'm going to just destructure that and I'm going to just pass it right here. Okay.
6:29:59
Así que si solo lo pasas aquí, si guardas nuestro archivo, nada
So if you just pass it right here if you save our file nothing
6:30:02
sucederá, así que ahora lo último que tienes que hacer es
will happen so now the last thing which you have to do is
6:30:06
que tenemos que ir a este componente de tarjeta y tenemos que
that we have to go to this card component and we have to
6:30:09
simplemente refactorizar el alibir, así que déjame mostrarte que voy a eliminar
just refactor the alibir so let me just show you that i'm going to just remove
6:30:12
eso de aquí, voy a guardar mi archivo y ahora voy
that from here i'm going to save my file and now i'm
6:30:15
a ir a mi componente de tarjeta aquí, así que ahora aquí puedes ver que tenemos como la misma imagen aquí, tenemos el
going to go into my card component right here so now here you can see we have like the same image right here we have the
6:30:22
mismo título, tenemos las mismas reseñas y
same title we have the same reviews and
6:30:25
todas esas mismas y pre, quiero decir, como todos sus precios anteriores
all of that same and pre i mean like all of their previous price
6:30:29
y todos sus nuevos precios, así que aquí puedes ver que tenemos datos codificados en todos estos componentes de tarjeta y no queremos
and all of their new price right like here you can see we have hard
6:30:33
eso, queremos renderizar contenido dinámico en estos componentes
coded data into all of these card component and we don't want
6:30:36
así que como imagen dinámica y todos sus títulos y
that we want to render a dynamic content into these components
6:30:39
así que como imagen dinámica y todo su título y
so like dynamic image and all of their title and
6:30:43
calificación y todo ese tipo de cosas, así que voy a refactorizar este componente desde cero, así que ahora si quieres refactorizar este componente
rating and all of that kind of stuff so i'm going to refactor this component from scratch so now if you want to refactor this component
6:30:50
primero voy a entrar en mi componente de aplicación y solo voy a copiar
first of all i'm going to go into my app component and i'm going to just copy
6:30:53
esto como esta desestructuración, puedo escribirlo manualmente
them like these destructuring i can type it manually
6:30:57
pero tomará mucho de mi tiempo, así que solo lo voy a colocar aquí
but it will take a lot of my time so i'm going to just place it right
6:31:00
bien, así que ya hemos desestructurado todos esos datos
here okay so we already destructure all of that data
6:31:03
que estamos pasando a este componente como un problema
which we are passing to this component as a problem
6:31:06
así que aquí puedes ver que solo desestructuramos la imagen y todo ese tipo de datos
so here you can see we just destructure image and all of that kind of data so
6:31:10
lo siguiente que tienes que hacer es que voy a dejar esta clase y todo ese alt aquí, solo voy a seleccionar mi imagen y voy a eliminarlas y aquí lo que
the next thing that you have to do is that i'm going to leave this class and all of that alt right here i'm going to just select my image and i'm going to just remove them and here what i
6:31:18
haré es que solo voy a copiar esta img y
will do is that i am going to just copy this img and
6:31:21
la voy a pegar aquí mismo, así que ahora si hago eso y
i'm going to just paste it right here okay so now if i do that and
6:31:24
si guardo mi archivo y solo esperemos un momento
if i sell my file and let's just wait for it so
6:31:28
aquí puedes ver que ahora solo renderizará todo su contenido dinámico
here you can see it will now just render all of their dynamic content right
6:31:31
aquí como todas sus imágenes, está bien, eso es genial, así que
here like all of their images right here all right that's cool so
6:31:34
lo siguiente que tienes que hacer es que también tenemos
the next thing which you have to do is that we also have
6:31:37
que proporcionar ese título aquí mismo, así que solo voy a pasar mi título aquí solo por datos aleatorios y ahora lo siguiente
to provide that title right here so i'm going to just pass my title in here just for random data and now the next thing
6:31:43
que tienes que hacer es que aquí voy a eliminar este zapato y
which you have to do is that here i am going to just remove this shoe and
6:31:47
lo voy a reemplazar con mi título, está bien, así que ahora
i'm going to replace it with my title okay so now
6:31:50
si guardas tu archivo, aquí puedes ver que tenemos este tipo diferente
if you save or file so here you can see we have this different kind
6:31:53
de títulos aquí y no te preocupes, voy a cambiar las fuentes y
of titles right here and don't worry i'm going to change the fonts and
6:31:56
todo ese tipo de cosas en un segundo, pero solo quiero
all of that kind of stuff just in a second but i just kind of want to
6:31:59
proporcionar diferentes tipos de datos en él, uh, dinámicamente, así que lo siguiente
provide different kind of data into it uh dynamically so next
6:32:02
que tienes que hacer es que voy a eliminar esa estrella de aquí
thing which you have to do is that i'm going to just remove that star from here
6:32:06
quiero decir, como ese ícono y lo voy a reemplazar con una estrella, está bien, así que solo lo copiaré cuatro veces
i mean like that icon and i'm going to just replace it with star okay so i'll just copy there four times you
6:32:13
puedes proporcionar tres o dos veces o lo que sea, así que solo voy a pasar
can provide three or two times or whatever so i'm going to just pass
6:32:16
eso cuatro veces, voy a enviar mi archivo y aquí estamos
it four times i'm going to send my file and here we are
6:32:19
obteniendo, uh, este color negro, ¿qué fue eso?
getting uh this black color what was that
6:32:22
uh, clase que proporcioné, olvidé el nombre de esa clase, déjame
uh class i provide i forgot the name of that class let
6:32:25
regresar, está bien, así que es esta clase
me just go back okay so it's this class
6:32:28
así que voy a copiar eso de un componente, voy a eliminar
so i'm going to just copy that from one component i'm going to delete
6:32:31
eso, luego voy a ir a mis datos y voy a
it then i'm going to go into my data and i'm going
6:32:34
voy a seleccionar mi bien, voy a
to select my okay i'm going to
6:32:37
simplemente seleccionar ahí y voy a presionar ctrl d y voy a seleccionar todos estos elementos aquí, así que ya proporcionamos este estilo, pero no sé por qué no está funcionando
just select there and i'm going to hit ctrl d and i'm going to select all of these items right here so we already provide this style but i don't know why it's not working
6:32:46
nombre de clase de eso, déjame pasarlo manualmente
class name of that let me just pass it manually
6:32:49
supongo que he estropeado algo en ello, oh, solo escribí calificaciones
i guess i messed up something in it oh i just write ratings
6:32:52
en lugar de calificación, solo proporciono s aquí, así que
instead of rating i just provide s in here so
6:32:55
voy a guardar mi archivo y voy a guardar este archivo
i'm going to just save my file and i'm going to save this file
6:32:58
también, pero solo eliminará estas estrellas, sabes, voy a renderizarlo dinámicamente, así que solo escribiré estrella, no inicio, sino solo estrella y cuatro veces tú
as well but it will just remove these stars you know i'm going to just render it dynamically so i'll just write star not start but just start and four times you
6:33:08
puedes proporcionar tres veces si quieres, pero para mí cuatro
can provide three times if you want to but for me four
6:33:11
la estrella estaría totalmente bien, así que estamos totalmente
star would be totally fine okay so we are totally
6:33:14
llegando, lo siguiente que tienes que hacer es que
getting there the next thing that you have to do is that
6:33:17
voy a proporcionar, um, reseñas
i am going to also provide um reviews
6:33:20
aquí, así que solo escribiré como reseñas aquí
right here so i'll just write like reviews in here
6:33:23
y luego, finalmente, como etiqueta, voy a eliminar
and then finally uh as a label i'm going to remove
6:33:26
esta etiqueta de aquí, bueno, sabes, voy a eliminar este nivel y voy a pasar mi nuevo, no nuevo, sino precio anterior y aquí voy a renderizar
this label from here well you know what i'm going to just remove this level and i'm going to just pass my new not new but uh previous price and here i am going to just render
6:33:36
mi nuevo precio aquí, así que si vendes un archivo y aquí tú
my new price right here so if you sell a file and here you
6:33:39
puedes ver que tenemos nuestro precio anterior y tenemos un nuevo precio aquí
can see we have our previous price and we have a new price right
6:33:42
para cada uno de estos elementos aquí, está bien, así que tenemos
here for each of these items right here okay so we have
6:33:45
todo este contenido dinámico aquí, probablemente puedes más
all of this dynamic content right here you can probably more
6:33:48
que eso si quieres, pero para mí está totalmente bien, así que
than that if you want to but for me that's totally okay so
6:33:51
aquí puedes ver que ya pasamos o, um, ¿cómo lo llamamos? o la funcionalidad de filtro aquí, si hago clic en las zapatillas, simplemente usará las zapatillas, si hago clic en los planos
here you can see we already passed or um what do we call it or filter functionality right here if i just click on the sneakers it will just use the sneakers if i click on the flats
6:34:01
está bien, no tenemos artes de caída, está bien
okay we don't have fall arts okay
6:34:05
así que voy a ir a mis planos, este componente
so i'm gonna go into my flats this component
6:34:08
¿dónde está la categoría? así que voy a entrar rápidamente en
where is the category so i'm gonna just go into
6:34:11
la categoría y en lugar de fallets
category very quickly and instead of fallets
6:34:15
voy a cambiar eso a planos
i'm gonna just change that to flats
6:34:18
zapatos planos, apuesto y
f l a t s i bet and
6:34:21
voy a cambiar este aquí también, así que si guardas nuestro archivo y ahora déjame refrescarlos, voy a hacer clic en zapatos planos, nos dará
i'm going to change this one right here as well so if you save our file and now let me just refresh them i'm gonna click on flats it will give us
6:34:28
sandalias splats y no soy bonita
splats sandals and i'm not pretty
6:34:31
seguro que son estas sandalias o supongo que estas
sure about are these sandals or i guess these
6:34:34
son todas zapatillas, pero no sé, solo puse un dato aleatorio
are all sneakers but i don't know i just put a random data
6:34:37
aquí no tengo idea de todas estas cosas, así que tacones
in here i don't have any idea about all of these stuff so heels
6:34:40
entonces tenemos todos los artículos aquí una vez más
then we have all of the items right here one more time
6:34:44
y tenemos de cero dólares a 50, aquí puedes ver que solo estamos obteniendo los 50 artículos, luego estamos obteniendo un artículo de cien dólares
and we have uh from zero dollar to 50 here you can see we are just getting the 50 uh items then we are getting a hundred dollars item
6:34:51
entonces estamos obteniendo 150 y finalmente tenemos 200 artículos aquí, así que si haces clic en todos los colores, aquí puedes ver que solo nos dará
then we are getting 150 and then finally we have 200 of items right here so if you click on all of the colors so here you can see it will just gives
6:35:00
todos los colores aquí, si solo quieres un color negro, así que
us all of the colors right here if you just want a black color so
6:35:03
voy a hacer clic en negro y ahora nos dará el color negro aquí, si
i'm going to just click on black and it will now give us black color right here if
6:35:06
solo quieres obtener un azul, tenemos rojo, tenemos
you just want to get a blue we have red we have
6:35:10
verde y también tenemos un color blanco aquí, está bien, así que
green and we also have a white color right here okay so
6:35:13
se ve genial, pero ahora voy a hacer clic en todos los productos
that's looking cool but now i'm going to just click on all of the products
6:35:16
así que eso no está funcionando, eso
so that's not working that's
6:35:19
no está funcionando, tenemos que encargarnos de eso muy rápido, así que
not working we have to take care of that really quickly so
6:35:22
eso está en este componente recomendado, así que voy a copiar el
that's in this recommended component so i'm going to just copy the
6:35:26
nombre y voy a entrar allí, ¿viste
name and i'm going to go into there did you
6:35:29
cuán rápido llegué a este componente, eso es
saw like how much fast i came into this component that's
6:35:32
porque no tomaste mi curso de grabador de historias visuales, así que
because you didn't take my visual story recorder course so
6:35:36
tienes que entrar en ese curso y tienes que tomar
you gotta go into that course and you have to take
6:35:39
ese curso, oh, y esta es totalmente mi garantía de que
that course oh and this is totally my guarantee that
6:35:42
al final de ese curso de grabador de historias visuales, si tomaste
by the end of that visual story recorder course if you took
6:35:45
ese curso, te vas a estar llamando a ti mismo un sonic
that course you are going to be calling yourself as a sonic
6:35:48
quarter, no quiero ir tan rápido en la grabación porque
quarter i don't want to go that much fast in the recording because
6:35:52
mucha gente se confunde, como hosan, ¿cómo lograste esto tan rápido?
a lot of people get confused like hosan how did you get this fast
6:35:55
en este componente y ¿cómo escribiste este código tan rápido?
into this component and how did you write this code that much fast
6:35:58
y todo ese tipo de cosas, así que por eso no quiero simplemente ir
and all of that kind of stuff so that's why i don't want to just go
6:36:01
tan rápido en mi grabación, así que confía en mí, como cuando estoy
that much fast in my recording so trust me like when i'm
6:36:04
trabajando en mi proyecto personal, simplemente voy
working on my personal project i just go
6:36:07
como loco y si eres programador
like crazy and if if you're a programmer
6:36:10
y te sientas solo, eh, conmigo, vas a estar llamándome
and you sit just uh with me you're going to be calling me
6:36:13
un loco porque escribo como, eh, ya sabes
a crazy because i type like a uh you know
6:36:16
esa es otra historia, voy a dejar eso de todos modos
that's another story i'm going to just leave that anyways
6:36:20
voy a entrar en mi componente de aplicación aquí y aquí puedes
i'm going to go into my app component right here and here you
6:36:23
ver que simplemente pasamos este manejador de clic aquí, como cada vez que
can see we just pass this handle click right here like whenever
6:36:26
alguien hace clic en este componente, así que ¿qué quieres hacer aquí?
somebody clicks on this component so what do you want to do here
6:36:29
puedes ver que tenemos el manejador de clic aquí, así que
you can see we have handle click right here so
6:36:32
simplemente estamos obteniendo sus datos y luego los estamos filtrando aquí, está bien, así que ya sabes todo eso, pero ahora déjame llegar allí, que es, eh, manejar
we are just getting their data and then we are just filtering it right here okay so you already know all of that stuff but now let me just get there which is uh handle
6:36:43
clic, pero sabes qué, simplemente voy a eliminar eso, pero primero, déjame crear un componente, un componente separado para estos botones, no se ven tan bien
click but you know what i'm going to just remove there but first of all let me just create a component separate component for these buttons they aren't looking that cool
6:36:53
eh, ya construimos ese componente, pero olvidé refactorizar
uh we already built that component but i forgot to refactor
6:36:56
este componente, simplemente escribimos un botón aquí, así que voy a encargarme
this component we just wrote a button right here so i'm going to just take
6:36:59
de eso, voy a proporcionar algunos, eh, ¿qué?
care of that i'm going to just provide a few um what
6:37:03
lo llamas, voy a pasar algunos valores, como, simplemente pasaré estos valores como en clic
do you call it i'm going to just pass a few values like i'll just pass this values like on click
6:37:10
un manejador y también voy a proporcionar un valor para
a handler and i'm going to also provide a value to
6:37:13
esto, tomará algún tipo de valor y también voy a proporcionar un título para
it it will take some sort of a value and i'm going to also provide a title for
6:37:16
este botón, así que lo que haré es que simplemente voy a eliminar eso y
this button so what i will do is that i'm going to just remove that and
6:37:20
voy a reemplazarlo con este botón aquí, está bien, así que ahora
i'm going to just replace it with this button right here okay so now
6:37:23
la siguiente cosa que tienes que hacer es que voy a escribir en clic, como cuando
the next thing which you have to do is that i'm going to just write on click like when
6:37:26
alguien hace clic en este botón, simplemente queremos activar esto
somebody clicks on this button we just want to fire this
6:37:29
parámetro justo aquí este parámetro um evento justo aquí que estamos pasando y la siguiente cosa que tenemos que hacer es que también tenemos que pasar nuestro valor que estamos
parameter right here this parameter um event right here which we are passing and the next thing which we have to do is that we also have to pass our value which we are
6:37:37
obteniendo dinámicamente y también voy a proporcionar un valor para ello está bien
getting dynamically and i'm going to also provide a value to it okay
6:37:40
y luego voy a dar algún tipo de nombre de clase como
and then i'm going to just give some sort of a class name like
6:37:43
los botones estarían bien está bien eso va a ser totalmente
buttons would be fine okay that's going to be totally
6:37:46
bien y solo voy a pasar eso
fine and i'm going to just pass that
6:37:49
título finalmente así que solo escribiré título t-i-t-l-e
title finally so i'll just write title t-i-t-l-e
6:37:53
ahí vamos ahora creamos este componente justo aquí así que ahora vamos a
there we go now we create this component right here so now let's
6:37:56
simplemente reutilizar eso en lugar de estos botones voy a usar los míos así que lo que haré es que voy a eliminar eso sabes qué um supongo
just reuse that instead of these buttons i'm going to use my own so what i will do is that i'm going to remove that you know what um i guess
6:38:05
que voy a dejar ese primero voy a simplemente dejarlos y
i'm going to leave that first one i'm going to just leave them and
6:38:08
ahora déjame conseguir mis propios botones así que botones ahí
now let me just get my own buttons so buttons there
6:38:12
tú vas y ahora solo proporcionaré un controlador de clic
you go and now i'll just provide on click handler
6:38:15
que estamos tomando y luego solo vamos a pasar o
which we are taking and then we are going to be just passing or
6:38:18
manejar uh evento de clic justo aquí y también voy a proporcionar un valor de nike está bien uh supongo que tendré que cerrar eso de lo contrario realmente nos da
handle uh click event right here and i'm going to also provide a value of nike okay uh i guess i'm going to have to close that otherwise it really gives us
6:38:28
¿Hay botones o botón? Está bien botones.
Is there buttons or button? Okay buttons.
6:38:32
De todos modos, voy a cerrarlo manualmente así.
Anyways, I am going to just close it manually like so.
6:38:36
Pero ¿por qué nos está dando este error desagradable una vez que tenemos nuestro mouse ordenado identifica inesperado? Voy a cerrar eso.
But why it's giving us this nasty error once we have our mouse ordered identify unexpected. I'm going to close that.
6:38:45
y sí, eso está bien, pero ¿por qué nos está dando un error cada vez que quiero pasar algún tipo de valor
and yep that's cool but why it's giving us an error anytime i want to pass some sort of a value
6:38:50
a ello así que voy a pasar algún tipo de valor como nike
to it so i'm going to pass some sort of a value like nike
6:38:53
ahora no nos está dando ningún error y también voy a pasar el título
now it's not giving us any error and i'm going to also pass the title
6:38:57
de nike también está bien así que eso está bien así que voy
of nike as well okay so that's cool so i'm going
6:39:00
a simplemente duplicar allí para agregar danza puma y vans y voy a simplemente eliminar este título voy a seleccionar eso
to just duplicate there for added dance puma and vans and i'm going to just remove this title i'm going to select that
6:39:06
presiona ctrl d y agrega una d
hit ctrl d and add a d
6:39:09
i d así que ahí vamos y voy a
i d as there we go and i'm going to
6:39:12
simplemente seleccionar nike presiona ctrl d establece eso en puma
just select nike hit ctrl d set that to puma
6:39:16
y luego tenemos nike una más
and then we have nike one more
6:39:19
la próxima vez voy a cambiar eso a vans de todos modos está bien
time i'm going to change that to vans anyways that's cool
6:39:22
y para este botón no podemos hacer nada con él
and for this button we cannot do anything with it you
6:39:25
sabes que también voy a duplicar, déjame quitar este de aquí y voy a duplicar este, así que en lugar de realmente voy a quitar este valor de aquí y solo voy a presionar
know what i'm going to also duplicate let me just remove this one from here and i'm going to duplicate this one so instead of really i'm going to just remove this value right here and i'm going to just press
6:39:36
valor vacío como cadena vacía y también voy a pasar todos mis productos como una etiqueta.
empty value like empty string and I'm going to also pass my all products as a label.
6:39:41
Así que ahora voy a guardar mi archivo y ahora déjame actualizar eso. No estamos recibiendo ningún tipo de error.
So now I'm going to save my file and now let me just refresh that. We are not getting any kind of error.
6:39:45
Ahora voy a hacer clic en Nike y luego voy a hacer clic en productos y ahora está funcionando.
Now I'm going to click on Nike and then I'm going to click on products and now it's working.
6:39:51
Está bien, así que ahora hemos terminado con éxito con todo nuestro proyecto, pero solo tenemos que proporcionar un poco de estilo para esta tipografía y cosas así.
All right so now we are successfully done with all of our project but we just have to provide a little bit of styling for this typography and stuff.
6:39:58
De todos modos, así que voy a hacer clic en todos los
Anyway so I'm going to click on all of
6:40:00
productos, luego zapatillas, planos, sandalias, tacones, clic
product then sneakers flats sandals heels click
6:40:03
en todos los productos, luego tenemos cero, 50 y 100
on all of the product then we have zero 50 and 100
6:40:06
y más de 100 y luego tenemos todos los colores
and over 100 and then we have all of the colors then
6:40:10
tenemos color negro, color azul, color rojo, color verde y blanco
we have black color blue color red color green color and white um
6:40:14
color negro, color azul, color rojo, color verde
black color blue color red color green color
6:40:17
y color blanco, está bien, todo está funcionando, voy a hacer clic
and white color okay everything is working i'm going to click
6:40:20
en todos los productos, luego tenemos un nike, un puma, vans, voy a hacer clic en todos los productos una vez más y supongamos que quieres obtener este como Nike Zoom Freak.
on all of the products then we have a nike at a dance puma vans i'm going to click on all of the products one more time and let's suppose if you want to get this one like Nike Zoom Freak.
6:40:31
Así que solo voy a pasar su nombre como Nike. Nos dará todos los productos de Nike y luego tenemos Zoom. Está bien.
So I'm going to just pass the name of him like Nike. It will give us all of the product of the Nike and then we have Zoom. Alrighty.
6:40:38
Así que este no está funcionando y no sé por qué.
So this one is not working and I don't know why.
6:40:43
No me vas a creer.
You won't believe me.
6:40:47
Este error me tomó mucho tiempo averiguar dónde en el mundo estoy haciendo algo mal.
This error took me a lot of time to figure out like where in the world is I'm doing something wrong.
6:40:54
Aquí puedes ver que solo escribí esta expresión
Here you can see I just write this expression
6:40:58
justo aquí voy a cortar eso de aquí y solo lo voy a colocar aquí
right here i'm going to cut that from here and i'm going to just place it right here
6:41:01
así que voy a guardar mi archivo finalmente y ahora
so i'm going to save my file finally and now
6:41:04
déjame buscar algo como nike, uh, zoom freak
let me just search for something like nike uh zoom freak
6:41:07
si solo escribo nike aquí, nos dará todos los productos de nike
if i just write nike right here so it will give us all of the nike products
6:41:11
voy a buscar un zoom, ahora solo nos dará
i am going to just search for a zoom it will now just give us
6:41:14
nike zoom freak y supongamos que quieres conseguir este, déjame copiar todo el nombre y lo voy a colocar aquí para que ahora nos dé
nike zoom freak and let's suppose you want to get this one like let me just copy all of the name and i'm going to just place it right here so it will now give us
6:41:22
este artículo aquí, así que este error me tomó un
this item right here so this bug took me a
6:41:25
montón de tiempo, ya sabes, así que finalmente
lot of time you know what so finally
6:41:28
lo que voy a hacer es que voy a entrar
what i will do is that i am going to go in
6:41:31
aquí y voy a seleccionar todas esas cosas y
here and i am going to select all of that stuff and
6:41:34
voy a proporcionar familia encontrada de conjunto de sentido de comercio y
i am going to provide found family of sense set of trade and
6:41:38
déjame refrescar eso y por qué no está tomando todo eso, así que
let me just refresh that and why it's not taking all of that so
6:41:43
tenemos acceso a este index.css aquí, apuesto a que no lo usamos aquí, así que por eso
we have access to this index.css right here i bet we didn't use that in here so that's why we
6:41:49
no estamos obteniendo todas esas cosas, déjame usar import
are not getting all of that stuff let me just use import
6:41:53
y luego tenemos que escribir index.css, así que
and then we have to write index.css so
6:41:57
ahora si guardamos nuestro archivo y aquí puedes ver que todo está
now if we save our file and here you can see everything is
6:42:00
funcionando como esperamos que funcione y todo está
working the way we expect them to work and everything is
6:42:03
bien, así que finalmente déjame probar
looking a-okay so finally let me just test
6:42:06
esto por última vez y luego vamos a estar listos
this for a final time and then we are going to be done
6:42:09
para este proyecto y si estás viendo este video en mi
for this project and if you are watching this video in my
6:42:13
curso de react, así que luego vamos a estar listos con todo el curso de react, de todos modos voy a hacer clic en todos los productos, eso
react course so then we are going to be done with all react course anyways i'm going to just click on all of the products it
6:42:19
nos dará todos los productos si haces clic en zapatillas y luego
will give us all of the products if you click on sneakers and then
6:42:22
tenemos planos, sandalias, tacones, voy a hacer clic en un
we have flats sandals heels i'm going to click on a
6:42:25
0, 50, 100 y más de 100, voy a
0 50 100 and over 100 i'm going
6:42:28
hacer clic en este, pero acabo de descubrir un error más y
to click on this one but i just figured out one more bug and
6:42:32
eso está ocurriendo aquí, así que tenemos que
that is occurring right here so we
6:42:35
ir a una marca lateral, luego tenemos que ir a la
have to go into a side mark then we have to go to the
6:42:38
categoría, así que aquí lo que estamos haciendo es que simplemente estamos proporcionando
category so here what we are doing is that we are just providing
6:42:41
una prueba aquí y prueba para todos ellos, eso es genial, voy a entrar en el precio y aquí simplemente estamos especificando
a test right here and test for all of them that's cool i'm going to go into the price and here we are just specifying
6:42:47
prueba 2 aquí, eso también es genial, pero ahora
test 2 right here that's also cool but now
6:42:50
voy a entrar en los colores y estamos especificando prueba
i'm going to go into the colors and we are specifying test
6:42:53
así que voy a seleccionar eso
2 right here so i'm going to just select that hit
6:42:56
ctrl d uh y sabes qué, solo voy a especificar
ctrl d uh and you know what i'm going to just specify
6:43:00
prueba 3 aquí, voy a copiar allí, ahora estoy
test 3 right here i'm going to copy there now i'm
6:43:03
voy a seleccionar mi prueba y todas ellas y aquí
going to just select my test one and all of them and here
6:43:06
voy a especificar prueba 3 si guardas un archivo
i'm going to just specify test 3 if you save a file
6:43:09
y ahora déjame verificar que voy a hacer clic en este, hacer clic en este producto y ahora eso es totalmente
and now let me just uh check that i'm going to click on this one click on this product and now that's totally
6:43:16
funcionando, así que si quiero obtener azul, voy a obtener azul
working so if i want to just get like blue i'm gonna get blue
6:43:19
luego rojo, luego verde, luego blanco, está bien, así que eso también es
then red then green then white okay so that's also
6:43:22
funcionando, supongamos que quiero obtener este producto, así que voy a
working let's suppose i want to just get this product so i'm
6:43:25
copiar allí y voy a colocar esto aquí, así que aquí puedes
going to just copy there and i'm going to just place it right here so here you can
6:43:28
verlo cuando usa solo este producto aquí y voy a hacer clic
see it when it uses just this one product right here and i'm going to just click
6:43:31
en las zapatillas y cosas así, y voy a hacer clic en
on the sneakers and stuff and i'm going to just click on
6:43:34
una nike, luego hemos agregado este puma vans
a nike then we have added this poma vans
6:43:38
y todos estos productos de nuevo, así que diciendo y mira en youtube
and all of these products again so saying and look at youtube
6:43:41
canal, así que en este video vamos a aprender
channel so in this video we are going to be learning
6:43:44
sobre typescript desde cero, así que qué en
about typescript from scratch so what in
6:43:47
el mundo es typescript y por qué deberías preocuparte por ellos, así que
the world is typescript and why you should care about them so
6:43:50
para dar una respuesta simple a eso, puedes pensar en typescript
to give a simple answer to that you can think about typescript
6:43:54
es como un javascript con superpoderes, así que
is like a javascript with super power so
6:43:57
¿qué significa eso? Así que typescript es como una versión más poderosa
what does that mean so typescript is like more powerful
6:44:00
versión de javascript te permite hacer cada uno
version of javascript it lets you do every single
6:44:03
de las cosas que javascript ya hace, pero también añade algunas características adicionales que vamos a aprender a lo largo de las escuelas para facilitarte la vida al escribir programas más grandes y complejos.
thing that javascript already does but it also adds some extra features which we are going to be learning throughout the the schools to make your life easier when writing a larger and more complex programs.
6:44:15
¿Entonces significa que solo podemos usar TypeScript para programas más grandes y complejos? No, por supuesto que no.
So does it mean that we can only use TypeScript for a larger and complex programs? No, of course not.
6:44:22
Y para cualquier escala de proyecto, puedes usarlo para más pequeños o para más grandes y todo eso.
And for any scale of project, you can use it for smaller or for bigger and all of that.
6:44:27
Así que eso fue solo una introducción básica a lo que es un TypeScript. Así que ahora déjame ir a la página oficial de TypeScript y cómo se llaman a sí mismos.
So that was just a basic intro to what a TypeScript is. So now let me just go ahead and go to the official page of TypeScript and how they call themselves.
6:44:34
Así que si quieres venir al mismo enlace, puedes escribir esto en tu navegador, que es typescriptlang.org y solo presionar enter y te llevará a este sitio web justo aquí.
So if you want to come to the same link, you can just type this in your browser, which is typescriptlang.org and just hit enter and it's going to bring you to this website right here.
6:44:44
Así que aquí puedes ver en la página oficial de TypeScript, se llaman a sí mismos TypeScript es un JavaScript con una sintaxis para tipos.
So here you can see on the official page of TypeScript, they call themselves as TypeScript is a JavaScript with a syntax for types.
6:44:52
Como TypeScript se trata de tipos justo aquí.
Like TypeScript is all about types right here.
6:44:56
Tipo, aquí puedes ver que tenemos tipo y también
Type, here you can see we have type and also
6:45:00
para el javascript, así que puedes pensar en typescript como eso, así que qué tipo de características proporciona puedes aprender más sobre eso si quieres, pero no tienes que hacerlo porque vas a aprender cada cosa
for the javascript so you can think about typescript as like that so which kind of feature it provides you can learn more about that if you wanted to but you don't have to because you're going to be learning every single thing
6:45:10
en este curso justo aquí, typescript agrega sintaxis adicional a un javascript para soportar una integración más estrecha con tu editor, detectar errores temprano en tu editor y también un resultado en el que puedes confiar.
in this course right here typescript add additional syntax to a javascript to support a tighter integration with your editor catch errors early in your editor and also a result you can trust
6:45:21
¿Qué significa eso? El código de typescript se convierte en javascript que
what does that mean typescript code converts to javascript which
6:45:25
se ejecuta en todas partes donde se ejecuta javascript, como para el navegador.
runs everywhere javascript runs like for the browser
6:45:28
y también para node y no tienes que preocuparte por dino.
and also for node and you don't have to worry about dino
6:45:31
uh y en tus aplicaciones justo aquí y seguridad.
uh and in your apps right here and safety
6:45:34
a gran escala, typescript entiende javascript y usa tipo
at scale typescript understand javascript and use type
6:45:37
inferencias o inferencia, algo en lo que vamos a
inferences or inference something which we are going to
6:45:40
profundizar en una gran profundidad en este curso para darte
be diving into in a really great depth in this course to give
6:45:44
herramientas geniales sin código adicional justo aquí, así que puedes
you great tooling without additional code right here so you
6:45:47
explorar más sobre typescript justo aquí, así que aquí puedes
can go ahead and explore more more about typescript right here so here you can
6:45:50
ver que no se puede encontrar el nombre de orr, quiero decir, como que ellos
see cannot uh find the name of orr i mean like they
6:45:53
olvidaron algo justo aquí en el código y ahora typescript les está dando
forgot something right here in the code and now the typescript is giving them
6:45:56
quejas justo aquí, puedes aprender más sobre eso y esto
complaints right here you can learn more about that and this
6:45:59
es la página oficial de typescript justo aquí y
is the official page of typescript right here and
6:46:02
vamos a aprender cada cosa que hay que aprender sobre
we are going to be learning every single thing there is to learn about
6:46:05
typescript en este curso, así que sí, eso fue solo un poco sobre el
typescript in this course so yeah that was just a bit about the
6:46:08
introducción básica de lo que es un typescript y ahora vamos a la instalación, así que ahora vamos a instalar typescript en nuestra máquina, así que voy a hacer clic en probar
basic introduction of what a typescript is and now let's get into the installation so now let's install typescript in our machine so i'm going to just click on try
6:46:17
typescript, ahora voy a hacer clic en este botón justo aquí, puedes usar
typescript now i'm going to click on this button right here you can use
6:46:21
esto en el navegador o puedes decir un playground, así que voy a
it in the browser or you can say a playground so i'm
6:46:24
voy a hacer clic en tu computadora, voy a hacer clic en eso y
going to just click on on your computer i'm going to click on that and
6:46:27
nos llevará a esta documentación aquí, así que si quieres
it's going to bring us to this documentation right here so if you want to
6:46:30
instalar esto aquí puedes ver que este es el comando como npm install
install this here you can see this is the command like npm install
6:46:33
typescript dash sale puedes guardarlo en tus dependencias
typescript dash sale you can save that to your dependencies
6:46:36
pero no vamos a usar eso, vamos a usar algo llamado esto
but we are not going to be using that we are going to be using something called this
6:46:40
comando que es npm install dash g typescript
command which is npm install dash g typescript
6:46:44
déjame hacer eso un poco más grande para que puedan ver todo un poco mejor, vamos
let me just make that a bit bigger so you guys can see everything a bit better we
6:46:47
a usar este comando aquí, ya lo instalé allí pero
are going to be using this command right here i already installed there but
6:46:50
ahora déjame mostrarte cómo vas a instalar allí, así que voy a abrir
now let me just show you how you are going to be installing there so i'm going to just open
6:46:53
mi terminal aquí, puedes abrir tu terminal en cualquier lugar que
my terminal right here you can open your terminal anywhere you
6:46:56
quieras y lo que quiero hacer es que voy a
want and what i want to do is that i'm going to just
6:47:00
verificar si ya tengo typescript o no, así que voy a escribir
check if i already have typescript or not so i'm going to just write
6:47:03
ts dash v aquí, oh no ts dot v, sino tsc dash v aquí y nos dará el
ts dash v right here oh not ts dot v but tsc dash v right here and it's going to give us the
6:47:10
número de versión del compilador de typescript que estoy usando aquí
typescript compiler version which i'm using right here
6:47:13
para este curso que es 5.2.2 aquí, así que
for this course which is 5.2.2 right here so
6:47:16
si ya lo instalaste, genial, si no lo instalaste
if you already installed that cool if you did not install that
6:47:20
puedes simplemente copiar este comando aquí que es npm install
you can just go ahead and copy this command right here which is npm install
6:47:23
dash g y typescript y por cierto olvidé
dash g and typescript and by the way i forgot
6:47:26
mostrarte algo, tienes que tener instalado node.js
to show you something you have to have the node.js installed
6:47:29
ya en tu máquina, así que voy a escribir como node.js.org, supongo que voy a ir a node.js aquí y solo tienes que
already in your machine so i'm going to just write like node.js.org i guess i'm going to go ahead and go to the node.js right here and you just have to
6:47:38
instalar cada uno de ellos, así que puedes instalar esta versión o también puedes instalar
install each one of them like so you can install this version or you can also install
6:47:41
esta versión aquí, así que una vez que lo hagas, solo haz clic en siguiente, siguiente
this version right here so once you do just click on the next next
6:47:44
siguiente y se instalará en tu máquina y luego solo tienes que
next and it's going to install in your machine and then you just have
6:47:47
escribir node-v, así que también te dará la versión
to write node-v so it's going to also give you the version
6:47:50
aquí, así que actualmente estoy usando 21.1 o
right here so currently i'm using 21.1 or
6:47:53
algo así y esta es mi garantía para cuando estés viendo este video, esta versión será totalmente diferente a la mía, vas a estar usando no sé
something like that and this is my guarantee by the time you're watching this video this version will be totally different than mine you're going to be using i don't know
6:48:01
como 22 o tal vez 25 o algo así
like 22 or maybe 25 or something like that
6:48:04
pero node.js no tiene que hacer nada
but node.js does not have to do anything
6:48:08
con typescript aquí, quiero decir que hay algunas cosas
with typescript right here i mean like there are a few things
6:48:11
que también vas a discutir a lo largo del curso, pero la versión
which you are going to be also discussing throughout the course but the versioning
6:48:14
no importa, puedes instalar como siempre que
doesn't matter you can install like as long as
6:48:17
la versión sea mayor que 8, estás totalmente bien, pero
the version is like greater than 8 you are totally good to go but
6:48:21
si estás usando alguna versión menor que 8, entonces
if you are using some version less than 8 then you
6:48:24
no estás en un buen lugar, amigo, así que ahora dejemos
are not in a great spot my friend so now let
6:48:27
que cierre eso, oh, olvidé mostrarte, lo acabo de cerrar, déjame
me just close that oh i forgot to show you i just closed it let me just
6:48:30
hacer clic derecho en eso y abrir mi terminal aquí y dejar
right click on that and open my terminal right here and let
6:48:33
que reinstale ese typescript aquí, así que ahora dejemos
me just reinstall that typescript right here so now let
6:48:36
que haga eso un poco más grande e instale ahí, aquí voy a copiar
me just make that a bit bigger and install there right here i'm going to just copy
6:48:39
este comando, déjame copiar eso, estoy
this command let me just copy that i'm
6:48:42
a punto de hacer clic derecho en eso y aquí puedes ver que tengo npm install g
going to right click on that and here you can see i have npm install g
6:48:46
typescript, voy a presionar enter aquí y aquí puedes ver que ya lo instalé, así que solo nos dará este mensaje aquí, en tu caso será algo diferente, pero de todos modos, mientras no veas errores
typescript i'm going to hit enter right here and here you can see i already installed there so it's going to give us only this message right here in your case it's going to be something different but anyways as long as you don't see any errors
6:48:57
estás totalmente bien, así que sí, eso está ahí, ahora lo siguiente
you are totally good to go so yeah that's there now the next
6:49:00
que quiero mostrarte es que también tienes que instalar algo
thing which i want to show you is that you also have to install something
6:49:04
llamado um ts node también, así que voy a
called um ts node as well so i'm going to
6:49:07
simplemente escribir como npm y i y luego solo tienes que
just write like npm and i and then you just have to
6:49:10
escribir dash g ts dash node, tienes
write dash g ts dash node you have
6:49:13
que hacer eso aquí, está bien, así que quiero que solo escribas este
to do that right here okay so i want you to just type this
6:49:16
comando en tu máquina e instales eso, quiero que instales eso
command in your machine and install that i want you to install that
6:49:19
porque a lo largo del curso, quiero decir, solo para el comienzo del curso
because throughout the course i mean like just for the beginning of the course
6:49:22
no vamos a estar usando todo eso, uh npm
we are not going to be using like all of that uh npm
6:49:25
cosas como cómo hacer una configuración de typescript y todo eso
stuff like how to make a typescript configuration and all of that
6:49:28
vamos a usar una extensión de vs code y confianza
we are going to be using a vs code extension and trust
6:49:31
para typescript te vas a enamorar de eso, lo prometo, pero
me that's like supremely amazing
6:49:34
lo que quiero que hagas es que también instales este como
for typescript you're gonna fall in love with that i promise but
6:49:38
lo que quiero que hagas es que quiero que también instales este como
what i want you to do is that i want you to also install this one as
6:49:41
bueno, así que quiero que simplemente presiones enter aquí, ya lo instalé allí y se va a reinstalar allí una vez más para mí, está bien, así que sí, aquí puedes ver que también está instalado y ahí vamos.
well so i want you to just hit enter right here i already installed there and it's going to reinstall there once again for me okay so yeah here you can you can see that's also installed and there we go.
6:49:51
Lo siguiente que quiero que hagas es que quiero que hagas una carpeta en cualquier lugar que te guste.
The next thing which I want you to do is that I want you to make a folder anywhere you like.
6:49:55
En mi caso, voy a crear mi carpeta dentro de mi escritorio y
In my case, I'm gonna create my folder inside my desktop and
6:49:59
puedes darle cualquier nombre que desees, como el nombre no importa, yo solo le voy a dar el nombre de
you can give any name you want like the name doesn't matter i'm going to just give a name of
6:50:02
como ts playground o algo así, ven
like ts playground or something like that come
6:50:05
al área de juegos justo aquí y puedes
on play ground right here and you can
6:50:08
darle cualquier nombre que desees, voy a hacer clic derecho en eso y luego voy a
give any name you want i'm going to right click on that and then i'm going to
6:50:11
abrir esta carpeta en mi vs code justo aquí, está bien, así es como se ve mi vs code y es probable que tu vs code no se vea exactamente
open this folder in my vs code right here okay so this is how my vs code looks like and chances are your vs code will not look exactly
6:50:19
igual que el mío, pero si te estás preguntando como huzan
the same like mine but if you're wondering like huzan
6:50:22
realmente me gusta tu vs code y tu extensión de vs code
i really like your vs code and your vs code extension
6:50:25
y todo ese tipo de cosas, puedes ir y ver mi revisión de personalización de vs code y confía en mí, te vas a enamorar de mi personalización y del tema que estoy usando aquí
and all of that kind of stuff you can go ahead and watch my vs code customization review and trust me you're going to fall in love with my customization and the theme i'm using right here
6:50:35
de todos modos, eso es fuera del curso, ahora voy a continuar y voy a
anyway so that's out of the course now i'm going to go ahead and go to
6:50:38
la extensión y simplemente hagamos clic en eso, en mi
the extension and let's just click on that in my
6:50:41
caso estoy usando este atajo justo aquí, pero en tu caso va a
case i'm using uh this shortcut right here but in your case it's
6:50:44
verse algo así, simplemente voy a continuar e ir a code.vscode.com
going to look something like this i'm going to just go ahead and go to like code.vscode.com
6:50:49
o algo así, déjame continuar, oh eso es
or something like that let me just go ahead oh that's
6:50:53
no es eso, no sé vscode o algo así
not the thing uh i don't know vscode or something like that
6:50:56
y déjame abrir eso y code.visualstudio.com
and let me just open that and code.visualstodio.com
6:51:00
mi error y vamos a estar usando este vscode a lo largo del curso y eres más que bienvenido a usar cualquier tipo de editor que quieras, quiero decir, sí, lo que te guste y en tu caso, si quieres ir al área de extensiones
my bad and we are going to be using this vscode throughout the course and you are more than welcome to use whichever kind of editor you i mean like yeah it is you like and in your case if you want to go to the extension area
6:51:11
tendrás que hacer clic en este botón justo aquí y va a
you're going to have to click on this button right here and it's going
6:51:14
tienes que hacer clic en este botón aquí y te va
to bring you this similar interface right here so the first thing which i want you to
6:51:17
a llevar a esta interfaz similar aquí, así que lo primero que quiero que
install is this extension right here which is javascript and
6:51:20
instales es esta extensión aquí que es javascript y
also typescript nightly okay so just install
6:51:23
también typescript nightly, así que solo instala
that and it is created by microsoft so yeah we are totally
6:51:26
eso y está creado por microsoft, así que sí, estamos totalmente
in the great hands and also install this coderunner
6:51:30
en buenas manos y también instala este coderunner
right here because throughout the course i mean like just for the beginning
6:51:33
aquí porque a lo largo del curso, quiero decir, solo para el principio
of this course we are going to be using this coderunner a lot and trust me you're going to fall in love with this coderunner right
6:51:40
de este curso vamos a estar usando mucho este coderunner y confía en mí, te vas a enamorar de este coderunner aquí
here just click on that install button and it's going to install it in
6:51:43
solo haz clic en ese botón de instalar y se instalará en
your machine so now i'm going to go ahead and create a file right here
6:51:46
tu máquina, así que ahora voy a proceder a crear un archivo aquí
you can give any name you want i'm going to just give a name of like index.ts
6:51:50
puedes darle cualquier nombre que quieras, yo solo le voy a dar un nombre como index.ts
right here and we are using a typescript so for
6:51:53
aquí y estamos usando typescript, así que para
this case we have to specify the ts extension right here if
6:51:56
este caso tenemos que especificar la extensión ts aquí, si
you are using a javascript so we just have for a js right here we are now currently working with this ts i mean like we are currently working with typescript so we have to specify ts at the end as an extension so now i'm going to just hit enter right here
6:52:09
y no tienes que hacer nada más ahora déjame solo crear
and you don't have to do nothing else now let me just create
6:52:12
una carpeta o un acceso directo, como quieras llamarlo
a binder or a shortcut whatever you want to call that
6:52:15
así que ahora voy a escribir un poco de código TypeScript que tú
so now i'm going to just write a bit of typescript code which you
6:52:18
no tienes que preocuparte por eso ahora, así que voy a escribir como, no sé, tipo
don't have to worry about right now so i'm going to just write like i don't know type
6:52:21
de uh persona o algo así y esta persona tendría
of uh person or something like that and this person would have
6:52:24
como, no sé, nombre o cadena, supongo que eso estaría bien, no tenemos
like i don't know name or string i guess that would be fine we don't
6:52:28
que preocuparnos por nada más, también voy a proporcionar a esta persona aquí, no tienes que hacer nada más, solo tienes que escribir este código aquí, solo este código, nada más
have to worry about anything else i'm going to also provide this person right here you don't have to do anything else you just have to write this code right here just this code nothing else
6:52:37
y ahora, si quieres ejecutar este código usando un compilador TypeScript
and now if you want to run this code by using a typescript compiler
6:52:40
este es un proceso enorme, así que
this is a huge process so
6:52:44
no vamos a entrar en todo ese proceso, no ahora
we are not going to be going into all of that process not right now
6:52:47
pero vamos a entrar en todas esas cosas un poco más tarde
but we are going to be going into all of that stuff a bit later
6:52:50
con un gran, gran detalle, pero no
in a really great great detail but not
6:52:53
ahora mismo, pero supongamos que quiero ejecutar este archivo, ¿cómo puedo hacerlo?
right now but let's suppose if i want to run this file how can i go about doing
6:52:57
eso, y sabes qué, déjame registrar en la consola algo como
that and you know what let me just log to the console something like
6:53:00
voy a registrar en la consola como persona punto nombre aquí, y ahora, si guardo este archivo, y ahora si quiero ejecutar este código, ¿cómo demonios debería hacerlo?
i'm gonna just log to the console like person dot name right here and And now if I save this file, and now if I want to run this code, how in the world should I go about doing that?
6:53:10
Así es como vas a hacerlo. Bien, aquí puedes ver que ahora estamos obteniendo a John. Así que ahora podrías estar preguntando, como, Hosean, ¿cómo hiciste eso?
This is how you're going to be doing that. Okay, so here you can see we're now getting John. So now you might be asking like, Hosean, how did you do that?
6:53:16
Dímelo. Te lo estoy diciendo, pero tienes que darme unos segundos.
Tell me. I'm telling you, but you have to give me a few seconds.
6:53:21
Ya instalaste esta extensión aquí, que tenemos esta extensión de ejecutor de código aquí. Ya instalaste eso.
You already installed this extension right here, which we have this code runner extension right here. You already installed that.
6:53:27
Lo siguiente que quiero que hagas es que quiero que abras tu paleta de comandos.
The next thing which I want you to do is that I want you to open your command palette.
6:53:31
No sé cómo vas a abrir la paleta de comandos en el sistema operativo Linux, y tampoco sé cómo vas a abrir tu paleta de comandos en, ¿cómo lo llamamos?, en el sistema operativo Mac OS.
I don't know how you're going to be opening the command pillet in the Linux operating system, and I also don't know how you're going to be opening your command pillet in the, what do we call it, in the Mac OS operating system.
6:53:43
Pero sé cómo vas a abrir tu paleta de comandos en el sistema operativo Windows aquí, pero tienes que buscar allí para tu propio sistema operativo.
But I do know how you're going to be opening your command pillet in Windows operating system right here, but you got to search there for your own operating system.
6:53:52
Para los usuarios de Windows, solo tienes que presionar F1, y ahí vamos.
For Windows users, you just have to hit F1, and there we go.
6:53:57
bien, y aquí quiero que busques, eh, ¿cómo lo llamamos?
okay and here i want you to just search for uh what do we call
6:54:00
los atajos de teclado aquí, así que
it the keyboard shortcuts right here so
6:54:03
aquí puedes ver que tenemos como abrir atajos de teclado, voy a hacer clic
here you can see we have like open keyboard shortcuts i'm going to click
6:54:06
en eso y aquí solo tienes que buscar el código
on that and here you just have to search for the code
6:54:09
ejecutor aquí y aquí quiero que selecciones este aquí, por defecto estará configurado en algo más, quiero que hagas doble clic en eso, te dará este campo de entrada aquí y solo proporciona shift
runner right here and here i want you to just select this one right here by default it's going to be set to something else i want you to just double click on that it's going to give this input field right here and just provide shift
6:54:21
y enter, y ahí vamos, quiero que presiones enter una
and enter and there we go i want you to just hit enter one
6:54:24
vez más, y así es como vas a crear un atajo
more time and this is how you are going to be creating a shortcut
6:54:27
para, eh, este ejecutor de código aquí, así que
for uh this code runner right here okay so
6:54:30
sí, eso es increíble, solo voy a mantener presionado mi shift y
yeah that's amazing i'm going to just hold my shift and
6:54:33
presionar enter y boom, ahí vamos, así que aquí puedes ver
hit enter and boom there we go so here you can see
6:54:37
ahora estamos obteniendo el resultado de john justo aquí, ahora voy a escribir
we are now getting the result of john right here now i'm going to right
6:54:40
haz clic en eso, luego voy a continuar e ir a mi posición de panel justo aquí, luego solo voy a configurarlo a la derecha si te gusta este diseño
click on that then i'm going to go ahead and go to my panel position right here then i'm going to just set that to right if you like this layout
6:54:47
siéntete libre de hacerlo así si no te gusta este diseño
feel free to make it like this if you don't like this layout so
6:54:50
puedes hacer clic derecho en eso, vamos, puedes hacer clic derecho en eso, ir al panel y puedes moverlo a la izquierda o también hacia abajo, está bien, así que sí, a lo largo del curso vamos a estar escribiendo nuestro código así.
you can just right click on that come on you can just right click on that go to the panel and you can make it to the left or also to the bottom itself okay so yeah throughout the course we are going to be writing our code like this.
6:55:01
O tal vez en alguna situación, también vamos a sumergirnos en la terminal.
Or maybe in some situation, we are going to be also diving into the terminal.
6:55:04
Y esto es algo de lo que hablaré en gran detalle aquí mismo. Ahora no tenemos que hacer nada más.
And this is something which I will discuss in a really great detail right here. Now we don't have to do nothing else.
6:55:11
Y ahí vamos. Voy a eliminar este código aquí y guardar mi archivo. Y aquí puedes ver que ni siquiera tenemos un archivo compilado aquí.
And there we go. I'm going to delete this code right here and save my file. And here you can see we don't even have any compiled file right here.
6:55:18
Así que sí, eso también es increíble. Así que ahora vamos a entrar en el primer tema técnico de este curso, que serán las anotaciones en TypeScript, así que las anotaciones se utilizan para especificar el tipo de datos
So yeah, that's also amazing. So now let's get into the first technical topic of this course, which will be annotations in typescript so annotation are used to specify the data type
6:55:28
de un parámetro de variable, valores de retorno de función y otros tipos
of a variable parameter function return values and other types
6:55:31
de valores, así que vamos a aprender sobre cómo
of values so we are going to be learning about how to
6:55:34
trabajar con anotaciones para las funciones y también vamos a
work with annotation for the functions and we're going to be also
6:55:37
aprenderlo para las cadenas, para booleanos y todo ese tipo de
learning it for the strings for booleans and all of that kind of
6:55:40
cosas, está bien, que vendrán en unos segundos. Ahora que sabemos qué son las anotaciones, ¿cuál es el propósito de las anotaciones? Así que las anotaciones ayudan
stuff okay which are coming in a few seconds now that we know what annotations is so what's the purpose of annotation so annotations help
6:55:48
a los desarrolladores a detectar errores temprano en el desarrollo al permitirles especificar qué tipo de valores se pueden asignar a una variable dada o pasar como argumento a una función.
developers catch errors early in the development by allowing them to specify what type of values can be assigned to a given variable or pass as an argument to a function.
6:55:57
Está bien, así que como dije, vamos a aprender sobre anotaciones para diferentes tipos de cosas que vendrán en unos segundos.
Okay so as I said there we are going to be learning about annotation for different kind of things which are coming up in a few seconds.
6:56:03
Así que ahora déjame mostrarte el primer ejemplo de uso de anotaciones. Así que aquí puedes ver que tenemos anotaciones para cadenas. ¿Cómo se verá la sintaxis?
So now let me just show you the first example of using annotation. So here you can see we have annotation for string. So how the syntax will look like?
6:56:10
Primero que nada, vamos a crear algún tipo de variable aquí.
First of all we are going to be creating some sort of a variable right here.
6:56:14
Luego vamos a proporcionar este separador aquí que puedes ver y luego tenemos que proporcionar algún tipo de tipo, así que esto se conoce como
Then we are going to be providing this separator right here which you can see and then we have to provide some sort of a type so this is known as
6:56:21
anotación de variable o puedes decir como anotación
annotating or variable or you can say like annotation
6:56:24
lo que quieras llamar a eso y finalmente vamos a usar
whatever you want to call that and finally we are going to be using
6:56:27
el signo igual y luego algún tipo de valor que vamos
the equal to sign and then some sort of a value which we
6:56:30
a almacenar basado en este tipo aquí, así que sí
are going to be storing best on this type right here so yeah
6:56:33
sé que suena un poco confuso, pero aquí está el ejemplo real
i know that sounds a bit confusing but here is the actual example
6:56:36
de eso, así que cómo vamos a usar eso. Primero que nada, vamos a crear una variable aquí, no importa si quieres crear tu variable usando el
of that so how we are going to be using that first of all we are going to be creating a variable right here it doesn't matter if you want to create your variable by using the
6:56:44
palabra clave const o var, no importa en absoluto, depende totalmente de ti, pero si quieres anotar, primero que nada tienes que
keyword the cons or the var it doesn't even matter it's totally
6:56:47
especificar el separador aquí, luego tienes que proporcionar algún
up to you but if you want to annotate there first of all you have
6:56:50
tipo, así que como qué tipo de datos es esta variable
to specify the separate right here then you have to provide some
6:56:53
que va a contener, así que en este caso estamos proporcionando como el
sort of a type so like which type of data this variable is
6:56:56
valor de cadena, así que aquí puedes ver que anotamos nuestra variable por
going to be holding so in this case we are providing like the
6:57:00
cadena aquí, así que sí, así es como se verá la sintaxis aquí y puedes proporcionar algún otro valor simplemente.
string value so here you can see so we annotate our variable by
6:57:03
cadena justo aquí así que sí, así es como se verá la sintaxis justo aquí y puedes proporcionar algún otro valor simplemente
string right here so yeah this is how the syntax will look like right here and you can provide some other value by just
6:57:09
usando el signo igual y si lo registras en la consola, va
using the equal to sign and if you log there to the console it's
6:57:12
a darte como otro valor en este caso porque estamos cambiando este valor
going to give you like another value in this case because we are changing this value
6:57:15
justo aquí, pero por otro lado quiero que tengas eso en
right here but on the other hand i want you to keep that in
6:57:19
mente si anotamos allí usando una cadena pero
mind if we annotate there by using a string but
6:57:22
si proporcionamos eso como algún tipo de número, será
if we provide that like some sort of a number to it it's
6:57:25
nos lanzará un error justo aquí, así que quiero que mantengas este diagrama en
going to throw us an error right here so i want you to just keep this diagram in
6:57:29
mente, así que esto fue para una cadena, también puedes escribir anotaciones para los números y la sintaxis será totalmente la misma, así que aquí puedes ver, primero estamos declarando nuestra variable
mind so this was for a string you can also write annotation for the numbers as well and the syntax will be totally the same so here you can see first of all we are declaring our variable
6:57:38
luego estamos anotando allí usando un número y estamos proporcionando
then we are annotating there by using a number and we are providing
6:57:41
algún tipo de valor como siete y solo podemos agregar algún otro
some sort of value of like seven and we can just add some other
6:57:44
valor a eso, pero quiero que tengas en cuenta que si intentas agregar
value to it but i want you to keep in mind that if you try to add
6:57:48
algún otro tipo de valor, como en este caso estamos especificando
some other type of value like in this case we are specifying
6:57:51
la cadena 11 justo aquí, esto no funcionará
the string 11 right here this will not fly
6:57:54
te va a lanzar un error o si especificas algún
it's going to throw you an error or if you specify some
6:57:57
tipo de valor booleano como verdadero o falso o algo así, también te dará un error y también voy a
sort of a boolean value like true or false or something like that it's going to also give you an error and i'm going to also
6:58:03
mostrarte eso en unos segundos, así que eso fue para
show you that in a few seconds so that was for
6:58:06
una cadena, este fue para un número y ahora hablemos
a string this one was for a number and now let's talk
6:58:09
sobre booleanos, así que aquí puedes ver que la sintaxis será
about booleans so here you can see the syntax will be
6:58:12
totalmente la misma, como si intentas agregar algún otro valor
totally the same like if you try to add some other value
6:58:16
por ejemplo, como un número o una cadena, te va a lanzar
for instance like number or string it's going to throw you
6:58:19
un error, así que quiero que mantengas esta sintaxis en mente y ahora vamos
an error so i want you to just keep this syntax in mind and now let's
6:58:22
a entrar en la codificación, entonces sabrás de qué estoy hablando, así que primero vamos a aprender sobre la anotación para las cadenas, luego también vamos a aprenderlo para los números y también para el booleano
get into the coding then you will get to know what i'm talking about so first of all we are going to be learning about annotation for the strings then we are going to be also learning it for the numbers and also for the boolean as well
6:58:33
bien, así que ahora hablemos sobre la cadena, así que primero voy a crear
okay so now let's talk about for the string so first of all i'm going to create
6:58:36
algún tipo de variable, como no sé, mi nombre o algo así y
some sort of variable like i don't know my name or something like that and
6:58:39
ahora, si quieres anotar, entonces para eso vamos a usar esto
now if you want to annotate then so for that we are going to be using this
6:58:43
uh dos puntos aquí y luego vamos a proporcionar algún tipo de un
uh colon right here and then we are going to be providing some sort of a
6:58:46
tipo así que en este caso voy a proporcionar el tipo de cadena aquí y
type so in this case i'm going to provide the type of string right here and
6:58:49
luego tenemos que escribir el signo igual y qué tipo de
then we have to write the equal to sign and which kind of
6:58:52
valor queremos almacenar así que supongamos que quiero almacenar el valor de 12, nos va a dar un error, ¿por qué es eso si yo
value we want to store so like let's suppose if i want to store the value of like 12 it's going to give us an error why is that if i
6:58:59
sin embargo, si paso el mouse sobre él, nos va a dar este error aquí como
however my mouse over to it it's going to give us this error right here like
6:59:02
el tipo número no es asignable al tipo
type number is not assignable to the type
6:59:05
cadena aquí así que ¿por qué demonios estamos
string right here so why on earth we are
6:59:08
recibiendo este error ya sabes por qué estamos recibiendo este error aquí eso es
getting this error you already know why we are getting this error right here that's
6:59:12
porque proporcionamos esta cadena, quiero decir, como anotamos que hay una cadena
because we provide this string i mean like we annotate there is a string
6:59:15
y estamos almacenando el valor de 12 aquí si
and we are storing the value of 12 right here if we
6:59:18
cambiamos eso a algún tipo de cadena como no sé, solo voy a
change that to some sort of a string like i don't know i'm going to just
6:59:21
almacenar mi nombre como hosan webdev aquí y si solo lo registro en la consola como mi nombre, déjame volver y déjame ejecutar esto
store my name like hosan webdev right here and if i just log that to the console like my name let me just go back and let me just run this
6:59:29
código aquí así que aquí puedes ver que va a tomar un poco de tiempo
code right here so here you can see it's going to take a bit of time
6:59:32
y aquí puedes ver que va a imprimir mi nombre aquí si
and here you can see it's going to print us my name right here if
6:59:35
intentas agregar o si cambias el valor de eso como mi
you try to add or if you change the value of that like my
6:59:38
nombre y va a ser igual a como alguna otra persona
name and it's going to be equal to like some other person
6:59:42
o algo así esa persona, ahí vamos y ahora
or something like that person there we go and now
6:59:45
déjame guardar eso y solo ejecutar eso y aquí puedes ver que nos va a dar como algo, quiero decir, como algo de otra persona aquí, está bien, así que sí, así es como vamos a
let me just save that and just run that and here you can see it's going to give us like some i mean like something other person right here okay so yeah this is how we are going to be
6:59:55
crear una variable, así es como vamos a anotar eso.
creating a variable, this is how we are going to be annotating that.
7:00:00
y así es como vamos a cambiar el valor de eso y sí
and this is how we are going to be changing the value of that and yeah
7:00:03
ya sabes cómo vamos a registrar eso en la consola, así que ahora
you already know how we are going to be logging there to the console so now
7:00:06
déjame eliminarlos y ahora hablemos de los números así que
let me just remove them and now let's talk about for the numbers so
7:00:09
lo que quiero hacer es que voy a crear una variable como número favorito
what i want to do is that i'm going to create a variable like fav number
7:00:13
y voy a anotar ahí con un número y va a
and i'm going to annotate there with a number and it's
7:00:16
ser igual a como no sé, estaría bien y ahora déjame registrar eso
going to be equal to like i don't know it would be fine and now let me just log there
7:00:19
en la consola como número favorito y ahora déjame guardar allí y ejecutar
to the console like fav number and now let me just save there and run
7:00:22
allí déjame cerrar allí y volver a ejecutar una vez más
there let me just close there and rerun there once again
7:00:25
así que aquí puedes ver que ahora estamos llegando a aquí por qué es
so here you can see we are now getting at right here why is
7:00:28
eso porque lo anotamos como un número y estamos almacenando
that because we annotate that as a number and we are storing
7:00:32
el valor de aquí en el otro lado déjame comentar estos
the value of at right here on the other hand let me just comment these
7:00:35
comentar si intento agregar algún otro valor como yo
line out if i try to add some sort of other value like i
7:00:38
no sé verdadero en este caso y ya sabes que nos va a dar un error
don't know true in this case and you already know it's going to give us an error
7:00:41
como um el tipo booleano no es asignable a un tipo número pero de todos modos voy a guardar este archivo y ejecutar eso y vamos hombre, solo hice zoom, déjame volver a ejecutar eso una vez más
like um type boolean is not assignable to a type number but anyways i'm going to just save this file and run that and come on man i just zoomed in let me just rerun that once again
7:00:53
y aquí puedes ver que nos va a dar este error desagradable y es
and here you can see it's going to give us this nasty error and it is
7:00:56
diciendo que um no se puede compilar como nosotros
saying that um unable to compile like we
7:00:59
no podemos compilarlos y aquí puedes ver el error como tipo booleano
cannot compile them and here you can see the error like type boolean
7:01:02
no es asignable al tipo número aquí
is not assignable to the type number right here
7:01:05
bien, así que ya obtuviste el error y así es como se ve
okay so you already get the error and this is how it looks like
7:01:08
aquí voy a almacenar el valor de como 12 o algo así
right here i'm going to just store the value of like 12 or something like that
7:01:11
y finalmente ahora también vamos a crear uno para el booleano también voy a crear una variable como es difícil typescript o
and finally now let's also create one for the boolean as well i'm going to just create a variable like is timescript hard or
7:01:18
algo así y voy a anotarlos usando un booleano
something like that and i'm going to annotate them by using a boolean
7:01:21
y ahora va a ser igual a falso por defecto y ahora
and it's going to be now equals to false by default and now
7:01:24
déjame registrar eso en la consola como es typescript vamos es
let me just log that to the console like is typescript come on is
7:01:28
typescript o no typescript difícil ahí vamos
typescript or not typescript hard there we
7:01:31
ahora déjame vender eso y ejecutar eso y aquí puedes ver
go now let me just sell that and run that and here you can see
7:01:34
nos va a dar falso aquí por qué es eso porque nosotros
it's going to give us false right here why is that because we
7:01:37
ahora estamos anotando eso como lo que llamamos un booleano
are now annotating that as a what do we call a boolean
7:01:40
aquí y estamos almacenando el valor del booleano ahí vamos, así que ahora
right here and we are storing the value of boolean there we go so now
7:01:43
déjame proporcionar algún otro valor como ts difícil como
let me just provide some other value like ts hard like
7:01:46
typescript difícil y solo voy a proporcionar como un verdadero aquí
typescript hard and i'm going just provide like a true right here
7:01:49
ahora déjame guardar eso y ejecutarlo y aquí puedes ver que
now let me just save that and run that and here you can see it's
7:01:53
nos va a dar verdadero aquí porque estamos cambiando el valor de eso
going to give us true right here because we are changing the value of that
7:01:56
aquí está bien, pero supongamos que intento
right here okay so that's cool but let's suppose if i try to
7:01:59
acceder o supongamos que intento proporcionar como no sé
access or let's suppose if i try to provide like i don't know
7:02:02
12 o algo así y ahora déjame pasar el mouse sobre eso, así que el tipo número no es asignable al tipo booleano aquí, así que así es como vas a proporcionar anotaciones
12 or something like that and now let me just hover my mouse over to it so type number is not assignable to the type boolean right here so this is how you are going to be providing annotation
7:02:12
para tus variables aquí, así que ahora déjame guardar eso, así que eso fue todo sobre la anotación y ahora hablemos sobre la inferencia de tipos en TypeScript.
for your variables right here so now let me just save that so that was it about for annotation and And now let's talk about a type inference in TypeScript.
7:02:20
¿Qué es la inferencia de tipos y por qué deberías preocuparte por eso? Así que la inferencia de tipos es una característica en TypeScript que permite al compilador determinar automáticamente el tipo de variable basado en su valor.
So what is a type inference and why you should care about that? So the type inference is a feature in TypeScript that allow the compiler to automatically determine the type of variable based on its value, baby.
7:02:32
En otras palabras, si declaras una variable sin especificar explícitamente su tipo, TypeScript intentará inferir el tipo basado en el valor que le asignes.
In other words, if you declare a variable with explicitly specifying its type, TypeScript will try to infer the type based on its value you assign to it.
7:02:41
Sé que eso fue un montón de palabrería. Ahora déjame mostrarte algo de código, entonces sabrás de qué estoy hablando. Así que sí, aquí está el código.
I know, that was a lot of gibberish. Now let me just show you some code, then you will get to know what I'm talking about. So yeah, here is the code.
7:02:46
así que aquí puedes ver que no estamos proporcionando ninguna anotación
so here you can see we are not providing any annotations
7:02:50
aquí y aquí puedes ver que ahora estamos inferiendo este tipo
right here and here you can see we are now inferring this type
7:02:53
o no puedo pronunciar esto para inferir
or i can't pronounce this for inferring
7:02:57
o inferir lo que quieras llamarlos, esta vez aquí puedes
or inferring whatever you want to call them this time here you can
7:03:00
ver que estamos declarando una variable, estamos proporcionando el valor de cadena aquí
see we are declaring variable we are providing the value of string right here
7:03:03
entonces estamos proporcionando el add, luego estamos proporcionando el verdadero como un booleano aquí, por otro lado, si solo proporciono como para la variable de cadena, si proporciono un booleano
then we are providing the add then we are providing the true as a boolean right here on the other hand if i just provide like for the string variable if i provide a boolean
7:03:11
nos va a dar un error si proporciono como, ¿qué?
it's going to give us an error if i provide like um what
7:03:14
lo llamamos para número, si proporciono algún tipo de cadena, nos va a dar un
do we call it for number i provide some sort of a string it's going to give us an
7:03:18
error y también para booleano si especificas
error and for also for boolean if you specify
7:03:21
algún tipo de número o una cadena, también nos va a dar un error
some sort of a number or a string it's going to also give us an error
7:03:24
así que ahora déjame escribir algo de código, entonces sabrás de qué estoy hablando, voy
so now let me just write some code then you'll get to know what i'm talking about i'm
7:03:27
a eliminar todo ese código y encontrarás todo ese código en la descripción a continuación, que te llevará a mi repositorio de dhub y encontrarás todo ese código, así que ahora déjame declarar una variable
going to delete all of that code and you will find all of that code in the in yeah in the description below which will bring you to my dhub repository and you will find all of that code so now let me just declare a variable um
7:03:38
y voy a simplemente darme un nombre como tech y va a ser igual a como yo
and i'm going to just give me a name of like tech and it's going to be equals to like i
7:03:41
no sé TypeScript aquí, así que lo que hice es que simplemente
don't know typescript right here so what i did is that i just
7:03:45
declaré una variable aquí, si paso el mouse sobre
declared a variable right here if i hover my mouse over
7:03:48
eso, ¿qué estamos obteniendo? Estamos obteniendo estas anotaciones
to it so what are we getting we are getting these annotations
7:03:51
justo aquí déjame resaltar eso para ti aquí
right here let me just highlight that for you here
7:03:54
puedes ver que ahora estamos obteniendo esta anotación justo aquí
you can see we are now getting this annotation right here
7:03:58
por defecto así que ahora déjame registrar eso en la consola y
by default so now let me just log that to the console and
7:04:01
ver qué va a pasar y voy a escribir tech y ahora déjame
see what's going to happen and i'm going to just write tech and now let
7:04:04
registrar eso en la consola y probablemente ya sabes como uh
me just log that to the console and you probably already know like uh
7:04:07
qué tipo de lo reinició oh olvidé guardar el archivo ahora déjame guardar eso
which kind of reset it oh i forgot to save the file now let me just save that
7:04:10
y volver a ejecutarlo y aquí puedes ver que ahora estamos obteniendo el
and rerun that and here you can see we are now getting the
7:04:14
tipo de typescript correcto quiero decir como uh el valor de typescript
type of typescript right i mean like uh the value of typescript
7:04:17
justo aquí ahora déjame verificar el tipo de este chequeo justo aquí
right here now let me just check the type of this check right here
7:04:20
guardar mi archivo y volver a ejecutarlo va a darnos una cadena correcto
save my file and rerun that it's gonna give us a string right
7:04:23
aquí genial eso es increíble pero ahora vamos a
here cool that's amazing but now let's
7:04:27
suponer que si proporciono algún otro valor como no sé tal vez voy a proporcionar algún tipo de variable 12 o algo así
suppose if i provide like some other value to it like i don't know maybe um i'm gonna provide some sort of like 12 variable or something
7:04:34
así que si paso el ratón sobre ello va a dar
like that if i hover my mouse over to it it's going to give
7:04:37
un error va a decir algo como tipo número no es asignable
us an error it's going to say like type number is not assignable
7:04:40
a una cadena aquí esto no está permitido porque
to a string right here this is not allowed because
7:04:43
actualmente estás trabajando con un tipo de script no un javascript
you are currently working with a type script not a javascript
7:04:46
pero si estás usando un javascript ahora déjame cambiar eso a
but if you are using like a javascript now let me just change that to the
7:04:50
js aquí ya sabes que no nos va a dar ningún error o
js right here you already know it's not going to give us any errors or
7:04:53
cosa así simplemente eliminemos eso guarda mi
anything like that let's just remove that save my
7:04:56
archivo y ejecuta eso nos va a dar 12 aquí pero en el
file and run that it's going to give us 12 right here but on the
7:04:59
otro lado si cambiamos eso a ts déjame hacer eso de todos modos así que
other hand if we change that to ts let me just do that anyway so
7:05:02
si simplemente ejecuto este código aquí va a lanzar
if i just run this code right here it's going to throw
7:05:05
un hermoso error diciendo algo como um tipo número es
us a beautiful error saying like um type number is
7:05:08
no asignable a un tipo cadena aquí y asombroso ya sabes eso ahora déjame inferir algún otro valor como no sé número favorito o algo así y va a ser igual a 8 y ahora si los guardas
not assignable to a type string right here and amazing you already know that now let me just infer some other value like i don't know fave number or something like that and it's going to be equal to 8 and now if you save them
7:05:21
y si paso el ratón sobre ello aquí puedes ver qué estamos obteniendo
and if i hover my mouse over to it so here you can see what are we getting
7:05:24
estamos obteniendo la anotación del número
we are getting the annotation of number
7:05:27
justo aquí, así que inferirá automáticamente el valor
right here so it will automatically infer the value
7:05:30
del número, así que si intento cambiar el valor a
of number so if i try to change the value to
7:05:33
algo más, como no sé, una cadena, así que aquí
like something else like i don't know string so here
7:05:36
puedes ver que nos dará un error y ya sabes por qué ahora
you can see it's going to give us an error and you already know why now
7:05:39
déjame solo eliminarlos y ahora déjame crear también es o no es, pero t es difícil y va a ser igual a verdadero, ahora déjame
let me just remove them and now let me just create also is or not is but t is hard and it's going to be equals to like true now let me
7:05:47
decir allí, si mantengo mi mouse sobre él, nos dará
just say over there if i hold my mouse over to it it's going to give us
7:05:50
la anotación de booleano justo aquí, así que inferirá el valor de booleano, puedes decirlo así, ahora déjame duplicar eso y cambiarlo a número favorito y también voy a proporcionar el ts difícil justo aquí
the annotation of boolean right here so it's going to infer the value of boolean you can say it like that now let me just duplicate that and change that to fav number and i'm going to also provide the ts hard right here
7:06:03
guardar mi archivo y ejecutar eso, vamos, guardar mi archivo y
save my file and run that come on save my file and
7:06:06
ejecutar eso y aquí puedes ver que terminamos obteniendo typescript y también verdadero justo aquí, ahora vamos, déjame escribir un tipo de y guardar mi archivo
run that and here you can see we end up getting typescript and and also true right here now come on let me just write a type of and save my file
7:06:15
y ejecutar eso, vamos, no puedes ver, lo siento, estoy
and run that come on you can't see i'm sorry i'm
7:06:19
haciendo eso una y otra vez, pero tengo que hacerlo, así que el primer valor que estamos obteniendo es un número, como cadena, y el segundo es un número y el tercero es el booleano justo aquí, así que eso fue una inferencia de tipo o
doing that again and again but i have to so the first value we are getting a number i'm like string and the second one we are getting a number and the third one we are getting the boolean right here so that was a type inference or
7:06:30
inferir el tipo, como quieras pronunciar eso en typescript
inferring the type however you want to pronounce that in typescript
7:06:33
así que ahora hablemos de uno de los peores
so now let's talk about one of the awful one
7:06:36
oh, ni siquiera puedo decirlo, pero sí, uno de los tipos más extraños en typescript que
of the oh i can't even say it but yeah one of the weirdest type in typescript which
7:06:43
se llama tipo any, así que ¿qué es el tipo any y
is called any type so what is any type and
7:06:46
por qué deberías preocuparte por eso? así que typescript tiene un especial, sí
why you should care about that so typescript has a special yeah
7:06:49
especial, así que typescript tiene un tipo any especial que
special so typescript has a special any type that
7:06:52
se puede usar para representar cualquier tipo, así que como
can be used to represent any type so like
7:06:55
supongamos que cuando una variable está anotada con tipo any
let's suppose when a variable is annotated with any type
7:06:58
typescript le permitirá tener cualquier valor y
typescript will allow it to have any value and
7:07:02
deshabilitará toda la verificación de tipos para esa variable y sus propiedades, sí, eso es totalmente horrible, como, ¿por qué demonios usaríamos typescript si quieres proporcionar un tipo any? así que ahora déjame profundizar un poco más en este agujero de conejo.
disable all the type checking for that variable and its properties yeah that's totally awful like why on earth we would use a typescript uh if you want to provide any type so Now let me dig into this rabbit hole a bit more.
7:07:14
Así que, advertencia. Si bien el tipo any puede ser útil en ciertas situaciones, sí, obviamente, debe usarse con moderación.
So, warning. While the any type can be useful in certain situations, yeah, obviously, it should be used sparingly.
7:07:23
El uso excesivo de any puede llevar a código sin tipos y hacer que sea más difícil detectar errores relacionados con tipos durante el desarrollo.
Overuse of any can lead to untyped code and make it harder to catch type related bugs during the development.
7:07:30
Y ciertamente es mejor usar un tipo específico siempre que sea posible para obtener los beneficios de la verificación de tipos de TypeScript. Sí, ahí vamos.
And it's certainly better to use a specific type whenever possible to get the benefits of TypeScript type checking. Yep, there we go.
7:07:37
¿Cómo va a lucir eso? Bueno, no tienes que hacer nada más que
So how that's going to look like? well you don't have to do nothing but
7:07:40
simplemente declarar una variable y proporcionar el tipo any a
you just have to declare a variable and provide the any type to
7:07:44
ella y puedes proporcionar, no sé, el tipo
it and you can provide like i don't know the type
7:07:47
de número, el tipo de cadena, el tipo de lo que quieras
of number the type of string the type of whatever you want you
7:07:50
incluso puedes llamarlo como un
can even um you can even call it as a come
7:07:53
puedes incluso llamarlo como una función aquí, puedes proporcionar el
on you can even call it as a function right here you can provide the
7:07:56
dos mayúsculas y todas esas cosas y luego almacenar el horrible
two uppercase and all of that stuff and then store the awful
7:07:59
el tipo any puede ser útil en algunas situaciones, pero no todo el tiempo, y ten en cuenta eso, y aquí
the any type can be in some situation useful but not all the time and be aware of that and here
7:08:07
puedes ver que mencioné eso en esta diapositiva, así que quiero que siempre tengas
you can see i mentioned that in this slide so i want you to always keep
7:08:10
eso en mente y ahora vamos a entrar en la codificación, así que voy a simplemente
that in mind and now let's get into the coding so i'm going to just
7:08:13
eliminar todas esas cosas de aquí y voy a simplemente declarar una variable llamada
remove all of that stuff from here and i'm going to just declare a variable called
7:08:16
colores y voy a proporcionar o anotar eso con
colors and i'm going to provide or annotate that with
7:08:19
el any aquí y voy a simplemente establecer eso en carmesí o
the any right here and i'm going to just set that to crimson or
7:08:22
cualquier cosa así, ahora déjame registrar eso en la consola como tú
anything like that now let me just log that to the console like you
7:08:25
ya sabes lo que nos dará a cambio, así que aquí puedes
already know what it will give us in return so here you can
7:08:28
ver que ahora estamos obteniendo el color de carmesí, obviamente, y ahora
see we are now getting the color of crimson obviously and now
7:08:32
déjame proporcionar algo más, como no sé, el color de
let me just provide something else uh like i don't know color of
7:08:35
20 y ahora si vendo ahí y vuelvo a ejecutar
20 and now if I sell there and rerun there
7:08:38
y vuelvo a ejecutar, y aquí puedes ver que es
and rerun there and here you can see it's
7:08:41
nos va a dar 20 aquí, también podemos proporcionar, como yo
going to give us 20 right here we can also provide like I
7:08:44
no sé, podemos proporcionar cualquier cosa que queramos, voy a cambiar eso a como yo
don't know we can provide anything we want I'm going to just change that to like I
7:08:48
no sé, verdadero, podemos proporcionar, no sé, déjame simplemente llamar a eso
don't know true we can provide I don't know let me just call that
7:08:51
como una función, sabes, voy a simplemente comentar esta línea, déjame
as a function you know I'm going to just comment this line out let
7:08:54
simplemente vender ahí y volver a ejecutar, y aquí puedes ver que nos va a dar
me just sell there and rerun there and here you can see it's going to give
7:08:58
verdadero aquí, pero ahora simplemente llamemos a eso aquí, guarda
us true right here but now let just call that right here save
7:09:01
mi archivo y ejecutar este archivo una vez más y
my file and run this file once again and
7:09:04
aquí puedes ver que obviamente nos dará un error como
here you can see it's it's gonna obviously gives us an error like
7:09:08
uh color no es una función ni un objeto aquí así que
uh color is not a function or an object right here so
7:09:11
aquí puedes ver que nos dará un error no nos dará ningún error
here you can see it's gonna give us an error it's not gonna give us any error
7:09:14
dentro de nuestro editor pero una vez que ejecutemos este código va a
inside our editor but once we run this code it's gonna
7:09:17
darnos un error aquí y ese any es el
give us an error right here and that any is the
7:09:20
tipo más horrible que puedes encontrar en typescript
most awful type you can ever find on typescript
7:09:23
aquí si cambias eso a algo más como no sé si yo
right here if you change that to something else like i don't know if i
7:09:26
simplemente proporcioné anotación de cadena aquí va a
just um provided annotation of string right here it's going
7:09:29
darnos un error aquí puedes ver si paso el mouse sobre
to give us an error here you can see if i hover my mouse over
7:09:33
eso así que el tipo número no es asignable al tipo cadena y
to it so type number is not assignable to the type string and
7:09:36
también el tipo booleano tampoco es asignable a una cadena si yo
also type boolean is also not assignable to a string if i
7:09:39
paso el mouse sobre eso así que esta expresión no es un tipo llamable
hover my mouse over to it so this expression is not callable type
7:09:42
la cadena no tiene firmas de llamada está bien así que sí, eso fue todo sobre el final del tipo y ya te mostré las diapositivas así que ahora aprendamos sobre las anotaciones de parámetros de función en TypeScript.
string has no call signatures okay so yeah that was it about for the type ending and i already show you the slides so now let's learn about a function parameters annotations in TypeScript.
7:09:54
Así que la anotación de parámetros de función en TypeScript se utiliza para especificar los tipos esperados de los parámetros que una función debe tomar.
So function parameter and rotation in TypeScript are used to specify the expected types of perimeters that a function should take.
7:10:01
Está bien, ¿cómo se verá eso? Así es como se verá aquí.
Okay, so how that's going to look like? This is how it's going to look like right here.
7:10:04
No tienes que hacer nada, pero aquí solo tienes que anotar el perímetro de tu función.
You don't have to do nothing, but here you just have to annotate the perimeter of your function.
7:10:09
Haz algo aquí, como qué tipo de datos debe tomar este perímetro. Como en este caso, actualmente estamos agregando un número.
Do something right here, like which type of data this perimeter should be taking. Like in this case, we are currently adding a number.
7:10:16
Así que aquí puedes ver que ahora estamos proporcionando este número como perímetro, y lo estamos anotando con el número aquí.
So here you can see we are now providing this number as perimeter, and we are annotating that with the number right here.
7:10:22
y luego podremos realizar esta operación que fue
and then we would be able to perform this operation that was
7:10:25
cadena así que luego no podremos proporcionar este más aquí y nos dará un error y esta es la función regular y este es el sabor de la función de error aquí está bien, así que si tienes múltiples
string so then we won't be able to provide this plus right here and it's going to give us an error and this is a regular function flavor and this is the error function flavor right here okay so if you have like multiple
7:10:36
parámetros también puedes anotar eso aquí como x y
parameters you can also annotate that right here like x and
7:10:39
anotar eso con un número y también tenemos y y
annotate that with a number and also we have y and
7:10:42
anotar eso y así es como podemos trabajar con la anotación de perímetro de función con una función regular y también para las funciones de error también así que ahora déjame escribir algo
annotate that and this is how we can work with the function perimeter annotation with a regular function and also for the error functions as well so now let me just write some
7:10:50
código y luego sabrás de qué estoy hablando así que primero vamos a
code and then you will get to know what i'm talking about so first of all we
7:10:53
vamos a anotar la función regular, ¿verdad?
are going to be annotating the regular function right
7:10:56
aquí, así que voy a crear una función, le voy a dar un nombre de
here okay so i'm going to just create a function i'm going to give a name of
7:10:59
como añadir uno y aquí puedes ver mi id automáticamente
like add one and here you can see my id automatically
7:11:02
proporcionar un tipo para eso, así que solo voy a proporcionar un num y
provide a type for that so i'm going to just provide a num and
7:11:05
vamos a anotar eso con un número aquí, así que
we are going to be annotating that with a number right here okay so
7:11:08
dentro de eso, solo voy a devolver el num más uno y ahora déjame crear algún tipo de razón como const res y va a ser igual a como añadir uno y ahora déjame
inside there i'm going to just return the num plus one and now let me just create some sort of reason like const res and it's going to be equals to like add one and now let me just
7:11:16
proporcionar un tres o algo así, ahora déjame registrar eso en
provide a three or something like that now let me just log that to
7:11:19
la consola, vuelve y ejecuta eso, vamos
the console go back and run that come on
7:11:23
uh, ejecuta eso una vez más y aquí puedes ver
uh run that once again and here you can see
7:11:26
nos va a dar cuatro aquí, ¿por qué es eso? oh
it's gonna give us four right here why is that oh
7:11:29
¿por qué en la tierra? oh, ahí vamos porque estamos proporcionando uno
why on earth oh there we come because we are providing one
7:11:32
a eso, aquí estamos especificando tres, este
to it here we are specifying three this
7:11:35
número va a etiquetar ese tres y solo estamos sumando este uno aquí, así que nos va a dar cuatro de todos modos, así que si solo cambio eso a cadena, déjame cambiar eso a cadena y aquí
number is gonna tag that three and we are just adding this one right here so it's gonna give us four anyway so if i just change that to string let me just change that to string and here
7:11:44
puedes ver si paso el ratón sobre eso, nos va a dar esto, um
you can see if i hover my mouse over to it it's going to give us this um
7:11:48
error aquí, déjame resaltar eso para ti, argumento de
error right here let me just highlight there for you argument of
7:11:51
tipo número no es asignable al perímetro de un tipo
type number is not assignable to the perimeter of a type
7:11:54
cadena, así que obviamente nos va a dar
string okay so it's going to obviously give us
7:11:57
un error y ahí vamos, ahora déjame proporcionar un booleano, quiero mostrarte cada cosa y también nos va a dar un
an error and there we go now let me just provide a boolean i
7:12:00
error si paso el ratón sobre eso, así que el operador más no se puede aplicar a un tipo booleano, error número, um, y aquí
want to show you every single thing and it's going to also give us an
7:12:03
también puedes ver ese mismo error, ahora déjame cambiar eso a como
error if i hover my mouse over to it so operator plus cannot be applied to a type boolean error number um and here
7:12:10
um número una vez más y ahí vamos y
you can also see that same error now let me just change that to like
7:12:13
ahora déjame mostrarte también para las funciones de flecha, así que flecha
um number once again and there we go and
7:12:16
funciones o funk serían
now let me just show you for the arrow functions as well so arrow
7:12:20
bien, más bien, ahora déjame venderlas y sí
functions or funk would be
7:12:23
así que ahora déjame crear una función doble y va a tomar dos parámetros
fine rather now let me just sell them and yep
7:12:26
así que ahora déjame crear una función doble y va a tomar dos parámetros
so now let me just create a double function and it's going to take two parameters
7:12:29
el primero que va a tomar es para x y también va a tomar el y, vamos a escribir una coma y y y vamos a estar proporcionando
the first one it's going to take is for x and it's going to also take the y as well come on let me just write a comma and y and we are going to be just uh providing
7:12:38
como x por y aquí y ahora si
like x times y right here and now if i
7:12:41
simplemente lo registro en la consola como doble o sabes que no voy a registrar eso en la consola
just log that to the console like double or you know what i'm not going to log that to the console
7:12:44
voy a escribir const res y va a ser igual a doble y
i'm going to just write const res and it's going to be equals to double and
7:12:47
voy a proporcionar como 2 y 10 aquí, está bien
i'm going to provide like 2 and 10 right here okay
7:12:50
así que si paso el mouse sobre eso, nos va a dar como perímetro
so if i hold my mouse over to it so it's going to give us like perimeter
7:12:53
x implícitamente tiene el tipo any
x implicitly has the any type
7:12:57
aquí por defecto, como dije, tienes que tener eso en mente, así que aquí puedes ver que nos va a dar como por
right here by default as i said that you gotta keep that in mind so here you can see it's going to give us like by
7:13:04
defecto el tipo de any porque typescript no
default the type of any because typescript do not
7:13:07
sabe qué tipo de datos vamos a estar especificando o
know which kind of data we are going to be specifying it or
7:13:10
este parámetro aquí, como si vamos a proporcionar el número
this parameter right here like either we are going to be providing the number
7:13:13
o vamos a proporcionar algún tipo de cadena o vamos a proporcionar
or we are going to be providing some sort of a string or we are going to be providing
7:13:16
algún tipo de booleano o algo así, typescript no tiene
some sort of a boolean or something like that typescript don't have
7:13:20
idea de lo que vamos a estar proporcionando aquí dentro de un doble, así que
any idea what we are going to be providing right here inside a double so
7:13:23
por eso typescript proporcionará por defecto el tipo implícito de any aquí, está bien, así que lo que quiero hacer es que voy a cambiar eso a
that's why the typescript will by default provide the implicit type of any right here okay so what i want to do is that i'm going to just change that to
7:13:33
número aquí, así que voy a anotar eso con número y también voy a cambiar este a número también y este va a darnos un error porque redeclaramos
number right here so i'm going to just annotate there with number and i'm going to also change this one to number as well and this one is going to give us an error because we redeclare
7:13:42
uh bloques, no sabía eso, no dejemos
uh blocks go i didn't know that no let
7:13:45
me oh, sabes, análisis o sabes que voy a comentar
me oh you know alysis or you know i'm going to just comment
7:13:49
esta línea y ahora, uh déjame
this line out and now uh let me just
7:13:52
registrar eso en la consola como res y ahora déjame volver a ejecutar mi código y aquí puedes ver que nos va a dar 20 aquí, ¿por qué es eso? porque
log there to the console like res and now let me just go back run my code and here you can see it's going to give us 20 right here why is that because
7:14:00
estamos proporcionando un 2 para el primer perímetro y estamos proporcionando
we are providing a 2 for the first perimeter and we are providing
7:14:03
10 para el segundo, así que por eso ahora estamos obteniendo 2 aquí, está bien
10 for the second one so that's why we are now getting 2 right here okay
7:14:07
así que así es como funciona el tipo any, así es como vas a
so this is how the any type work this is how you are going to
7:14:10
anotar los perímetros de tu función aquí, oh, olvidé mostrarte algo, uh déjame mostrarte eso ahora
be annotating your function perimeters right here oh i
7:14:13
olvidé mostrarte algo, déjame mostrarte eso ahora
forgot to show you something uh let me just show you that right
7:14:16
aquí supongamos que si proporcionas más valores de los que especificamos
here let's suppose if you provide more values than we specified
7:14:19
dentro de una firma de perímetro aquí nos dará un error, así que también nota que typescript dará
inside a perimeter signature right here it's gonna give us an error so also notice typescript will give
7:14:25
una advertencia si proporcionas más o menos argumentos de los que
a warning if you provide more or less argument then
7:14:28
especificas en el área del perímetro aquí, está bien, así que
you specify in the perimeter area right here okay so
7:14:32
ahora déjame proporcionar algo como no sé, va a tomar dos
now let me just provide something like i don't know it's gonna take two
7:14:35
parámetros como x y también el y, así que voy a
parameters like x and also the y so i'm gonna
7:14:38
especificar como no sé, tal vez 20 y aquí puedes
just specify like i don't know maybe 20 and here you
7:14:41
ver que nos dará un error si paso el mouse sobre él, va a
can see it's gonna give us an error if i hold my mouse over to it it's
7:14:44
darnos como dos argumentos inesperados pero obtuvimos tres
gonna give us like unexpected two arguments but got three
7:14:47
o supongamos que si simplemente elimino ambos y
or let's suppose if i just remove both of them and
7:14:51
solo proporcionamos uno, si paso el mouse sobre él, esperaba
we just provide one to it if i I hover my mouse over to it expected
7:14:54
dos argumentos pero obtuve uno aquí, así que va a dar
two arguments but got one right here so it's going to give
7:14:57
este error también, así que quiero que también tengas
us this error as well so I want you to also keep
7:15:01
eso en mente, así que ahora hablemos de nuestros
that in mind as well so now let's talk about our
7:15:04
valores de parámetros predeterminados en typescript, así que hoy en día en
default parameter values in typescript so nowadays in
7:15:07
javascript también tenemos esta característica disponible en es6 como
javascript we also have this feature available in es6 like
7:15:11
en javascript moderno podemos especificar el valor predeterminado
in modern javascript we can specify the default
7:15:14
para nuestro perímetro aquí, así que si quieres proporcionar un valor predeterminado para tu parámetro en una función usando typescript, tienes que anotar eso aquí
value to our perimeter right here so if you want to provide a default value for your parameter in uh in a function by using a typescript you have to annotate that right here
7:15:23
así que solo tienes que proporcionar esta anotación y puedes especificar cualquier
so you just have to provide this annotation and you can specify any
7:15:26
valor que desees, así que en este caso solo estamos creando esta función y bla bla bla
value you want so in this case we are just creating this function and blah blah blah
7:15:29
sí, sé que fue rápido, así que ahora déjame
yeah i know that was quick so now let me
7:15:32
simplemente escribir algo de código porque no quiero perder tu tiempo ahora
just write some code because i don't want to waste your time now
7:15:35
déjame simplemente escribir algo de código y luego sabrás de qué estoy hablando, así que ahora déjame
let me just write some code and then you'll get to know what i'm talking about so now let
7:15:38
simplemente eliminar eso y voy a crear una función, dame un nombre como
me just remove that and i'm going to just create a function give me a name of like
7:15:41
saludar o algo así y también voy a proporcionar una persona y déjame quitar eso aquí y quiero establecerlo como
greet or something like that and also i'm going to provide a person and let me just remove that right here and i want to set that to like
7:15:49
no sé anónimo ni siquiera
i don't know anonymous i don't even
7:15:52
sé cómo se escribe el anónimo pero de todos modos ahora déjame devolver
know how to spell the anonymous but anyways now let me just return
7:15:55
como no sé hola y persona bien
like i don't know hello and person right
7:15:58
aquí está bien y también voy a proporcionar constres y
here okay and also i'm going to just provide constres and
7:16:02
saludar y no voy a proporcionar ningún valor para ellos
greet and i'm not going to provide any value for them
7:16:05
déjame registrar este resto en la consola déjame volver y
let me just log this rest to the console let me just go back and
7:16:08
vender mi archivo así que ¿qué crees que será el resultado si ejecuto este archivo?
sell my file so what do you think will be the result if i run this file
7:16:11
y hola anónimo aquí lo que significa que esto está funcionando totalmente bien si yo
and hello anonymous right here which means like this is working totally okay if i
7:16:18
cómo está mi ratón sobre él así que ¿qué estamos obteniendo? estamos obteniendo
how are my mouse over to it so what are we getting we are getting
7:16:22
la inferencia por defecto en type script correcto
the default inferring in type script right
7:16:25
aquí así que la persona ahora está configurada actualmente como cadena así que eso es
here so person is now currently set to string so that's
7:16:28
lo que estamos obteniendo aquí como totalmente bien pero si quieres
what we are getting right here like totally a-okay but if you want
7:16:31
proporcionar una anotación específica para esta persona vamos a estar
to provide a specific annotation for this person we are going to be
7:16:34
haciéndolo así así que voy a proporcionar mi separador y luego
doing it like so so i'm going to just provide my separator and then
7:16:37
voy a escribir mi cadena puedes proporcionar como número si solo escribo número siempre nos dará un error dirá que el tipo cadena no es asignable a un tipo número correcto
i'm going to write my string you can provide like number if i just write number it's going to always give us an error it's going to say like type string is not assignable to a type number right
7:16:46
aquí vamos a cambiar eso a cadena bebé déjame guardar eso y volver a ejecutar una vez más
here let's just change that to string baby let me just save that and rerun there once again
7:16:51
y hola anónimo aquí pero si quiero proporcionar algún tipo de valor como hosan
and hello anonymous right here but if i want to provide some sort of value like hosan
7:16:57
semi-archivo nos va a dar como hola hosan ahí
semi-file it's going to give us like hello hosan there
7:17:00
ahí vamos como dije, typescript no es tan difícil y estamos casi allí bebé estamos casi allí así que ahora hablemos sobre el valor de retorno
we go as i said like typescript is not that hard and we are almost there baby we are almost there so now let's talk about the return value
7:17:09
anotaciones para una función en typescript así que ¿qué quiero decir con eso? así que supongamos que en esta función vas a devolver algún tipo de valor.
annotations for a function in typescript so what do i mean by that so let's suppose in this function you are going to be returning some sort of a value.
7:17:18
Así que como en este caso, ahora estamos devolviendo el número aquí. Estamos proporcionando el x y lo estamos anotando como número.
So like in this case, we are now returning the number right here. We are providing the x and we are annotating there by number.
7:17:24
Así que obviamente, vamos a estar devolviendo algún tipo de número para esta función.
So obviously, we are going to be returning some sort of a number for this function.
7:17:27
Así que si quieres anotar la declaración de retorno también, para eso, fuera del área del perímetro, vas a proporcionar tus anotaciones aquí y luego puedes hacer lo que quieras.
So if you want to annotate the return statement as well, so for that, outside from the perimeter area, you are going to be providing your annotations right here and then you can do whatever you want.
7:17:38
Está bien, así que esto es para una función regular. Ahora hablemos también de las funciones de flecha.
Okay, so this is for a regular function. Now let's talk about for the arrow functions as well.
7:17:43
Así que aquí puedes ver que solo estamos creando un doble dos y si
So here you can see we are just creating a double two and if
7:17:46
quieres anotar el valor del perímetro, así que así es como lo vas a anotar
you want to annotate the perimeter value so this is how you are going to be annotating
7:17:49
ahí, pero si quieres anotar el valor de retorno, así que
there but if you want to annotate the return value so
7:17:52
para eso vas a escribir una sintaxis como
for that you are going to be writing syntax like
7:17:55
esto aquí, así que este será para la anotación de retorno
this right here so this one will be for the return annotation
7:17:58
y luego puedes hacer lo que quieras hacer dentro de esa función
and then you can do whatever you want to do inside that function
7:18:01
y así es como vas a estar registrando allí en la consola, así que
and this is how you're going to be logging there to the console so
7:18:04
ahora déjame escribir algo de código, entonces sabrás de qué estoy hablando, así que primero para la función regular aquí y voy a crear
now let me just write some code then you'll get to know what i'm talking about so first of all for the regular function right here and i'm going to just create
7:18:11
una función, darle un nombre como doble, va a venir
a function give a name of like double it's going to come
7:18:14
déjame hacer eso una vez más, función y
on let me just do that once again function and
7:18:18
voy a darle un nombre como doble uno aquí, va a tomar el
i'm going to give a name of like double one right here it's going to take the
7:18:21
perímetro de x y el tipo se establecerá en número, ¿verdad?
perimeter of x and the type will be set to number right
7:18:24
aquí, así que para esta función vamos a estar retornando
here so for this function we are going to be returning
7:18:27
como x por x, lo que significa que vamos a estar retornando
like x time x so which means like we are going to be returning
7:18:31
el valor de esta función, si paso el mouse sobre eso, aquí puedes ver que el tipo de script inferirá automáticamente el valor de
the value from this function if i hold my mouse over to that here you can see the type script will automatically infer the value of
7:18:37
número, aquí también podemos proporcionarlos nosotros mismos, así que
number right here we can also provide them by ourselves so
7:18:40
voy a proporcionar este separador y voy a proporcionar un número aquí
i'm going to just provide this separator and i'm going to just provide a number right here
7:18:43
y ahí vamos, así que ahora déjame escribir const res y
and there we go so now let me just write const res and
7:18:47
va a ser igual a como doble uno y en este caso vamos a estar
it's going to be equals to like double one and in this case we are going to be
7:18:50
solo escribiendo dos, ahora déjame registrar este res en la consola
just writing two now let me just log this res to the console
7:18:53
guardar mi archivo, ejecutarlo, nos va a dar cuatro
save my file run it it's going to give us four
7:18:56
aquí ahora estamos duplicando el valor de esto
right here now we are doubling uh the value of this
7:18:59
función, así que sé que no es algo tan difícil de aprender, pero si quieres anotar el tipo de retorno, quiero decir, si tú
function so i know that's not that much difficult thing to learn but if you want to annotate the return type uh i mean like if you
7:19:05
quieres anotar ese valor de retorno, así que así es como
want to annotate that return value so this is how
7:19:08
lo vas a hacer usando una función regular y ahora
you're going to be doing that by using a regular function and now
7:19:11
hablemos también de las funciones de flecha, así que déjame
let's talk about for the arrow functions as well okay so let
7:19:15
crear una función de flecha y dentro de ahí, ¿qué quieres hacer?
me just create an arrow func and inside there what do you want to do
7:19:18
solo queremos crear un doble dos y va a ser igual a como
we just want to create a double two and it's going to be equals to like uh
7:19:21
va a tomar algún tipo de perímetro como x y vamos a
it's going to take some sort of a perimeter like x and we are
7:19:24
anotar eso como un número y solo voy a proporcionar como
going to be annotating that as a number and i'm going to just provide like
7:19:27
un número y va a tomar x tiempo x ahí vamos, ahora déjame registrar ese doble y proporcionar un dos o algo así
a number and it's going to take x time x there we go now let me just log that double and provide a two or something like that
7:19:35
solo guardemos eso y ejecutemos, vamos
let's just save that and run that come on i
7:19:38
está muy ampliado, así que aquí puedes ver que nos va a dar
just way zoomed in okay so here you can see it's going to give us
7:19:41
cuatro y ahí vamos, así es como vas a anotar
four and there we go this is how you are going to be annotating
7:19:44
el valor de retorno que vas a obtener de
the return value which you are going to be getting from
7:19:47
esta función, a veces lo sabrías y muchas veces no, así que typescript inferirá el valor aquí por defecto, pero sí, entiendes la idea, así que ahora hablemos
this function sometime you would know that and a lot of time you don't so typescript will by default infer the value right here but yeah you get the idea so now let's talk
7:20:00
del void en typescript. Entonces, ¿qué es un void y por qué deberías preocuparte por eso?
the void in typescript. So what is a void and why you should care about that?
7:20:04
Así que void es un tipo que representa la ausencia de cualquier valor.
So void is a type that represents the absence of any value.
7:20:08
A menudo se usa como el tipo de retorno para funciones que no devuelven ningún valor.
It is often used as the return type for the function that do not return any value.
7:20:15
Está bien, entonces vamos a usar este void. Está bien, y así es como se verá el código.
Okay so then we're going to be using this void. Okay and this is how the code will look like.
7:20:20
Así que aquí puedes ver que tenemos esta función que no está devolviendo algo, pero solo estamos registrando como este es mi mensaje o algo así en la consola.
So here you can see we have this function which is not returning something but we are just logging like this is my message or something like that to the console.
7:20:27
así que aquí tenemos que especificar void justo aquí, no tienes que hacer nada
so here we have to specify void right here you don't have to do nothing
7:20:30
pero solo tienes que especificar este void y lo hará por
but you just have to specify this void and it's going to do it for
7:20:34
ti, está bien, así que ahora déjame escribir un poco de código, entonces sabrás de qué estoy hablando
you okay so now let me just write some code then you will get to know what i'm talking
7:20:37
voy a eliminar todo ese código, voy a crear una función una vez
about i'm going to delete all of that code i'm going to create a function once
7:20:40
más, un nombre humano como imprimir mensaje o algo así
again human name of like print message or something like that
7:20:43
va a tomar como un mensaje como un perímetro, vamos
it's going to take like a message as a perimeter come
7:20:46
solo un mensaje y vamos a especificar el valor de cadena para ello y puedes anotar eso con lo que quieras y ahora déjame registrar en la consola
on just a message and we're going to be specifying the string value to it and you can annotate that with anything you want and now let me just console log
7:20:53
un valor como este es mi análisis render
some value like this is my analysis render
7:20:56
o mensaje justo aquí y ahora déjame escribir y proporcionar
or message right here and now let me just write and provide
7:21:00
un mensaje aquí déjame solo guardar eso volver y ejecutar eso
a message right here let me just save that go back and run that
7:21:03
vamos tengo que hacerlo manualmente y aquí puedes ver uh
come on i gotta do that manually and here you can see uh
7:21:06
este es mi mensaje aquí el cual está funcionando totalmente si
this is my message right here which is totally working if
7:21:09
tengo mi mouse sobre eso así que aquí puedes ver qué estamos obteniendo estamos
i have my mouse over to it so here you can see what are we getting we
7:21:13
obteniendo este blanco aquí porque es eso porque para esta función ni siquiera estamos devolviendo nada si solo escribo como
are getting this white right here why is that because for this function we are not even returning anything if i just write like
7:21:21
devolver y mensaje y cerremos eso
return and message and let's just close that
7:21:24
y si paso mi mouse sobre eso ahora va a anotar
and if i hover my mouse over to it right now it's going to annotate
7:21:28
eso con una cadena aquí así que también podemos hacer eso manualmente
that with a string right here so we can also do that manually
7:21:31
así que solo tenemos que escribir este separador y blanco y
so we just have to write this separator and white and
7:21:34
aquí puedes ver si paso mi mouse sobre eso así que ahora estamos obteniendo
here you can see if i hover my mouse over to it so we are now getting
7:21:37
blanco aquí está bien así que sí esto es
white right here okay so yeah this is
7:21:40
un blanco y deberías evitar porque deberías devolver algún valor de tu función así que ahora hablemos sobre el hermano la hermana la madre o
a white and you should avoid because you should return some value from your function so now let's talk about the brother the sister the mother or
7:21:50
lo que quieras llamar eso un abuelo de cualquier
whatever you want to call that a grandfather of any
7:21:53
palabra clave así que de qué estamos hablando estamos hablando
keyword so what are we talking about we are talking
7:21:56
sobre la palabra clave nunca reservada en typescript así que qué es
about the never reserved keyword in typescript so what is
7:21:59
la nunca la palabra clave nunca se usa para indicar que una función no
the never the never keyword is used to indicate that a function will not
7:22:02
devolverá nada pero confía en mí es totalmente diferente
return anything but trust me it's totally different
7:22:05
que el blanco o que una variable nunca puede tener
than the white or that a variable can never have
7:22:09
un valor el tipo nunca es útil para indicar que
a value the never type is useful for indicating that
7:22:12
un cierto camino de código nunca debe ser alcanzado o que ciertos valores son imposibles puede ayudar a detectar errores en tiempo de compilación en lugar de en tiempo de ejecución.
a certain code path should never be reached or that a certain values are impossible it can help catch errors at compile time instead of run time.
7:22:21
Entonces, ¿cómo demonios vamos a usar la palabra clave nunca? Vamos a usar eso para tres casos.
So how on earth we are going to be using the never keyword? We are going to be using that for three cases.
7:22:27
Así que como una función que siempre lanza un error, vamos a usar la palabra clave nunca para eso.
So like a function that always throw an error, we are going to be using never keyword for that.
7:22:31
O una función que tiene un bucle infinito, vamos a usar un nunca para eso.
Or a function that has an infinite loop, we are going to be using a never for that.
7:22:36
O una variable que nunca puede tener ningún valor. Así que para eso podemos usar la palabra clave nunca.
Or a variable that can never have any value. So for that we can use the never keyword.
7:22:42
Así que ahora déjame darte el ejemplo de eso. Así que ahora hablemos sobre la función
So now let me just give you the example of that. So now let's talk about the function
7:22:45
que siempre lanza un error, así que si ya has trabajado
that always throw an error so if you've already worked
7:22:48
con el stack mern y específicamente en expressjs y
with the mern stack and specifically in the expressjs and
7:22:52
no estoy asumiendo que ya trabajas con eso, pero solo voy a decir
i'm not assuming that you already work with that but i'm gonna just say
7:22:55
como para algunos de ustedes, si ya trabajan con el stack mern y específicamente para
like for some of you if you already work with the mern stack and specifically for
7:22:59
el expressjs, un medio para um, tú
the expressjs a middle verse for um you
7:23:02
sabes que eso es otra historia, vamos a salir de aquí, sabes que eso es solo otra historia, así que aquí puedes ver que ahora estamos creando una función, estamos
know what that's other story let's just get the hell out you know what that's just other story so here you can see we are now creating a function we are
7:23:09
proporcionando algún tipo de mensaje y ahora estamos proporcionando un error para ese mensaje, así que para eso podemos anotar eso con una palabra reservada nunca aquí, está bien, así que ahora hablemos de
providing some sort of a message to it and we are now providing an error for that message so for that we can annotate that with a never reserved keyword right here okay so now let's talk about
7:23:19
el bucle infinito, así que ahora en este caso solo estamos proporcionando el infinito
for the infinite loop so now in this case we are just providing the infinite
7:23:22
bucle, así que para eso también podemos usar la palabra reservada nunca para
loop so for that we can also use the never reserved keyword for
7:23:25
como recursión o algo así, también podemos
like recursion or something like that we can also
7:23:28
usar la palabra nunca y, por cierto, esta palabra nunca puede ser
use the never keyword and by the way this never keyword can be
7:23:31
raramente utilizada en este tipo de situación, como cuando estamos lanzando algún tipo de error y nunca he usado eso en algún tipo de
rarely used in this kind of situation like when we are throwing some sort of an error and i have never used that in some sort of
7:23:38
¿cómo lo llamamos? para bucle infinito o
what do we call it for infinite loop or
7:23:41
algo así, también puedes usarlo como una variable que puede
something like that you can also use it like a variable that can
7:23:45
nunca tener un valor, así que aquí puedes ver que estamos declarando una variable y
never have a value so here you can see we are declaring a variable and
7:23:48
estamos especificando al anotar eso con la palabra reservada nunca
we are specifying on annotating that with the never reserved
7:23:52
aquí y también en esta función estamos proporcionando
keyword right here and also in this function we are providing
7:23:55
el bucle infinito, así que por eso proporcionamos una palabra reservada nunca y ahora este x va a ser igual a esta función de bucle infinito, así que esta línea causará un error de compilación
the infinite loop so that's why we provide a never reserved keyword and now this x is going to be equal to this infinite loop function so this line will cause a compile time error
7:24:05
porque la función nunca retorna, así que entonces, uh, va a ser
because the function never returns so then uh it's
7:24:09
igual a la palabra reservada nunca aquí, sé que suena confuso
going to be equals to the never reserved keyword right here i know that sounds confusing
7:24:12
pero ahora déjame escribir algo de código y luego sabrás de qué estoy hablando
but now let me just write some code and then you'll get to know what i'm talking
7:24:15
y este no es tanto, sabes, que uso, pero quiero
about and this one isn't that much you know i use but i
7:24:18
incluirlo en este curso de todos modos para algunos de ustedes que
want to include it in this course anyways for some of you who
7:24:21
les importa, así que voy a escribir lanzar, uh
cares about it so i'm going to just write throw uh
7:24:25
no sé, lanzar error o algo así, voy a proporcionar un mensaje y vamos a anotar eso como una cadena y voy a proporcionar como lanzar nuevo error
i don't know throw error or something like that i'm going to provide a message and we are going to be just annotating that as a string and i'm going to just provide like throw new error
7:24:34
del mensaje y podemos anotar eso con nunca
of message and we can annotate that with never
7:24:37
palabra clave reservada justo aquí y ahora si paso el ratón
reserved keyword right here and now if i hover my mouse
7:24:40
sobre eso, así que aquí puedes ver que ahora estamos obteniendo el nunca um
over to it so here you can see we are now getting the never um
7:24:43
maldita sea, si paso el ratón sobre
god damn it if i hover my mouse over to
7:24:46
eso, así que aquí puedes ver que ahora estamos obteniendo la palabra clave reservada nunca justo aquí, está bien
it so here you can see we are now getting the never reserved keyword right here okay
7:24:50
así que sí, puedes usar eso si quisieras, ahora déjame darte
so yeah you can use that if you wanted to now let me just give you
7:24:53
otro ejemplo de bucle infinito, así que solo voy a escribir infinito
another example of infinite loop so i'm going to just write infinite
7:24:56
o i n f i vamos, i n
or i n f i come on i n
7:25:00
f i n i t bucle y vamos a
f i n i t loop and we're going to
7:25:03
simplemente no proporcionar nada en absoluto y solo voy a
be just not providing anything at all and i'm going to just
7:25:06
anotar eso con la palabra clave reservada nunca y dentro de eso
annotate that with the never reserved keyword and inside that we
7:25:09
vamos a estar usando el mientras y verdadero si eso es cierto
are going to be using the while and true if that's true
7:25:12
así que tendríamos algún tipo de bucle infinito y ya sabes todas esas cosas, así que solo voy a escribir let x y vamos a estar anotando eso con el nunca
so we would get some sort of infinite loop and you already know all of that stuff so i'm going to just write let x and we are going to be annotating that with the never
7:25:20
palabra clave reservada y déjame crear algún tipo de función y
reserved keyword and let me just create some sort of a function and
7:25:24
nunca regresará
never returns will
7:25:27
está bien, no vamos a proporcionar nada aquí y
be fine we're not going to be providing anything right here and
7:25:30
voy a anotar eso con la palabra clave reservada nunca y
i'm going to just annotate that with the never reserved keyword and
7:25:33
mientras verdadero, nos dará un bucle infinito
while true it's going to give us an infinite loop
7:25:36
y también vamos a proporcionar que x es igual a nunca regresa y ahí vamos, así que ahora déjame volver, puedes usar la palabra clave reservada nunca cuando estás lanzando algún tipo de error
and we are going to be also providing the x is equal to never returns and there we go so now let me just go back so you can use the never reserved keyword when you're throwing some sort of an error
7:25:47
también puedes proporcionarlo para la función que están en
you can also provide it for the function which are in
7:25:50
el bucle y también puedes usarlo para una variable que no tiene
the loop and you can also use it for a variable who does
7:25:53
ningún valor aquí, está bien, así que había un nunca
not have any value right here okay so there was a never
7:25:56
palabra clave desierto en typescript, así que ahora hablemos de arreglos
desert keyword in typescript so now let's talk about arrays
7:26:00
en typescript, así que los arreglos son un tipo de objeto que puede
in typescript so arrays are a type of object that can
7:26:03
almacenar múltiples valores del mismo tipo de dato
store multiple values of the same data type
7:26:06
está bien, así que los arreglos en TypeScript son tipo, está bien, esto es algo de lo que voy a estar hablando ahora mismo, lo que significa que puedes especificar el tipo
okay so arrays in typescript are type okay this is something which i'm going to be discussing right now which means you can specify the type
7:26:13
de valores que un arreglo puede contener, está bien, así que sí
of values that an array can hold okay so yeah
7:26:17
esa fue solo una definición básica de arreglos en TypeScript, ahora
that was just a basic definition of arrays in typescript now
7:26:20
déjame darte un ejemplo de eso, pero antes de hacerlo, hay
let me just give you example of that but before i do there are
7:26:23
dos formas de crear un arreglo en TypeScript
two flavors of creating an array in typescript
7:26:26
así que la primera es usando una notación de corchetes y
so the first one is using a bracket notation and
7:26:29
la segunda es usando este tipo de sintaxis que no sé, tipo HTML
the second one is using this kind of i don't know html-ish
7:26:33
sintaxis tipo html aquí
html-ish kind of syntax right
7:26:36
bien, así que ahora déjame mostrarte el primero que usa la notación de corchetes, así que primero vamos a
here okay so now let me just show you the first one which uses the bracket notation so first of all we are going to be
7:26:42
crear nuestro arreglo regular aquí como vamos a estar primero de
creating our regular array right here like we're going to be first of
7:26:45
todo declarando nuestra variable, luego vamos a almacenar algún tipo de valores
all declaring our variable then we're going to be storing some sort of values
7:26:48
usando una notación de corchetes, pero si quieres inferir
by using a bracket notation but if you want to infer
7:26:52
que primero vamos a usar este separador, entonces vamos a
that first of all we are going to be using this separator then we are
7:26:55
proporcionar algún tipo de un tipo, como qué tipo de datos
going to be providing some sort of a type like which type of data
7:26:58
esta variable o este arreglo va a contener, va a
this variable or this array is going to be holding it's
7:27:02
contener arreglos de números aquí, pero si intentamos
going to be holding the arrays of numbers right here but if we try
7:27:05
proporcionar, no sé, cadenas o booleanos o funciones o objetos o algo así, va a lanzar
to provide like i don't know strings or booleans or uh function scale or objects or something like that it's going to throw
7:27:11
un error, algo que te voy a mostrar en unos segundos y
an error something which i'm going to show you in a few seconds and
7:27:14
esta es la segunda sintaxis para crear un arreglo
this one is the second syntax of creating an array
7:27:18
dentro de TypeScript y esta ya está totalmente
uh inside a typescript and this one is totally
7:27:21
obsoleta, nadie usa esta sintaxis ya, está bien
old nobody use this syntax anymore okay
7:27:24
así que sí, así es como vas a crear un arreglo en
so yeah this is how you're going to be creating an array in
7:27:27
TypeScript, así que ahora déjame darte un ejemplo de eso, entonces entenderás
typescript so now let me just give you example of that then you'll get
7:27:30
de qué estoy hablando, así que ahora déjame quitar todo ese código
to know what i'm talking about so now let me just remove all of that code
7:27:33
aquí, así que ahora déjame crear una variable nums
right here so now let me just create a nums variable
7:27:36
o variable nums así y voy a simplemente anotar eso
or nums variable like so and i'm going to just annotate that
7:27:40
con el número de arreglos aquí y va a ser igual a
with the number of arrays right here and it's going to be equals to
7:27:43
uh algún tipo de número como no sé uno dos cuatro
uh some sort of a number like i don't know one two four
7:27:46
seis o lo que quieras llamar eso ahora déjame solo registrar
six or whatever you want to call that now let me just log
7:27:49
este nums en la consola aquí semi archivo ir
this nums to the console right here semi file go
7:27:52
adelante y ejecuta eso, nos va a dar como uno dos cuatro
ahead and run that it's going to give us like one two four
7:27:55
seis y todos sus datos que ya estamos especificando dentro de esta área aquí ahora déjame entrar en eso supongamos que solo especifico algo
six and all of their data which we are already specifying it inside this area right here now let me just get into it let's suppose if i just specify something
7:28:04
más como no sé si quiero proporcionar como cadena
else like i don't know if i want to provide like string
7:28:07
así que cadena uno cadena y si quiero proporcionar
so string one string and if i want to provide
7:28:10
algún tipo de otro valor como verdadero o algo así es
some sort of other value like true or something like that it's
7:28:13
va a darnos un error ¿por qué es eso? porque actualmente estamos
going to give us an error why is that because currently we
7:28:16
especificando que este arreglo debería contener los
are specifying like this array should hold the
7:28:19
arreglos de números solo números nada más después
numbers array only numbers nothing else later
7:28:23
también vamos a aprender sobre este operador pero aún no estamos allí así que no vamos a discutir eso ahora así que si paso el mouse sobre él
we are going to be also learning about this operator but we are not there yet so we are not going to be discussing that right now so if i hold my mouse over to it
7:28:31
así que el tipo cadena no es asignable al tipo número aquí si
so type string is not assignable to the type number right here if
7:28:35
pongo el mouse sobre este así que el tipo booleano no es asignable a
i hover my mouse over to this one so type boolean is not assignable to
7:28:38
nuestro tipo número aquí así que obtendremos un error aquí
our type number right here so we will get an error right here
7:28:41
déjame simplemente eliminarlos y este fue el primero
let me just remove them and this one was a first
7:28:44
sabor o sabes déjame también darte un ejemplo de cadenas como
flavor or you know let me just also give you example of strings as
7:28:48
bueno así que cadena y voy a anotar eso uh con cadena aquí y va a ser igual a como no sé uno dos o algo así tres tal vez
well so stir and i'm going to annotate that uh with string right here and it's going to be equals to like i don't know one two or something like that three maybe
7:28:58
ahora déjame solo registrar eso en la consola como cadena ya sabes lo que es
now let me just log there to the console like stir you already know what it
7:29:01
nos dará pero ahora déjame solo ejecutarlo de todos modos va a dar
will give us but now let me just run there anyways it's gonna give
7:29:04
nos como arreglos de cadenas como uno dos y tres
us like arrays of strings like one two and three
7:29:07
aquí así que sí ese es el primer sabor
right here so yeah that's the first flavor
7:29:10
ahora déjame solo uh comentar o sabes déjame solo eliminar eso este
now let me just uh comment or you know let me just delete that this
7:29:13
código aquí o, ya sabes, déjame dejarlos aquí y hablemos sobre el segundo sabor de crear un array, así que antes de entrar en el segundo sabor, voy a
code right here or you know let me just leave them right here and let's talk about the second flavor uh of creating an array so before i get into the second flavor uh i'm gonna just
7:29:25
mostrarte algo aquí, ya sabes, primero que nada déjame crear un array vacío, así que items y va a ser igual a string y no vamos a proporcionar nada aquí
show you something right here you know first of all let me just create an empty array so items and it's going to be equal to string and we are not going to be providing anything right here
7:29:35
supongamos que quieres agregar un elemento a este array, así que voy a escribir algo como
let's suppose if you want to push item to this array so i'm going to just write like
7:29:38
items.push, ya sabes lo que hará push, push
items.push you already know what push will do push will
7:29:41
simplemente insertará un elemento al final de este array, así que
just insert an element at the end of this array so
7:29:44
voy a proporcionar algo como, no sé, teclado o algo así
i'm going to just provide like i don't know keyboard or something like
7:29:47
eso y ahora si registro estos items en la consola, ¿qué crees que será el resultado si guardo este archivo y empujo ese elemento, ejecuto ese archivo aquí?
that and now if i log these items to the console what do you think will be the result if i save this file and push that push that item, run that file right here.
7:29:57
Así que nos va a dar el teclado aquí, que está totalmente
So it's gonna give us the keyboard right here which is totally
7:30:00
funcionando bien, pero si simplemente duplico eso y si simplemente pongo, no sé, 12 o algo así y ahora si ejecuto mi código, obviamente nos dará este error aquí
working a-ok but if i just duplicate that and if i just put like i don't know 12 or something like that and now if i just run my code it's gonna obviously gives us this error right here
7:30:12
dirá que, vamos, el argumento de tipo número no es asignable al perímetro de tipo
it's gonna say that um come on argument of type number is not assignable to the perimeter of type
7:30:20
string aquí, así que nos va a dar un error, así que typescript
string right here so it's going to give us an error so typescript
7:30:23
es extremadamente estricto y ya sabe cada
is supremely strict and it already knows every
7:30:26
cosa aquí, está bien, así que ya
single thing right here okay so it already
7:30:29
conoce los tipos, por eso se llama typescript
knows the types that's why it is called the typescript
7:30:33
baby, bienvenido a las palabras de typescript, así que no puedes
baby welcome to the typescript words so you cannot
7:30:36
hacer esas locuras que solías hacer en el
do that crazy stuff which you used to do in the
7:30:39
javascript regular, está bien, así que eso es y lo que quiero hacer es, ya sabes, déjame darte un ejemplo más de nuestros números porque sé que algunas personas dirán que
regular javascript okay so that's that and what i want to do is then you know let me just give you one more example of our numbers because i know some people will say like
7:30:48
hosan, ¿funcionará para los números también o
hosan will it work for the numbers as well or
7:30:51
¿funcionará para el array y algo así? Sí, funcionará
will it work for the array and something like that yeah it will
7:30:54
obviamente funcionará, disculpa
obviously work excuse
7:30:58
bien, así que ahora déjame escribir un número que
me all righty so now let me just write a number that
7:31:01
era una voz horrible, por cierto, y va a ser igual a este array
was a horrible voice by the way and it's going to be equals to this array
7:31:04
aquí y voy a escribir un número de lista y déjame
right here and i'm going to just write a number of list and let
7:31:07
simplemente agregar como 20, obviamente funcionará, ahora déjame
me just push like 20 it's going to obviously work now let
7:31:10
simplemente escribir el número de listas, guardar este archivo y venir
me just write number of lists save this file and come
7:31:15
en hosan no tenemos mucho tiempo y
on hosan we don't have a lot of time and we
7:31:18
ahora estamos obteniendo 20 eso es genial pero supongamos que si solo
are now getting 20 that's cool but let's suppose if i just
7:31:21
duplico eso y trato de proporcionar la verdad aquí y
duplicate that and try to provide true right here and
7:31:24
estoy proporcionando la positividad pero ahora estamos obteniendo la
i'm providing the positivity but we are now getting the
7:31:27
negatividad aquí el argumento de tipo booleano es
negativity right here argument of type boolean is
7:31:30
no asignable al perímetro de número genial está bien
not assignable to the perimeter of number cool okay
7:31:33
así que nos va a dar ese error déjame mostrarte ahí y ahí vamos
so it's going to give us that error let me just show you there and there we go
7:31:37
tienes tu propio error favorito que es el argumento
you got your own favorite error which is argument
7:31:40
es bla bla bla así que sí, eso está ahí ahora déjame mostrarte la alternativa
is blah blah blah so yeah that's there now let me just show you the alternative
7:31:43
sintaxis de crear un arreglo en typescript que
syntax of creating an array in typescript which
7:31:46
no está obsoleta aún pero voy
is not deprecated yet but i'm going
7:31:50
a mostrártelo de todos modos si quieres crear un arreglo usando
to show it to you anyways if you want to create an array by using
7:31:53
no sé ni cómo llamar a esta sintaxis pero voy a
the i don't even know what to call this syntax but i'm going to
7:31:56
simplemente llamarlo como una especie de sintaxis html así que
just call it like html kind of syntax so
7:31:59
voy a escribir item o items y va a ser igual así que
i'm going to just write item or items and it's going to be equal so
7:32:02
primero que nada tenemos que escribir este arreglo y dentro de él estamos
first of all we have to write this array and inside there we are
7:32:05
escribiendo o anotando como string en este caso y
going to be writing or annotation like string in this case and
7:32:08
ahora va a ser igual a este arreglo aquí
now it's going to be equals to this array right here
7:32:11
así que supongamos que si solo no sé dejemos
so let's suppose if i just i don't know let
7:32:15
mejor solo registrar ahí en la consola oh estamos obteniendo un error
me just log there to the console oh we are getting an error
7:32:18
por qué es eso oh eso es porque estamos proporcionando el igual a
why is that oh that's because we're providing the equal to
7:32:21
signo aquí tenemos que anotar ahí y ahora si
sign right here we have to annotate there and now if
7:32:24
simplemente copio estos items los pongo aquí no nos va a dar nada porque esto está totalmente vacío está bien así que ahora déjame ejecutar ahí no nos va a dar nada nos va a dar el arreglo vacío
i just copy these items put it right here it's not going to give us anything because this is totally empty okay so now let me just run there it's not going to give us anything it's going to give us the empty array
7:32:36
porque no almacenamos nada dentro de ahí si quieres crear
because we did not store anything inside there if you want to create
7:32:39
uno para los números también así que solo puedes poner un números y
one for the numbers as well so you can just put a numbers and
7:32:42
ahora déjame solo venderlos y déjame poner como
now let me just sell them and let me just put like
7:32:46
no sé uno dos o vamos cuatro o
i don't know one two or come on four or
7:32:49
algo así déjame solo venderlos y ejecutar mi archivo
something like that let me just sell them and run my file
7:32:52
así que aquí puedes ver que ahora estamos obteniendo el arreglo de números pero supongamos que intento poner algo como una cadena y también el booleano y también déjame poner el objeto o algo así
so here you can see we're now getting the numbers array but let's suppose if i try to put something like string and also the boolean and also let me put the object or something like that
7:33:04
y obviamente nos dará un error si paso el mouse sobre
and it's going to obviously gives us an error if I have my mouse over to
7:33:07
eso así que el tipo objeto no es asignable al tipo número
it so type object is not assignable to the type number
7:33:10
aquí está bien así que este es el segundo sabor
right here okay so this one is the second flavor
7:33:14
de crear arreglos en TypeScript así que ahora hablemos de
of creating an arrays in TypeScript so now let's talk about
7:33:17
arreglos multidimensionales o también puedes llamarlo matriz
a multi-dimensional arrays or you can also call it matrix
7:33:20
o también puedes llamarlo arreglos anidados si
or you can also call it the nested arrays if
7:33:23
lo deseas así que por el bien de esta lección lo llamaré un arreglo multidimensional y puedes llamarlo como quieras. Entonces, ¿qué demonios es un arreglo multidimensional y por qué deberías preocuparte por eso?
you wanted to so for the sake of this lecture I'm going to call it a multi-dimensional array and you can call it whatever you want to call it So what on earth is a multi-dimensional arrays and why you should care about that?
7:33:32
Así que un arreglo multidimensional es un arreglo que contiene otros arreglos como sus elementos.
So a multi-dimensional array is an array that contains other arrays as its elements.
7:33:39
Así que un arreglo multidimensional se puede definir usando la misma notación que los arreglos unidimensionales, pero con corchetes anidados, cariño.
So a multi-dimensional array can be defined using the same notation as one-dimensional arrays, but with nested square brackets, baby.
7:33:47
Así que, ¿cómo se verá eso? Así es como se verá. Así que aquí puedes ver, si quieres anotar eso, solo vamos a proporcionar un número, un corchete y también otro corchete también.
So how that's going to look like? This is how it's going to look like. So here you can see, if you want to annotate that, so we are going to be just providing a number, one bracket, and also another bracket as well.
7:33:57
y dentro de ahí vamos a crear nuestro arreglo anidado o
and inside there we are going to be creating our nested array or
7:34:00
arreglo multidimensional aquí así que ahora déjame
multi-dimensional array right here so now let
7:34:03
escribir algo de código para eso y luego sabrás de qué estoy hablando así que ahora
me just write some code for that and then you'll get to know what i'm talking about so now
7:34:06
déjame solo eliminar eso y voy a seguir adelante y crear un
let me just remove that and i'm going to just go ahead and create a
7:34:09
dado único como un arreglo unidimensional y voy a crear un número y anotarlo como un número aquí, vamos, debería anotarlo, siempre olvido eso y ahora déjame escribir como uno dos tres
single die like a single dimensional array and i'm going to just create a number and annotate that as a number right here come on i should annotate that i always forget that and now let me just write like one two three
7:34:21
cuatro cinco o algo así, ahora déjame crear un arreglo bidimensional
four five or something like that now let me just create a two-dimensional
7:34:25
o arreglo multidimensional así que voy a escribir const
or multi-dimensional array so i'm going to just write const
7:34:28
y mult uh multi-di
and mult uh multi-di
7:34:31
arreglo multidimensional y va a ser igual a número y
multi-dimensional array and it's going to be equals to number and
7:34:35
solo proporcionemos dos pares de corchetes aquí y va a ser igual
let's just provide two pair of brackets right here and it's going to be equals
7:34:38
a como arreglos y puedes proporcionar un interno y proporcionarte un arreglo anidado como ahí, pero en mi caso solo voy a proporcionar un arreglo más aquí como uno dos y tres, vamos
to like arrays and you can provide an inner and provide you a nested array like there but in my case i'm going to just provide one more array right here like one two and three come on
7:34:48
cuatro y cinco como este y ahora déjame crear uno para
four and five like this one and now let me just create one for
7:34:51
el arreglo de triple dimensión así que triple y
the triple dimension array so triple and
7:34:56
va a ser igual a número y solo proporcionemos tres pares de
it's going to be equals to number and let's just provide three pairs of
7:34:59
corchetes aquí sé que ustedes no irán tan lejos
brackets right here i know you guys won't go that much
7:35:02
loco pero voy a mostrarles la sintaxis de todos modos así que
crazy but i'm going to just show you the syntax anyways so
7:35:05
tenemos un arreglo y dentro del arreglo tenemos otro arreglo
we have array then inside the array we have yet another array
7:35:09
y ahora dentro de este arreglo anidado tenemos otro
and now inside this nested array we have yet another
7:35:12
arreglo anidado aquí está bien así que solo proporcionemos uno dos
nested array right here okay so let's just provide one two
7:35:15
tres cuatro cinco si vienen de las cosas de álgebra lineal así que ya conocen toda esa sintaxis eh de todos modos ustedes
three four five if you are coming from the linear algebra stuff so you already know all of that syntax uh anyways you
7:35:24
ni siquiera tienen que saber álgebra lineal en matemáticas así que
don't even have to know a linear algebra in mathematics so
7:35:27
ahora déjame escribir un registro en consola de un solo dado dejemos
now let me just write a console log of single die let's
7:35:30
solo duplicar eso tres veces y dado múltiple y nosotros
just duplicate that three times and multi die and we
7:35:33
también tenemos para el triple vamos no esto
also have for the triple come on not this
7:35:36
uno uh dado triple aquí y ahora déjame guardar eso y
one uh triple die right here and now let me just save that and
7:35:40
vamos a ejecutar eso va a darnos primero el arreglo de una dimensión luego nos va a dar el doble diamante o multidimensional lo que quieras llamar allí y finalmente va a dar
let's just run that baby it's going to give us first of all the single dimension array then it's going to give us the double diamond or multi dimension whatever you want to call there and finally it's going to give
7:35:49
nos el triple de dimensión o lo que quieras llamar eso.
us the triple dimension or whatever you want to call that.
7:35:53
Así que sí, eso fue todo sobre los arreglos multidimensionales en TypeScript. Así que ahora hablemos sobre objetos en TypeScript.
So yeah that was it about for the multi-dimensional arrays in TypeScript. So now let's talk about objects in TypeScript.
7:36:00
Así que un objeto en TypeScript es un tipo de dato estructurado que representa una colección de propiedades cada una con clave y valores asociados.
So an object in TypeScript is a structured data type that represents a collection of properties each with key and associated values.
7:36:07
Las propiedades del objeto pueden tener un tipo específico y el objeto en sí puede ser anotado con un tipo a menudo definido usando interfaces o alias de tipo.
The properties of object can have a specific type and the object itself can be annotated with a type often defined using an interfaces or type aliases.
7:36:16
Ambos no hemos aprendido aún como
Both we did not learn yet like
7:36:19
no aprendimos las interfaces y también los alias de tipo no
we didn't learn the interfaces and also the type aliases not
7:36:22
ahora mismo pero vamos a aprender allí en unos segundos
right now but we are going to be learning there in a few seconds
7:36:26
así que TypeScript usa algo llamado un i estructural
so typescript uses something called a structural i
7:36:29
puedo decir esto para el tipado estructural significando
can say this for structural typing meaning
7:36:32
la forma de un objeto y la estructura o propiedades es
the shape of an object and structure or properties is
7:36:36
lo que importa para la compatibilidad de tipos así
what matters for the type compatibility so
7:36:39
cómo se verá la sintaxis del objeto así es como se verá la sintaxis del objeto y sé que muchas personas dirán como oh mi
how the syntax of object will look like this is how the syntax of object will look like and i know a lot of people will say like oh my
7:36:46
dios hosan qué demonios es eso ni siquiera sé qué demonios está pasando pero
god hosan what the hell is that i don't even know what the hell is going on but
7:36:49
primero que nada, como solo crear una variable aquí mismo y
first of all like just creating a variable right here and
7:36:52
aquí tenemos que especificar la anotación y también
here we have to specify the annotation and also
7:36:55
tiempos específicos para la anotación y va a ser igual a
specific times for the annotation and it's going to be equals to
7:36:58
la propiedad y el valor, así que cómo se verá eso
the property and value so how that's going to look like
7:37:02
así es como se verá aquí mismo, así que primero que nada estamos
this is how it's going to look like right here so first of all we
7:37:05
solo creando una variable aquí mismo y luego estamos proporcionando
are just creating uh or variable right here and then we are providing
7:37:08
una propiedad y también una anotación para esa propiedad
a property and also annotation for that property
7:37:11
aquí mismo y luego estamos proporcionando el signo igual
right here and then we are providing the equal to sign
7:37:15
y aquí dentro estamos proporcionando nuestra primera propiedad como
and here inside there we are providing our first property like
7:37:18
lo que vamos a estar devolviendo o como qué tipo de datos o
what we are going to be returning or like which kind of data or
7:37:21
qué tipo de datos vamos a estar almacenando dentro de esto
which type of data we are going to be storing inside this
7:37:24
persona aquí mismo, así que en este caso solo estamos devolviendo como
person right here okay so in this case we are just returning like
7:37:27
nombre primero cadena nombre de familia cadena y también la edad así que
first name string last name string and also the edge so
7:37:30
tienes que proporcionar esas propiedades y sus valores
you have to provide that properties and its values
7:37:33
aquí dentro de este objeto persona aquí mismo, así que ahora déjame darte un ejemplo rápido de eso oh, sabes qué, también quiero mostrarte este aquí mismo Oh, sabes, digamos que.
right here inside this person object right here so now let me just give you a quick example of that oh you know what uh i also want to show you the this one right here Oh, you know, let's just say that.
7:37:44
Está bien, así que también puedes proporcionar un valor de retorno para la función.
Okay, so you can also provide a return value for the function.
7:37:47
Como, supongamos que para alguna función, como, si ya conoces la función de fábrica de mi curso de JavaScript, quiero decir, como, no tienes que saber eso.
Like, let's suppose for some function, like, if you already know the factory function from my JavaScript course, I mean, like, you don't have to know that.
7:37:54
Pero si ya sabes qué es una función de fábrica de mi curso, entonces ya sabes qué está pasando aquí.
But if you already know what a factory function is from my course, so you already know what's going on right here.
7:38:00
Pero ahora déjame explicarlo para aquellos que no saben qué está pasando. Así que aquí puedes ver que estamos creando una función, una función regular aquí mismo.
But now let me just explain it for those who don't know what's going on. So here you can see we are just creating a function, a regular function right here.
7:38:07
Y quiero que no prestes atención a este tipo aquí, no por ahora.
And I want you to do not pay attention to this type right here, not for now.
7:38:11
así que solo estamos creando una función aquí dentro de esta función estamos
so we are just creating a function right here inside this function we are
7:38:14
solo devolviendo un objeto así que dentro de este objeto tenemos
just returning an object so inside this object we have
7:38:17
un nombre alex edad 19 y ubicación unida
a name alex age 19 and location united
7:38:20
estado de américa así que ahora si quieres devolver este objeto de esto
state of america so now if you want to return this object from this
7:38:24
función específica justo aquí así que también podemos proporcionar esto
specific function right here so we can also provide this
7:38:27
anotación uh o lo que quieras llamar eso
annotation uh or whatever you want to call that
7:38:30
para el valor de retorno justo aquí está bien así que esto se conoce como una función de fábrica si ustedes lo saben genial si no lo saben también está bien
for the return value right here okay so this is known as a factory function if you guys know it cool if you don't know it cool too
7:38:37
está bien así que sí ahora déjame escribir algo de código y
okay so yeah now let me just write some code and
7:38:40
entonces vas a saber de qué estoy hablando está bien así que voy a eliminar
then you will get to know what i'm talking about okay so i'm going to just remove
7:38:44
eso y primero que todo define una persona
that and first of all define a person
7:38:47
objeto o sabes vamos a eliminar eso déjame hacer
object or you know let's just remove that let me just do
7:38:50
eso de inmediato así que la persona va a ser igual a uh esta anotación
that right away so person is going to be equals to uh this annotation
7:38:54
primero que todo así que qué vamos a almacenar dentro de este objeto vamos a almacenar el primer nombre justo aquí y ahora simplemente proporcionemos uh el tipo de cadena justo aquí y
first of all so what are we going to be storing inside this object we are going to be storing the first name right here and now let's just provide uh the type of string right here and
7:39:03
no vamos a proporcionar una coma en este caso vamos a
we are not going to be providing a comma in this case we are
7:39:06
proporcionar uh ni siquiera sé cómo llamar a esto un punto y coma
going to be providing uh i don't even know what to call this one semicolon
7:39:09
ahí vamos y apellido y voy a
there we go and last name and i'm going
7:39:12
también proporcionar una cadena y proporcionar un colon y también el
to also provide a string and provide a column and also the
7:39:15
límite y el límite se establecerá en número déjame volver y
edge and the edge will be set to number let me just go back and
7:39:19
entonces vamos a proporcionar el signo igual y dentro de ahí
then we are going to be providing the equal to sign and inside there
7:39:22
vamos a estar escribiendo nuestros corchetes justo aquí así que aquí
we are going to be just writing our brackets right here so here
7:39:25
tenemos que especificar estos valores justo aquí como para el primer nombre se establecerá en john el apellido se establecerá en do y el límite se establecerá en 30 correcto
we have to specify these values right here like for the first name it will be set to john last name will be set to do and edge will be set to 30 right
7:39:32
aquí está bien así que ahora si quiero acceder a eso así que ahora déjame escribir
here okay so now if i want to access that so now let me just write
7:39:35
console.log uh no sé el nombre será ahora
console.log uh i don't know name will be now
7:39:38
proveniente de person.first name y también podemos
coming from the person.first name and we can also
7:39:42
obtener uh cómo lo llamamos un person.last name
get uh what do we call it a person.last name
7:39:45
y también podemos obtener el límite justo aquí límite
and we can also get the edge right here edge
7:39:49
ahí vamos person.edge y ahora déjame guardar eso y ejecutar eso justo aquí así que qué estamos obteniendo ahora estamos obteniendo el nombre john do y también estamos obteniendo el límite que se establecerá
there we go person.edge and now let me just save that and run that right here so what are we getting we are now getting the name john do and we are also getting the edge which will be set
7:40:00
30 justo aquí, pero ahora supongamos que solo lo elimino
30 right here but now let's suppose if i just remove that
7:40:03
borde justo aquí, así que ahora si tengo mi ratón sobre él
edge right here so now if i have my mouse over to it so
7:40:06
nos va a dar este error justo aquí, va a decir que la propiedad borde
it's going to give us this error right here it's going to say like property edge
7:40:09
falta en el tipo de esta definición que ya estamos
is missing in the type this definition which we are already
7:40:13
proporcionando justo aquí, pero requerido en el tipo um
providing right here but required in the type um
7:40:16
anotación justo aquí, así que tienes que especificar eso
annotation right here so you have to specify that
7:40:20
borde justo aquí que lo eliminamos dentro
edge right here which we which we remove it inside
7:40:23
esta definición justo aquí, está bien, así que tienes que especificar
this definition right here okay so you have to specify
7:40:26
su borde, de lo contrario, te va a lanzar ese error y ahora déjame
their edge otherwise going going to throw you that error and now let me just
7:40:29
mostrarte cómo se verá este error, así que ahora déjame ejecutar eso y
show you how this error is going to look like so now let me just run that and
7:40:32
te dará el mismo mensaje de error justo aquí como
it will give you that same error message right here as
7:40:36
bueno, si especificas algún tipo de firma justo aquí, entonces
well if you specify some sort of a signature right here then
7:40:39
tienes que proporcionar todos sus valores para esas firmas, así que
you have to provide all of their values for that signatures so
7:40:42
ahora déjame escribir 10 y ahí vamos, así que eso fue
now let me just write 10 and there we go so that was
7:40:45
para las notaciones literales de objeto y ahora
for the object literal notations and now
7:40:48
hablemos de los parámetros de la función también, así que ahora déjame crear una función, le voy a dar un nombre como usuario padre o algo así y no va a
let's talk about for the function perimeters as well so now let me just create a function i'm going to give a name of like a parent user or something like that and it's not going to
7:40:57
tomar ningún parámetro ni nada de eso y para el retorno
take any perimeter or anything like that and for the return
7:41:00
valor, lo que quiero hacer es que solo voy a verter este mismo
value what i want to do is that i'm going to just pour this same
7:41:03
sabes, no quiero copiar eso, déjame
you know i don't want to copy that let
7:41:06
escribir eso porque sé que algunos de ustedes dirán que entonces solo copias
me just type that because i know some of you will say like then you just copy
7:41:10
y pega el código, así que sí, eso es ahora
and paste the code so yeah that's now
7:41:13
déjame escribir borde y va a estar configurado como número, estamos obteniendo algún tipo
let me just write edge and it's going to be set to number we are getting some sort
7:41:16
de error, pero no sé por qué, solo pongamos un número y ahí vamos, y olvidé algo sobre qué pasa con una función cuyo
of error but i don't know why let's just put a number and there we go and i forgot something on what's up a function whose
7:41:24
tipos declarados no son ni indefinidos ni void
declared types is neither undefined void
7:41:27
ni nada debe ser devuelto, vamos, demonios
nor any must be returned come the hell on
7:41:30
hombre, solo estamos devolviendo este tipo justo aquí y allí
man we are just returning this type right here and there
7:41:33
vamos, oh, ¿qué tal el tipo?
we go oh what's up type
7:41:36
el objeto está faltando las siguientes propiedades, solo dame un respiro
object is missing the following properties just give me a break
7:41:40
hermano, ni siquiera termino de escribir y ya estás lanzando
brother i don't even finish typing and you are throwing
7:41:43
algunos errores aleatorios y ahora déjame escribir el nombre
me some sort of a random errors and now let me just write name
7:41:46
de hosane y también voy a proporcionar la edad
of hosane and i'm gonna also provide the age
7:41:49
de 20 y también la ubicación será
of 20 and also the location will be
7:41:52
sí, sí, oh hosan chino
yeah yeah oh chinese hosan
7:41:55
voy a proporcionar china justo aquí, chino
i'm gonna just provide china right here chinese
7:41:58
hosan y ahora déjame registrarme allí en el núcleo tú
hosan and now let me just log there to the core you
7:42:01
sabes que no quiero registrarme allí, solo escribamos cons res y
know i don't want to log there let's just write cons res and
7:42:05
imprimir usuario y no vamos a especificar nada
print user and we're not going to be specifying anything
7:42:08
sobre eso, pero voy a escribir res, solo guardemos eso, bebé
to it but i'm going to just write res let's just save that baby
7:42:11
y ejecuta eso y vamos, ejecuta
and run that and come the hell on run
7:42:15
eso una vez más y ahora estamos obteniendo el nombre de hosain, edad de 20, ubicación de china y ahí vamos, bebé
that once again and we are now getting the name of hosain age of 20 location of china and there we go baby
7:42:21
así que sí, así es como vamos a proporcionar una firma para
so yeah this is how we are going to be providing a signature for
7:42:25
el valor de retorno de una función y así es como vamos a anotar, uh, nuestro objeto justo aquí, está bien, y estoy bastante seguro
the return value of a function and this is how we are going to be annotating uh or object right here okay and i'm pretty much sure
7:42:33
de que no olvidé nada, así que ahora vamos a
that i did not forget anything so now let's get
7:42:36
nuestros alias de tipo, así que ahora hablemos sobre un alias de tipo
into our type aliases so now let's talk about a type aliases
7:42:40
en typescript, así que un alias de tipo es una forma
in typescript so a type alias is a way
7:42:43
de crear un nuevo nombre para un tipo existente y te permite
to create a new name for existing type and it allows you
7:42:46
definir un tipo personalizado que se refiere a otro tipo
to define a custom type that refers to another type
7:42:49
y darle un nombre más significativo o descriptivo
and give it a more meaningful or descriptive name
7:42:52
y un alias de tipo se define usando una palabra clave reservada
and a type aliases are defined using a type reserved
7:42:55
seguida del nombre del alias y igual a
keyword followed by the name of the alias and equal to
7:42:58
signo y el tipo al que se refiere, así es como se verá la sintaxis y así es como vamos a escribir eso en un ejemplo del mundo real, así es como se verá
sign and the type it refers to so this is how the syntax will look like and how we are going to be writing that in a real world example this is how it's going to be looking
7:43:07
así que aquí puedes ver, primero que nada, estamos proporcionando el tipo
like so here you can see first of all we are providing the type
7:43:10
palabra clave reservada y este tipo de palabra clave reservada es
reserved keyword and this type reserved keyword is
7:43:13
una palabra clave especial, como tienes que especificar la palabra clave de tipo
a special keyword like you have to specify the type keyword
7:43:16
siempre que estés creando un tipo personalizado y luego estamos dando
whenever you're creating a custom type and then we are giving
7:43:20
el nombre de como persona, puedes dar banana, puedes dar cualquier nombre
the name of like person you can give banana you can give any name
7:43:23
que desees y va a ser igual a este objeto y dentro
you want and it's going to be equals to this object and inside
7:43:26
ahí podemos especificar nuestras propiedades y tipos específicos para sus propiedades aquí mismo, así que no tenemos que no
there we can specify our properties and a specific types for their properties right here so like we don't have to no
7:43:32
hacer esto una y otra vez, así que en este caso solo estamos
longer do this stuff again and again so in this case we are just
7:43:35
proporcionando un nombre y ahora se establecerá en cadena y luego
providing a name and it will be now set to string and then
7:43:38
estamos creando un borde y estamos proporcionando un número para luego también para la ubicación
we are creating an edge and we are providing a number for then also for location
7:43:41
no tenemos que hacer eso una y otra vez, solo podemos crear
we don't have to do that again and again we can just create
7:43:44
un tipo de persona o un tipo personalizado, lo que quieras llamar
a person type or a custom type whatever you want to call
7:43:48
eso y luego podremos usarlo aquí mismo y aquí puedes ver que
that and then we will be able to use it right here and here you can see we
7:43:51
también podemos usar eso para el objeto en sí e incluso en la definición
can also use that for the object itself and even in the definition
7:43:54
ya te dije que puedes crear interfaces o alias de tipo, así que ahora que aprendemos sobre un alias de tipo, así que vamos
i already told you that you can create interfaces or type aliases so now that we learn about a type aliases so we are going
7:44:02
estamos aprendiendo sobre interfaces en unos segundos, que son más
we're learning about interfaces in a few seconds which are more
7:44:05
poderosas que los alias de tipo, pero aún no estamos allí
powerful than type aliases but we are not there yet
7:44:08
bien, así que ahora vamos a entrar en los alias de tipo
okay so now let's get into the type aliases
7:44:11
código, así que ahora déjame eliminar todo ese código aquí mismo y
code so now let me just remove all of that code right here and
7:44:14
quiero definir un tipo personalizado, así que solo voy a dar un nombre como
i want to define a custom type so i'm going to just give a name of like
7:44:17
usuario en este caso y dentro de este usuario vamos a proporcionar un nombre de cadena, también voy a proporcionar la edad de número y también voy a proporcionar una ubicación de cadena
user in this case and inside this user we are going to be providing a name of string i'm going to also provide the edge of number and i'm going to also provide a location of string as well
7:44:28
puedes proporcionar un arreglo como ubicación, pero sí, eh
you can provide array as a location but yeah uh
7:44:31
de todos modos, así que ahora déjame crear algún tipo de función const imprimir
anyway so now let me just create some sort of a function const print
7:44:34
información del usuario o algo así y va a tomar el usuario
user info or something like that and it's going to take the user
7:44:38
y aquí vamos a estar proporcionando o tipo
and here we are going to be providing or type
7:44:41
alias o puedes establecer un tipo personalizado, lo que quieras
alias or you can set a custom type whatever you want to
7:44:44
llama a eso, así que ahora estamos proporcionando todos sus tipos como un perímetro aquí, está bien, así que va a ser igual a esta función y dentro de allí, si solo escribo return y si solo escribo name
call that so we are now providing like all of their types as a perimeter right here okay so it's going to be equals to this function and inside there if i just write return and if i just write name
7:44:55
y si solo escribo como user.name en este caso, si
and if I just write like user.name in this case, if
7:44:59
coloco el mouse sobre allí, así que ¿qué estamos obteniendo? Estamos
I hover my mouse over to there so what are we getting we are
7:45:02
obteniendo el usuario y anotado con el tipo de usuario
getting the user and annotated with the user type
7:45:05
aquí, está bien, así que por eso ahora podemos obtener esto con éxito
right here okay so that's why we are now successfully able to get this
7:45:08
nombre de este usuario aquí y también podemos proporcionar
name from this user right here and we can also provide
7:45:11
lo que llamamos el borde o, ya sabes, solo envolvamos
the what do we call it the edge or you know let's just wrap
7:45:14
allí con algún tipo de paréntesis para que obtengamos una salida increíble, también voy a proporcionar el borde y dentro de allí
there with some sort of parentheses so that we get an amazing output i'm going to also provide the edge and inside there
7:45:20
vamos a estar usando el usuario punto borde y también dejemos
we are going to be using the user dot edge and also let
7:45:24
que escriba para la ubicación también, así que, eh
me just write for the location as well so uh
7:45:27
simplemente escribamos, vamos, bien, entonces puedes hacer eso, dejemos
let's just write come on well then you can do that let
7:45:30
que escriba user punto location y ahí vamos, está bien, así que ahora finalmente
me just write user dot location and there we go okay so now finally
7:45:34
volvamos, oh Dios mío, ¿qué demonios estoy haciendo?
let's just go back oh my god what the hell am i doing
7:45:37
está bien, así que ahora finalmente volvamos y creemos un resultado y el resultado va a ser igual a imprimir info o imprimir información del usuario aquí y dentro de allí vamos a estar proporcionando el nombre
okay so now finally let's just go back and create a result and result is going to be equals to like print info or print user info right here and inside there we are going to be providing the name
7:45:48
y el nombre se establecerá en alex y también voy a especificar el
and the name will be set to alex and i'm going to also specify the
7:45:51
borde y el borde ahora se establecerá en 20
edge and the edge will be now set to 20
7:45:54
o algo así y déjame también proporcionar, no sé, ubicación o algo, vamos, me gusta esa ubicación y la ubicación va a ser igual a estados unidos de américa
or something like that and let me just also provide i don't know location or something come on i like that location and location is going to be equals to united state of america
7:46:05
y la cadena no es asignable, oh, eso es porque estoy proporcionando una cadena aquí
and string is not assignable oh that's because i'm providing a string right here
7:46:12
no debería estar haciendo eso y ahora déjame registrar eso en la consola y ahí vamos
i shouldn't be doing that and now let me just log that rest to the console and there we go
7:46:17
voy a guardar este archivo y ejecutar eso y ahora estamos obteniendo
i'm going to sell this file and run that and we are now getting
7:46:20
el nombre de alex, también estamos obteniendo la edad de 20
the name of alex we are also getting the age of 20
7:46:23
y también estamos obteniendo la ubicación de estados unidos y
and we are also getting the location of united state and
7:46:26
sí, así es como vamos a estar definiendo nuestro tipo personalizado
yeah this is how we are going to be defining or custom type
7:46:29
alias y así es como vamos a usarlo dentro de una función, así que
alias and this is how we are going to be using the inside a function so
7:46:33
no estamos limitados a usar estos tipos dentro de funciones, más adelante los vamos a usar para diferentes cosas, pero por ahora quiero que solo tengas en cuenta la sintaxis
we are not just limited to use these types inside a functions later we are going to be using it for a different kind of things but for now i want you to just keep in mind the syntax
7:46:42
de cómo crear un alias de tipo en typescript aquí mismo
of how to create a type aliases in typescript right here
7:46:45
así que no es algo tan difícil de recordar
so it's like not that much difficult thing to remember you
7:46:48
solo tienes que recordar este tipo y el resto es totalmente objeto
just have to remember this type and the rest is totally object
7:46:51
aquí y la convención es hacerlo en mayúsculas
right here and the convention is to make it the uppercase
7:46:55
como la primera letra, deberías hacerla mayúscula, aquí déjame
like the first letter you should make that uppercase right here let
7:46:58
cambiar eso, supongo que te dará un error si solo cambias
me just change that to i guess it's going to give you an error if you just change
7:47:01
eso a minúsculas, no, no te va a dar
that to lowercase nope it's not going to give you
7:47:04
un error, la convención es usar mayúsculas, pero también puedes usar minúsculas, y eso lo acabo de aprender, así que ahora hablemos de
an error the convention is to use the uppercase but you can go with lowercase as well and i just learned that so now let's talk about
7:47:10
propiedades opcionales en typescript, así que puedes hacer que una cierta propiedad sea opcional
optional properties in typescript so you can make a certain property optional
7:47:14
en un tipo de objeto simplemente agregando una pregunta
in an object type by just adding a question
7:47:17
marca después del nombre de la propiedad, por ejemplo, digamos que tienes
mark after the property name for example let's say you have
7:47:20
un tipo de objeto de una persona como nombre, edad y correo electrónico
an object type of one person like name age and email
7:47:23
pero quieres hacer que la propiedad de correo electrónico sea opcional, así que puedes simplemente proporcionar
but you want to make the email property optional so you can just provide
7:47:27
como un signo de interrogación y eso sería totalmente opcional, así que
like question mark and that would be totally optional so
7:47:30
aquí puedes ver en este ejemplo que estamos creando nuestro alias de tipo aquí mismo, así que tenemos una propiedad de nombre, también tenemos el
here you can see in this example we are just creating our type alias right here so we have a name property we also have the
7:47:36
límite y supongamos que quieres hacer que la propiedad de correo electrónico
edge and let's suppose if you want to make the email property
7:47:39
sea opcional, así que para eso solo tenemos que escribir este signo de interrogación y
optional so for that we just have to write this question mark and
7:47:42
va a hacerlo totalmente opcional, así que cómo en el mundo vamos a usar
it's going to make it totally optional so how in the world we are going to be using
7:47:46
eso, así es como vamos a usar eso, así que ahora cuando tú
that this is how we are going to be using that so now when you
7:47:49
creas un objeto del tipo persona, puedes elegir si incluir o no
create an object of type person you can choose whether or
7:47:52
la propiedad de correo electrónico, como que depende totalmente de ti si quieres
not to include the email property like it's totally on you if you want to
7:47:55
proporcionarlo, puedes hacerlo, si no quieres proporcionarlo, no tienes que hacerlo
provide it you can if you don't want to provide it you don't have to
7:47:58
está bien, porque ya lo hicimos opcional aquí dentro de nuestro tipo, así que ahora en este ejemplo el
okay because we already make that optional right here inside or type right here so now in this example the
7:48:05
el objeto interminable no incluye la propiedad de correo electrónico mientras que el
endless object does not include the email property while the
7:48:08
el objeto bomba sí porque la propiedad de correo electrónico está marcada como
bomb object does because the email property is marked as
7:48:11
opcional en la definición del tipo de persona es válido
an optional in the person type definition it is valid
7:48:14
crear un objeto con o sin ella allí
to create an object with or without it there
7:48:17
así que ahora déjame darte un ejemplo rápido de eso y luego sabrás de qué estoy hablando así que ahora déjame eliminar todo ese código de aquí y voy a crear un tipo de usuario y dentro de ahí oh olvidé incluir el signo igual
we go so now let me just give you a quick example of that and then you'll get to know what i'm talking about so now let me just remove all of that code from here and i'm going to just create a type of user and inside there oh i forgot to include the equal to sign
7:48:29
dentro de ahí se nos va a dar el nombre de como algún nombre y así se va a establecer como cadena y
inside there we're going to be given name of like some name and so it's going to be set to string and
7:48:34
también vamos a proporcionar edad y la edad se establecerá como número
we are going to be also providing edge and edge will be set to number
7:48:37
y también voy a proporcionar una ubicación de cadena como
and i'm going to also provide a location of string as
7:48:40
bueno, pero ahora en este caso quiero hacer que esta edad sea totalmente
well but now in this case i want to make this edge totally
7:48:43
opcional así que solo puedo proporcionar un signo de interrogación
optional so i can just provide a question mark
7:48:46
aquí o también puedes decir, uh, propiedad opcional
right here or you can also say uh optional property
7:48:49
lo que quieras llamar eso y ahora está totalmente en
whatever you want to call that and now it's totally on
7:48:53
nosotros si quieres proporcionar, uh, esta edad aquí así que totalmente podemos si no quieres proporcionar esta edad no tenemos que hacerlo así que ahora déjame crear un
us if you want to provide uh this edge right here so we totally can if you don't want to provide this edge we don't have to so now let me just create a
7:49:01
objeto de usuario y el tipo que voy a proporcionar a este usuario
user object and the type i'm going to provide this user
7:49:04
tipo aquí y dentro de ahí vamos a usar como nombre
type right here and inside there we're going to be using like name
7:49:07
y el nombre se establecerá como mi propio nombre y también voy a especificar
and the name will be set to my own name and i'm going to also specify
7:49:11
20 aquí y también voy a especificar la ubicación
20 right here and i'm going to also specify the location
7:49:14
la ubicación de china sí ahí
the location of china yeah there
7:49:17
vamos y ahora déjame ir y registrar eso en la consola y
we go and now let me just go ahead and log there to the console and
7:49:20
por cierto, realmente amo china, realmente quiero ir a china alguna vez, pero no tengo suficiente dinero para visitar algún otro país así que sí, eso es
by the way i really love china i really want to go to china sometime but i don't have enough money to visit to some other country so yeah that's
7:49:29
eso de todos modos así que ahora déjame crear un nombre aquí
that anyway so now let me just create a name right here
7:49:32
y voy a escribir como nombre de usuario y
and i'm going to just write like user name and
7:49:35
voy a escribir edad y aquí voy a escribir como
i'm going to just write edge and here i'm going to just write like
7:49:38
usuario punto edad y también para la ubicación estoy
user dot edge and also for the location i'm
7:49:42
simplemente renderizando como usuario punto ubicación aquí, está bien, así que
going to just render like user dot location right here okay so
7:49:45
Voy a volver y ahora déjame mostrar eso y ejecutar mi código para que puedas ver el resultado en unos segundos si lo vuelvo a ejecutar una vez más, así que aquí puedes ver que el nombre está configurado como Hosain, el borde está configurado en 20 y la ubicación está configurada en China.
i'm going to go back and now let me just show that and run my code so you will get to see the result in a few second if i rerun there once again so here you can see name is set to hosain edge is set to 20 any location is set to China.
7:49:57
Pero ahora supongamos que quiero eliminar este borde aquí.
But now let's suppose if I want to remove this edge right here
7:50:00
Si simplemente elimino eso, guardo mi archivo y aquí puedes.
if i just remove that save my file and here you can
7:50:03
ver dentro de nuestro código, no estamos obteniendo ningún error, pero
see inside our coder we are not getting any errors but
7:50:06
si simplemente lo vuelvo a ejecutar, aquí puedes ver que ni siquiera estamos obteniendo
if i just rerun that and here you can see we are not even getting
7:50:09
ningún error aquí, en su lugar estamos obteniendo indefinido como si estuviera requiriendo alguna propiedad, quiero decir que estamos proporcionando alguna propiedad aquí, pero que actualmente está indefinida, como no la definimos.
any errors right here instead we are getting undefined like is requiring some property i mean like we are providing some property right here but which is currently undefined like we did not define that
7:50:21
Así que por eso ahora estamos obteniendo indefinido en lugar de algún tipo de error, está bien.
so that's why we are now getting undefined rather than some sort of an error okay
7:50:24
Así que supongamos que simplemente elimino este signo de interrogación de
so let's suppose if i just remove this question mark from
7:50:27
aquí, así que aquí puedes ver instantáneamente que estamos obteniendo este error si
here so here you can see instantly we are getting this error if
7:50:31
coloco el mouse sobre él, así que la propiedad borde está
i hold my mouse over to it so the property edge is
7:50:34
faltando en la definición de este tipo, pero requerida dentro
missing in the type this definition but required inside
7:50:37
del usuario, aquí puedes ver que está requiriendo que nosotros
the user here you can see it is requiring that we
7:50:40
no estamos proporcionando eso, así que por eso ahora nos está lanzando este error, pero si simplemente lo hago opcional no tenemos que hacer
are not providing that so that's why it is now throwing us this error but if i just make that optional we don't have to do
7:50:46
nada, está bien, así que sí, voy a dejar este código
anything okay so yeah i'm gonna just leave this code
7:50:49
tal como está y eso fue todo sobre las propiedades opcionales
the way it is and that was it about for the optional properties
7:50:52
en TypeScript, así que ya estamos aquí.
in typescript so we are already here
7:50:55
Así que ahora déjame hablarte sobre otra propiedad
so now let me just talk to you about one other property
7:50:58
que se llama la propiedad de solo lectura y no
which is called the read only property and i
7:51:02
hice una diapositiva para ellos porque esto es totalmente
did not make a slide for them because this is totally
7:51:05
simple y fácil, así que sí, por eso no hice una diapositiva para eso, como su nombre sugiere, hará que nuestra propiedad sea de solo lectura, lo que significa que solo podemos leer esto.
simple and easy so yeah that's why i didn't make a slide for that as the name suggests that it will make our property read only which means like we can only read this
7:51:13
pero no podemos cambiar el valor de eso, así que
property but we cannot change the value of that so
7:51:16
aquí puedes ver que hacemos esta propiedad de solo lectura, la estamos configurando
here you can see we make this property read only we are setting that
7:51:20
en China, pero supongamos que tengo como un usuario
to china but let's suppose if i have like a user
7:51:23
punto ubicación y si quieres configurarlo en algo más, está bien.
dot location and if you want to set that to something else right
7:51:26
aquí, así que ya estamos obteniendo este error si paso el mouse sobre
here so we are already getting this error if i hover my mouse over
7:51:30
así que no se puede asignar a la ubicación porque es una propiedad de solo lectura justo aquí, así que solo tienes que tener eso en cuenta. Por otro lado, si quiero cambiar el nombre
to it so cannot assign to the location because it is read only property right here okay so you just have to keep that in mind on the other hand if i want to change the name
7:51:39
así que solo voy a escribir algo como nombre y aquí puedes ver que no estamos obteniendo
so i'm going to just write like name and here you can see we're not getting
7:51:43
ningún error en absoluto, pero hacemos este
any errors whatsoever but we make this one
7:51:46
solo lectura, así que por eso si intentas cambiar
read only so that's why if you try to uh change
7:51:49
el valor de eso, nos dará un error, así que ahora déjame cambiar eso
the value of that so it's going to give us an error so now let me just change that
7:51:52
a ubicación o algo más y si solo ejecuto eso, nos dará ese hermoso error, dirá que no se puede asignar a la ubicación porque es una propiedad de solo lectura, así que solo tienes que tener eso
to location uh or something else and if i just run that it's going to give us that beautiful error it's going to say like cannot assign to the location because it is a read only property so you just have to keep that
7:52:04
también en mente. Así que ahora hablemos sobre tipos de intersección o tipos de intersección en TypeScript.
also in mind. So now let's talk about intersection types or intersection types in type script.
7:52:12
Pero no estoy aquí para hablarte sobre la intersección en inglés. De todos modos, ¿qué demonios son los tipos de intersección y por qué deberías preocuparte por eso?
But I'm not here to tell you about the English intersection. Anyway, so what in the world is intersection types and why you should care about that?
7:52:20
Así que un tipo de intersección es una forma de combinar múltiples tipos en un solo tipo que incluye todas las propiedades y métodos de cada constituyente
So an intersection type is a way to combine multiple types into a single type that includes all the properties and method of each constitute
7:52:27
tipo y el tipo de intersección se denota
type and intersection type is denoted
7:52:30
simplemente con el signo ampersand justo aquí
by just the ampersand sign right here just
7:52:33
el signo ampersand, así que cómo vamos a usar eso
the ampersand sign so how we are going to be using that this
7:52:36
es cómo vamos a usar eso. Primero que nada, vamos a crear
is how we are going to be using that first of all we are going to be creating
7:52:40
dos tipos justo aquí, así que tenemos un tipo de persona dentro
two types right here so we have a person type inside
7:52:43
este tipo de persona tenemos un nombre de cadena el borde del número que
this person type we have a name of string the edge of number we
7:52:46
también tenemos el tipo de empleado y dentro de ahí estamos proporcionando un número y también quiero decir como el id y también el título y luego si quieres
also have the employee type and inside there we are providing a number and also i mean like the id and also the title and then if you want to
7:52:55
combinar o intersectar esta persona y
combine or intersect this person and
7:52:58
también este empleado juntos, así que para eso podemos
also this employee together so for that we can
7:53:01
simplemente crear algún tipo de otro tipo y podemos usar persona
just create some sort of other type and we can use person
7:53:04
y ampersand aquí quiero que lo tengas en cuenta
and ampersand right here i want you to keep that in mind
7:53:07
este ampersand y luego otro tipo aquí y
this ampersand and then another type right here and
7:53:11
entonces puedes usar este tipo combinado justo aquí
then you can use this combined type right in here
7:53:14
así que supongamos que estás creando algún tipo de persona
baby so let's suppose if you are creating some sort of a person
7:53:17
objeto así que aquí puedes ver que tenemos alias y estamos proporcionando este tipo combinado o intersectado justo aquí, así que ahora estamos proporcionando el nombre de alice, la edad de 30, el id de 123 y el título de gerente justo aquí
object so here you can see we have alias and we are providing this combined or intersected type right here so we are now providing the name of alice the edge of 30 the id of 123 and the title of manager right here
7:53:29
así que ahora déjame darte un rápido ejemplo de eso y luego sabrás de qué estoy hablando
so now let me just give you a quick example of that and then you'll get to know what i'm talking about
7:53:32
voy a eliminar todo ese código aquí y voy a
i'm going to delete all of that code right here and i'm going to
7:53:35
simplemente crear dos tipos primero para intersecarse entre sí
just create two type first of all to intersect them with each other
7:53:38
o para combinarlos entre sí combinar es
or to combine them with each other combine is
7:53:41
una mejor palabra así que ahora déjame crear una información de usuario
a better word so now let me just create a user info
7:53:44
va a ser igual a este tipo y vamos a proporcionar el primero oh Dios mío vamos a proporcionar un primero y el primero va a ser igual a cadena
it's going to be equals to uh this type and let's just provide the first oh my god let's just provide a first and the first is going to be equal to string
7:53:52
y también proporcionar una pérdida y la pérdida también se va a establecer en cadena
and also provide a loss and the loss is going to be also set to string
7:53:55
y voy a crear un borde y el borde se establecerá en número
and i'm going to create an edge and the edge will be set to number
7:53:58
aquí ahora déjame también crear los detalles de la cuenta
right here now let me just also create the account details
7:54:02
va a ser igual a este objeto va a tomar el correo electrónico es
it's going to be equals to this object it's going to take the email it's
7:54:06
también va a etiquetar algún tipo de contraseña también ahora déjame volver
going to also tag some sort of a password as well now let me just go
7:54:09
así que aquí puedes ver que tenemos dos tipos aquí pero
back so here you can see we have two types right here but
7:54:12
si quieres combinar ambos tipos en un tipo así que para eso primero vamos a crear una variable o no una variable vamos a crear un tipo separado voy a
if you want to combine both of these types into one type so for that first of all let's just create a variable or not a variable let's just create a separate type i'm going to
7:54:21
darle un nombre como usuario y va a ser igual a la información del usuario
given name of like user and it's going to be equals to the user info
7:54:24
y quiero que solo mantengas esto
and i want you to just keep this
7:54:27
n en tu mente quiero que mantengas
n in your mind i want you to keep
7:54:31
este n en tu mente así que este n
this n in your mind so this n will
7:54:34
combinará ambos tipos aquí así que voy a escribir una información de usuario
combine both of these types right here so i'm going to just write a user
7:54:37
y también los detalles de la cuenta aquí y
info and also the account details right here and
7:54:40
ahora podemos usarlos totalmente así que estos son todos los tipos y ahora los combinamos en solo este tipo de usuario lo que significa que cada vez que usamos este usuario tenemos que especificar el nombre, apellido, edad
now we can totally use them so these are all types and now we combine them into only this user type which means like whenever we use this user we have to specify the first name last name age
7:54:51
y también tenemos que especificar el correo electrónico y también la contraseña misma.
and we also have to specify the email and also the password itself.
7:54:55
Está bien, así que ahora déjame crear algún tipo de usuario como yo mismo y
Okay, so now let me just create some sort of a user like myself and
7:54:58
va a ser igual a ese usuario que estamos
it's gonna to be equals to uh that user which we
7:55:01
combinando y dentro de ahí oh Dios mío no como
are combining and inside there oh my god not like uh
7:55:05
tenemos que anotar eso así y dentro
we have to annotate that like so and inside
7:55:08
de lo que requiere ahora déjame pasar el mouse sobre eso así que el tipo objeto no es asignable a un tipo usuario de qué demonios estás hablando um sí tipo um
there what it requires now let me just hold my mouse over to it so the type object is not assignable to a type user what the hell are you talking about um yeah type um
7:55:18
el tipo objeto está faltando, bien, ahí vamos, así que el tipo objeto está faltando algunas propiedades
type object is missing the okay there we go so type object is missing a few properties
7:55:23
y la información del usuario, nombre, apellido y borde y bla bla bla, está bien
and user info first name last name and edge and blah blah blah okay
7:55:26
así que ahora hagamos eso aquí mismo, así que voy a escribir un nombre
so now let's just do that right here so i'm going to just write a first name
7:55:29
y el nombre se establecerá en hosain, también voy a
and the first name will be set to hosain i'm going to also
7:55:33
proporcionar una pérdida, sí, la pérdida estará bien y se
provide a loss yeah loss will be fine and it's
7:55:36
establecerá en desarrollador web aquí mismo y también voy a
going to be set to web dev right here and i'm going to also
7:55:39
proporcionar esta contraseña, está bien
provide um this password right
7:55:42
aquí, así que la contraseña que voy a proporcionar es como contraseña uno dos o
here so the password i'm going to provide like password one two or
7:55:45
algo así, déjame proporcionar mi propia dirección de correo electrónico que será was in at gmail.com aquí, está bien, y la página es 25, ahí vamos, uh, cambiemos eso a 20.
something like that let me just provide my own email address which will be was in at gmail.com right here okay and page is 25 there we go uh let's just change that to 20.
7:55:56
ahora déjame guardar eso y vamos a usar eso aquí
now let me just save that and let's just use that right here
7:55:59
si todo está funcionando o no, y por cierto, aquí puedes
whether everything is working or not and by the way here you
7:56:02
ver que el error también ha desaparecido por completo, supongamos
can see that error is also totally gone let's suppose
7:56:05
que si simplemente elimino una de estas propiedades aquí, puedes ver que el error regresó aquí, está bien, así que si vuelvo a escribir mi contraseña, ahí vamos, todo está funcionando, está bien, así que ahora déjame iniciar sesión en el
if i just remove one of these properties here you can see that error came backward here okay so if i just write my password once again and there we go everything is working okay so now let me just log to the
7:56:19
um, voy a escribir hosan.firstname y
um i'm going to just write hosan.firstname and
7:56:22
también hosan.lastname
also hosan.lastname
7:56:26
también y edad, vamos, edad
as well and age come on age
7:56:29
se va a igualar a hosan.age y también voy a proporcionar el
is going to be equals to hosan.age and i'm going to also pour the
7:56:32
correo electrónico para la dirección de correo electrónico, voy a escribir hosan.email
email for the email address i'm going to write hosan.email
7:56:36
dirección y también la contraseña misma
address and also the password itself
7:56:39
está bien, así que ahora vamos a renderizar hosan.password, sí, proyecto totalmente autenticado aquí, está bien, así que ahora déjame ejecutar eso aquí
okay so now let's just render hosan.password yeah fully authenticated project right here okay so now let me just run that here
7:56:48
puedes ver que ahora estamos obteniendo el nombre was in desarrollador web, la edad ahora está
you can see we are now getting the name was in web dev edge is now
7:56:51
establecida en 20, también estamos obteniendo el correo electrónico de us in gmail.com
set to 20 we are also getting the email of us in gmail.com
7:56:54
y la contraseña es contraseña 12 aquí, está bien
and the password is password 12 right here okay
7:56:57
así que eso se conoce como el tipo de intersección en typescript, aquí se combinarán más de un tipo a la vez
so that is known as the intersection type in typescript right here which will combine more than one types at once
7:57:06
sí, eso es todo sobre los tipos de intersección en typescript, así que es hora de hablar sobre los tipos de unión en typescript, sí, eso es un poco de poesía, es hora de hablar sobre los tipos de unión en typescript de todos modos
yep that's it for the intersection types in typescript so time to talk about union types in typescript yeah that's kind of a poetry time to talk about union types in typescript anyways
7:57:18
Las uniones se utilizan para declarar un tipo que puede tener uno o varios tipos posibles.
So unions are used to declare a type that can have one or several possible types.
7:57:23
Las uniones son útiles cuando quieres permitir que una variable o un parámetro acepte múltiples tipos.
So unions are useful when you want to allow a variable or a perimeter to accept multiple types.
7:57:29
Así que la sintaxis es que solo tenemos que usar el símbolo de barra vertical. Solo tienes que mantener presionada la tecla Shift y presionar el que está debajo o, ya sabes, no debajo, sino el que está encima del botón de entrada.
So the syntax is we just have to use the pipe symbol. You just have to hold a shift key and hit which is underneath or you know not underneath but which is above the inner button.
7:57:40
Ahí vamos. ¿Cómo vamos a usar eso? Así es como vamos a usar eso.
There we go. So how we are going to be using that? This is how we are going to be using that.
7:57:44
Por ejemplo, queremos crear una variable que puede ser un número o una cadena. Así que solo tenemos que escribir este símbolo de barra vertical aquí.
For example, we want to create a variable which can either be number or a string. So we are going to have to just write this pipe symbol right here.
7:57:52
Está bien, ahí vamos. Y también podemos usarlo para un parámetro de función. Vamos a usarlo así. Así que solo vamos a escribir algún tipo de parámetro.
Okay, so there we go. And we can also use it for a function parameter. We are going to be using it like this. So we are going to be just writing some sort of parameter.
7:57:59
Y el parámetro debe ser una cadena o también una cadena de arreglo. Como si estuvieras trabajando con algún tipo de función asincrónica.
And the parameter either should be string or also the string of array. Like if you are working with some sort of asynchronous function.
7:58:07
Así que sí, eso es. Y también podemos usarlo para las interfaces. Pero no discutimos qué son nuestras interfaces.
So yeah, that's that. And we can also use it for the interfaces. But we did not discuss what our interfaces are.
7:58:14
Así que no voy a discutir el tipo de unión dentro de la interfaz, así que
and so i'm not going to discuss the union type inside the interface so
7:58:17
ahora déjame escribir algo de código y entonces sabrás de qué estoy hablando
now let me just write some code and then you will get to know what i'm talking about
7:58:20
así que voy a eliminar todo ese código aquí y voy a
so i'm going to just remove all of that code right here and i'm going to
7:58:23
simplemente crear algún tipo de contraseña, uh vamos p swrd
just create some sort of a password uh come on p swrd
7:58:27
y la variable de contraseña debe ser una cadena
and password variable should either be string
7:58:30
o, uh, tipo de unión número aquí
or uh union type number right here
7:58:34
y por defecto voy a especificar el valor de 20 aquí
and by default i'm going to specify the value of 20 right here
7:58:37
está funcionando totalmente, pero si intento proporcionar algo más
it is totally working but if i just try to provide something else
7:58:40
como una cadena, está funcionando totalmente también
like string okay so it is totally working as well
7:58:43
pero supongamos que si solo escribo verdadero, nos dará un
but let's suppose if i just write it true it's gonna give us an
7:58:46
error, ¿por qué es eso? Porque solo escribimos una unión
error why is that because we only write a union
7:58:49
tipo para una cadena o un número, así que por eso
type for either a string or a number so that's why it
7:58:52
ahora nos está dando este error aquí, así que ahora
is now giving us this error right here so now
7:58:55
déjame establecerlo en 20 y ahí vamos, y también podemos escribir
let me just set there to 20 and there we go and we can also write
7:58:58
un tipo de unión para tipos también, así que ahora déjame crear una información de usuario
a union type for types as well so now let me just create a user info
7:59:02
tipo, va a tomar el primero y voy a proporcionar una cadena
type it's gonna take the first and i'm gonna provide a string
7:59:05
aquí también va a tomar, oh Dios, último
right here it's going to also take oh my god last
7:59:08
y el último también se establecerá como cadena, también voy a proporcionar el borde
and last will be also set to string i'm going to also provide the edge
7:59:11
del no sí, borde del número, ahora déjame crear uno para
of no yeah edge of number now let me just create one for
7:59:14
los detalles de la cuenta una vez más, así que los detalles de la cuenta
that account details once again so account details
7:59:18
y va a ser igual a este tipo justo aquí, así que
and it's going to be equals to this type right here so
7:59:21
vamos a proporcionar el correo electrónico y el correo electrónico se establecerá como cadena y también la contraseña se establecerá como cadena aquí queremos usar ese tipo de unión, así que voy a crear un objeto de usuario y solo voy a anotar esto.
we're going to be providing the email and the email will be set to string and also the password will be set to string as well here we want to use that union type so i'm going to just create a user object and i'm I'm gonna just annotate this.
7:59:32
Así que tienes que usar la información del usuario, que requiere el nombre y también el apellido y también el borde en sí.
So you either have to use the user info, which requires the first name and also the last name and also the edge itself.
7:59:40
O podemos usar el tipo de unión justo aquí o usar los detalles de la cuenta justo aquí.
Or we can use the union type right here or use the account details right here.
7:59:46
Así que va a ser igual a, supongamos que lo intentamos con el nombre y el apellido como para la información del usuario.
So it's gonna be equals to, let's suppose let's try it with the first name and last name like for the user info.
7:59:53
Así que intentémoslo para la información del usuario. Así que tenemos el nombre de John, el apellido de Doe y el borde de 20 justo aquí.
So let's try it for the user info. So we have first name of John, the last name of Doe and edge of 20 right here.
8:00:00
todo está funcionando totalmente porque aquí estamos proporcionando o especificando todas las propiedades justo aquí, todas las propiedades que esta información del usuario tiene actualmente aquí
everything is totally working because here we are providing or we are specifying all of the properties right here all of the properties which this user info currently have right here
8:00:10
bien, así que ahora estamos proporcionando todas sus propiedades, pero si solo quito eso
okay so we are now providing all of their property but if i just remove that
8:00:14
y ahora trabajemos con este detalle de la cuenta, así que solo voy a
and now let's work with this account detail so i'm going to just
8:00:17
especificar como un correo electrónico y el correo electrónico será como uh algo como
specify like an email and the email will be like uh some come
8:00:21
alguien en gmail.com o algo así y ahora también voy a proporcionar una contraseña
on someone at gmail.com or something like that and now i'm going to also provide a password
8:00:26
también una contraseña será como contraseña o
as well a password will be like password or
8:00:29
algo así, así que aquí puedes ver que no nos dará ningún
something like that so here you can see it's not going to give us any
8:00:32
error, pero si solo quito esta contraseña y aquí puedes ver que
error but if i just remove this password and here you can see we
8:00:35
ahora estamos obteniendo este error como si algo faltara, como la contraseña
are now getting this error like something is missing like password
8:00:38
falta, tienes que proporcionar esa contraseña y ahí vamos, está bien
is missing you have to provide that password and there we go okay
8:00:42
así que podemos usarlo para um, vamos, podemos usarlo para objetos, podemos usarlo para tipos, también puedes usarlo para una sola variable y más tarde también vamos a aprender
so we can use it for um come on we can use it for objects we can use it for types you can also use it for a single variable and later we are going to be also learning
8:00:51
sobre algo llamado interfaces, así que
about something called the interfaces so
8:00:54
vamos a usarlo dentro de las interfaces también, así que ahora déjame
we are going to be using it inside interfaces as well so now let me
8:00:57
simplemente usar el arreglo interno, así que podemos escribir elementos y
just use the inside array so we can just write items and
8:01:00
aquí tenemos que escribir primero nuestros paréntesis porque primero
here we have to write first of all our parentheses because first
8:01:03
de todo tenemos que especificar el tipo, está bien, así que voy a escribir
of all we have to specify the type okay so i'm going to just write
8:01:06
un número o debería estar usando el
a number or it should be using the
8:01:10
cadena de array, así que ya sea el número del array o las cadenas del array aquí, así que puedes usar el array de números y también puedes usar ambos
string of array so either the number of array or the strings of array right here so you can either use the number array and you can also use both of them
8:01:18
también puedes incluso usar como ambos el usuario
as well you can even also use like both the user
8:01:21
información y también los detalles de la cuenta, así que ambos en
info and also the account detail as well like both of them at
8:01:24
una vez que olvidé mostrarte allí, pero puedes intentar eso por
once i forgot to show you there but you can try that by
8:01:27
ti mismo, así que en este caso solo proporcionemos valores para ellos
yourself so in this case let's just provide a values for them
8:01:31
así que voy a especificar primero el radio para un número, así que
so i'm going to just first of all specify radius for a number so
8:01:34
voy a decir como uno y cinco cuatro cuatro o
i'm going to just say like one and five four four or
8:01:37
algo así y también voy a especificar algún tipo de cadena aquí como hola o algo así, también puedo pro pero puedo
something like that and i'm going to also specify some sort of a string right here like hello or something like that i can also pro but i can
8:01:45
proporcionar el booleano, así que si solo lo escribo, va a dar
provide the boolean so if i just write it through it's going to give
8:01:48
un pequeño error genial y ya sabes qué tipo de error dará
us a cool little error and you already know which kind of error it will give
8:01:51
nos dará como tipo de booleano no asignable
us it will give us like type of boolean is not assignable
8:01:54
al tipo de cadena o número, está bien, así que va a dar
to the type of string or number okay so it's going to give
8:01:57
ese error, ahora déjame solo eliminar eso y podemos registrar
us that error now let me just remove that and we can log
8:02:00
los elementos en la consola, cariño, volvamos y
the items to the console baby let's just go back and
8:02:04
ejecuta eso y aquí puedes ver que nos va a dar ese array con, vamos, con un número y también con un
run that and here you can see it's going to give us that array with uh come on with a number and also with a
8:02:10
string también, así que eso fue todo sobre el tipo de unión
string as well so that was it about for the union type
8:02:13
en typescript, así que ahora aprendamos sobre tipos literales en
in typescript so now let's learn about literal types in
8:02:16
typescript, así que los tipos literales te permiten especificar un valor que
typescript so literal types allow you to specify a value that
8:02:20
solo puede ser un literal específico
can only be one specific literal
8:02:23
valor, está bien, así que esto significa que la variable con el literal
value okay so this means that the variable with the literal
8:02:26
tipo solo puede tener un valor específico y
type can only have one specific value and
8:02:29
ninguno más, está bien, así que cómo se verá la sintaxis, así es como se verá la sintaxis, así que podemos usarlo para una cadena, podemos usarlo para booleano y también para números, así que aquí puedes
no others okay so how the syntax will look like this is how the syntax will look like so we can use it for a string we can use it for boolean and also for a numbers as well so here you
8:02:39
ver que tenemos algún tipo de variable aquí, así que
can see we have some sort of a variable right here so
8:02:42
podemos proporcionar el valor de rojo, azul o
we can either provide the value of red blue or
8:02:45
verde está bien nada más como si solo
green okay nothing else like like if i just
8:02:48
pongo el valor de rojo totalmente válido si proporciono
put the value of red totally valid if i provide
8:02:51
un amarillo que no tenemos en esta lista va
a yellow which we don't have inside this list it's
8:02:54
a darnos un inválido y no funcionará por otro lado probemos con los números así que aquí puedes ver que estamos proporcionando un
going to give us an invalid and it will not work on the other hand let's try it for the numbers so here you can see we are providing a
8:03:01
valores literales como uno dos o tres como
literal values like one two or three like
8:03:05
uno o dos o tres está bien
either one or two or three okay
8:03:08
así que supongamos que si proporcionas como el número uno está totalmente
so let's suppose if you provide like the number of one to it totally
8:03:11
válido puedes trabajar totalmente con eso pero ahora
valid you can totally work with that but now
8:03:14
estamos especificando para que no está disponible dentro
we are specifying for to it which is not available inside
8:03:17
de esta lista así que nos dará un inválido lo que significa que
this list so it's going to give us an invalid which means like it's
8:03:20
va a lanzar algún tipo de error y lo mismo sucederá con los booleanos
going to throw some sort of error and the same will goes for the booleans
8:03:24
así que solo estamos declarando lo que llamamos oh Dios mío solo estamos declarando una variable y estamos asignando
so we are just declaring the what do we call it oh my god we are just declaring a variable and we are assigning
8:03:30
el valor de verdadero a eso y pero si pones el valor de
the value of true to it and but if you put the value of
8:03:33
falso a eso así que nos dará algún tipo de errores ahora déjame darte un ejemplo
false to it so it's going to give us some sort of errors now let me just give you an example
8:03:36
de eso entonces sabrás de qué estoy hablando así que ahora déjame quitar
of that then you will get to know what i'm talking about so now let me just remove
8:03:39
todo ese código y solo voy a escribir let color en el
all of that code and i'm going to just write let color in the
8:03:42
color vamos a especificar algún tipo de color
color we are going to be specifying some sort of a color
8:03:45
como rojo y también voy a poner el color carmesí y también voy a poner el color fucsia está bien así que ahora déjame poner estos colores
like red and i'm going to also put the color of crimson and i'm going to also put the color of fuchsia okay so now let me just put these colors
8:03:56
y solo voy a proporcionar color y el color se establecerá en
and i'm going to just provide color and the color will be set to
8:04:00
uh rojo en este caso totalmente accesible
uh red in this case totally accessible
8:04:03
totalmente funcional como no estamos obteniendo ningún error nada aquí
totally working like we are not getting any errors nothing right here
8:04:06
si registro allí en la consola como color envía mi archivo
if i log there to the console like color send my file
8:04:09
regresa y ejecuta eso vamos a
go back and run that come on let's just
8:04:12
quitar esa basura y volver a ejecutarlo una vez más y
remove that crap and rerun that once again and
8:04:16
aquí puedes ver que ahora estamos obteniendo rojo aquí que está totalmente funcionando pero si solo duplico eso y cambio eso a como amarillo y aquí puedes ver que va a
here you can see we are now getting red right here which is totally working but if i just duplicate that and change that to like yellow and here you can see it's going to
8:04:24
nos da un error y el tipo amarillo no es asignable
gives us an error and the type yellow is not assignable
8:04:28
al tipo rojo o carmesí o fucsia que
to the type red or crimson or fuchsia which
8:04:31
significa que este tipo que estás proporcionando aquí no está
means like this type which you are providing right here is
8:04:34
dentro de esta lista así que por eso ahora estamos recibiendo
not inside this list so that's why we are now getting
8:04:37
un error aquí si simplemente ejecuto eso, obviamente vamos a estar
an error right here if i just run that obviously we are going to be
8:04:40
recibiendo un pequeño error, oh no guardé eso, simplemente vamos a
getting a cool little error oh i didn't save that let's just
8:04:44
guardar eso y volver a ejecutarlo una vez más y aquí puedes
save that and rerun that once again and here you can
8:04:47
ver que nos va a dar ese mismo error aquí, está bien, así que eso es totalmente genial, pero ahora
see it's going to give us that same error right here okay so that's totally cool but now
8:04:53
déjame darte un ejemplo de números o ya sabes booleanos, así que menos es verdadero, así que el booleano puede ser verdadero o
let me just give you example of a numbers or you know boolean so less is true so the boolean can either be true or
8:05:00
uh no otros valores, así que ahora déjame escribir es
uh no other values so now let me just write is
8:05:03
verdadero y va a ser igual a verdadero aquí, está bien, así que
true and it's going to be equals to true right here okay so
8:05:06
podemos registrar eso en la consola y ya sabes lo que nos dará
we can log there to the console and you already know what it will give us
8:05:09
pero si simplemente escribo como es verdadero es igual a algo
but if i just write like is true is equal to like something
8:05:13
más y ya sabes que nos va a dar un
else and you already know it's going to give us an
8:05:16
error, así que eso fue todo para los booleanos, ahora déjame darte el ejemplo de algún tipo de, ya sabes cómo va a funcionar eso para los números, así que no voy a dar los números
error so that was it for the booleans now let me just give you the example of some sort of uh you already know how that's going to work for the numbers so i'm not going to give the numbers
8:05:24
ejemplo, pero ahora déjame crear algún tipo de contraseña y
example but now let me just create some sort of a password and
8:05:27
voy a proporcionar el video de como una contraseña secreta
i'm going to provide the video of like secr et
8:05:30
como una contraseña secreta, contraseña secreta
password like a secret password secret password
8:05:34
y va a ser igual a, uh, esa contraseña secreta, estoy
and it's going to be equals to uh that secret password i'm
8:05:37
y ahora déjame colocar eso aquí, volver atrás, está bien
going to copy there and now let me just place that right here go back okay
8:05:40
así que ahora estamos proporcionando este valor específico para esto
so we are now providing this specific value for this
8:05:43
contraseña específica, ahora dentro de eso lo que quiero hacer es que si simplemente registro en la consola esta contraseña, déjame volver atrás y
specific uh password right here now inside there what i want to do is that if i just log to the console this password let me just go back and
8:05:51
ejecutar eso, déjame volver atrás y ejecutar eso y aquí puedes ver que nos va a dar una contraseña secreta
run that let me go back and run that and here you can see it's going to give us a secret password
8:05:56
supongamos que quiero cambiar el valor de eso como contraseña
let's suppose if i want to change the value of that like password
8:05:59
es igual a algo más y aquí puedes ver
is equal to like something else and here you can see
8:06:03
ahora estamos obteniendo este error como si algo más no fuera asignable a esa contraseña secreta aquí, así que si solo lo ejecuto, nos dará ese error justo aquí
we are now getting this error like something else is not assignable to that secret password here okay so if i just run that it's going to give us that error right here
8:06:11
oh vamos, siempre olvidé guardar eso y aquí puedes ver que nos dará ese horrible error justo aquí.
oh come on i always forgot to save that grab and here you can see it's going to give us that awful error right here.
8:06:18
Así que eso fue todo sobre cómo lo llamamos? Eso fue todo sobre los tipos literales en TypeScript.
So that was it about what do we call it? That was it about for the literal types in TypeScript.
8:06:24
Ahora aprendamos sobre un tema del lenguaje de programación Python que se llama tuplas. ¿Tienes que saber el lenguaje de programación Python?
Now let's learn about a Python programming language topic which is called tuples. Do you have to know Python programming language?
8:06:31
Por supuesto que no. Pero sí, esto ya está disponible dentro de Python si quisieras verlo.
Of course not. But yeah this is already available inside of Python if you wanted to check it out.
8:06:35
Entonces, ¿qué es una tupla o tuplas o como quieras llamarlo?
So what is a tuples or tuples or whatever you want to call that?
8:06:40
Así que una tupla o tuplas es un tipo que representa un arreglo con un número fijo
So tuple or tuples is a type that represents an array with a fixed number
8:06:45
de elementos donde cada elemento puede tener un tipo diferente
of elements where each element can have a different type
8:06:48
el orden de estos tipos en la definición de la tupla corresponde
the order of these types in the tuple definition corresponds
8:06:51
al orden de los valores en el arreglo real, así que
to the order of the values in the actual array so
8:06:55
las tuplas son similares a los arreglos, pero tienen una estructura específica
tuples are similar to arrays but they have a specific
8:06:58
y se pueden usar con
structure and can be used with
8:07:01
una secuencia modal finita con longitudes conocidas, está bien
modal finite sequence with known lengths okay
8:07:05
así que eso fue solo una definición de lo que es una tupla o tuplas, ahora aprendamos sobre cómo vamos a estar usándolas, es similar a los arreglos
so that was just a definition of what a tuples or tuples is now let's learn about how we are going to be using that this is how we are going to be using them it is similar to arrays
8:07:14
pero la sintaxis es un poco diferente y ya discutimos eso, así que
but the syntax is a bit different and we already discussed that so
8:07:17
vamos a estar anotando allí justo aquí dentro de los corchetes, no
we are going to be annotating there right here inside of brackets not
8:07:21
fuera de los corchetes, sino dentro del corchete vamos a estar usando
outside from the brackets but inside the bracket we are going to be using
8:07:24
ya sea una cadena o un número, así que podemos proporcionar algún tipo de un
either a string or number so we can provide some sort of a
8:07:27
estructura para nuestros datos que vamos a estar almacenando dentro de esta tupla
structure for our data which we are going to be storing inside this tuple
8:07:30
como el primer valor se establecerá en cadena, así que ahora estamos almacenando
like the first value will be set to string so we are now storing
8:07:33
el valor de cadena y el segundo se establecerá en número, así que aquí puedes ver que ahora estamos proporcionando el número justo aquí, así que nos dará su hola y también, ¿cómo lo llamamos? el número también.
the string value and the second one will be set to number so here you can see we are now providing the number right here so it's going to give us their hello and also uh what do We call it the number as well.
8:07:44
Y por cierto, esto también es un índice cero. Así que quiero que tengas eso en mente también. Ahora aprendamos también sobre la desestructuración.
And by the way, this is also a zero index bar. So I want you to keep that in mind as well. Now let's also learn about destructuring.
8:07:52
No tienes que preocuparte por la desestructuración. Pero estoy discutiendo este tema para aquellos que les importa.
You don't even have to worry about destructuring. But I'm discussing this topic for those who cares.
8:07:58
Si no te importa eso, ni siquiera tienes que preocuparte por eso. Entonces, ¿cómo vamos a desestructurar el valor de eso? Bueno, solo vamos a estar usando estos corchetes.
If you don't care about that, you don't even have to worry about that. So how are we going to be destructuring the value of that? Well, we are going to be just using these brackets.
8:08:06
Así que vamos a desestructurar el valor de hola. Y le vamos a dar el nombre de primero. Puedes darle cualquier nombre que quieras.
So we are going to be destructuring the value of hello. And we are going to be giving it the name of first. You can give it any name you want.
8:08:14
y luego vamos a desestructurar el valor de número y estamos viniendo
and then we are going to be destructuring the value of number and we are coming
8:08:17
como este 42 y vamos a darle un nombre como segundo, así que si
like this 42 and we are going to give a name of like second so if
8:08:20
registras en la consola primero y segundo, así que para el primero estamos
you log to the console first and second so for the first one we are
8:08:23
a obtener un hola, para el segundo vamos a obtener 42
going to be getting a hello for the second one we are going to be getting 42
8:08:26
aquí mismo, así que ahora déjame escribir algo de código, entonces sabrás qué
right here so now let me just write some code then you will get to know what
8:08:29
estoy hablando, así que lo que quiero hacer es que primero estoy
i'm talking about so what i want to do is that first of all i'm
8:08:32
simplemente creando un simple dos, déjame mi dos, uh, creo que así se escribe, y ahora vamos a proporcionar el
going to just create a simple two let my two uh pull i guess this is how you spell it and now we are going to be providing the
8:08:41
anotación, así que vamos a proporcionar una estructura como cuál
annotation so we are going to be providing a structure like which
8:08:44
tipo de datos o qué tipo de estructura vamos a usar para
kind of data or which kind of structure we are going to be using for
8:08:47
nuestros datos, así que vamos a especificar el número y también la cadena
our data so we are going to be specifying the number and also the string
8:08:50
también, y ahora déjame especificar algún tipo de valor
as well and now let me just specify some sort of a value
8:08:54
para ello, así que como mi tupla y va a ser igual a primero
to it so like my tuple and it's going to be equals to first
8:08:57
de todo, estamos requiriendo el número, así que
of all we are requiring the number so
8:09:00
en este caso tenemos que especificar algún tipo de número aquí, así que en este caso voy a especificar como 10 y luego tenemos que especificar el valor de cadena, así que para el valor de cadena voy a decir como
in this case we have to specify some sort of a number right here so in this case i'm going to just specify like 10 and then we have to specify the string value so for the string value i'm going to just say like
8:09:11
hola mundo, ahí vamos, y ahora déjame registrar
hello world there we go and now let me just log
8:09:14
eso en la consola, como mi tupla, ahí vamos, déjame
that to the console like my tuple there we go let me just
8:09:17
guardar eso y ejecutar eso, y aquí puedes ver que dará
save that and run that and here you can see it will
8:09:20
como 10 y también hola mundo en el
give us like 10 and also hello world on the
8:09:23
otro lado, déjame intentar algo más, si corto
other hand let me just try something else if i cut
8:09:26
este 10 de aquí y si simplemente lo coloco aquí
this 10 from here and if i just place it right here
8:09:30
y simplemente guardemos eso y va a darnos un error, ¿por qué es eso? Si paso el mouse sobre él, así que el tipo string no es asignable al tipo number, ¿por qué es eso?
and let's just save that and it's going to give us an error why is that if i hover my mouse over to it so type string is not assignable to the type number why is that
8:09:40
porque hicimos una estructura así, primero que todo
because we made a structure like this first of all
8:09:43
requeriríamos algún tipo de número, luego requeriríamos
we would require some sort of a number then we would
8:09:47
algún tipo de cadena, así que en este caso estamos proporcionando primero
require some sort of a string so in this case we are providing first of all
8:09:50
la cadena y luego el número, eso no es aceptable, eso es
the string and then the number that's not acceptable that's
8:09:53
un gran no-no en tuplas, así que sí, esa es la única razón por la que vamos a usar tuplas en primer lugar y tú
a big no-no in tuples okay so yeah that's the only reason we are going to be using tuples in the first place and you
8:10:00
estás violando sus reglas, así que typescript no va a estar feliz con
are violating their rules so typescript is not going to be happy with
8:10:03
eso, así que voy a comentar esta línea y ahora
that okay so i'm going to just comment this line out and now
8:10:06
déjame crear alguna otra o, ya sabes, um
let me just create some other or you know um
8:10:09
déjame crear una tupla para un producto, así que voy a
let me just create a tuple for a product so i'm going to just
8:10:12
escribir const productos y va a ser igual a
write const products and it's going to be equals to
8:10:16
va a tomar ya sea un número o la cadena de un array y va a ser igual a como no sé, ítem uno y también voy a proporcionar
it's going to take either number or the string of one array and it's going to be equals to like i don't know item one and i'm going to also provide
8:10:24
uno dos aquí, está bien, ahora déjame volver y
one two right here okay now let me just go back and
8:10:28
si registro esos productos en la consola, ya sabes qué tipo de razón tenemos
if i log that products to the console you already know which kind of reason we
8:10:31
por qué, oh, ahí vamos, siempre lo olvidaba
would get why oh there we go i always forgot
8:10:34
esta anotación aquí, simplemente ejecutémosla
this annotation right here let's just run
8:10:37
eso, vamos, y aquí puedes ver que nos va a dar
that come on and here you can see it's going to give us
8:10:40
ítem uno y también aquí, lo cual es totalmente
item one and also right here which is totally
8:10:43
genial, así que voy a eliminar eso, ahora déjame darte un ejemplo más para la cadena cadena cadena, así que ahora déjame escribir un juegos y va a tomar
cool so i'm going to delete that now let me just give you one more example for the string string string so now let me just write a games and it's going to take
8:10:52
la estructura como cadena y también cadena y también
the structure like string and also string and also
8:10:55
una vez más cadena y ven el infierno
yet again string and come the hell
8:10:59
hombre, voy a proporcionar el signo de anotación en lugar
man i'm going to provide the annotation sign rather
8:11:02
del signo igual y aquí voy a escribir como juego uno
than the equal sign and here i'm going to just write like game one
8:11:05
y voy a decir como juego dos y
and i'm going to just say like game two and
8:11:09
también el juego tres, ahora déjame registrar estos juegos en la consola, guardar mi archivo y ejecutar, ahí va a darnos juego uno, juego dos, juego
also the game three as well now let me just log this games to the console save my file and run there it's going to give us game one game two game
8:11:17
gratis, pero si solo escribo como para el
free but if i just write like for the
8:11:20
medio, quiero obtener un número aquí, así que si
middle one i want to get a number right here so if i
8:11:23
simplemente los vendo, va a darnos un error si solo
just sell them it's going to give us an error if i just
8:11:26
coloco el mouse sobre eso, oh Dios mío, va a decir
hover my mouse over to that oh my god it's going to say
8:11:29
como tipo cadena no es asignable al tipo número porque
like type string is not assignable to the type number because
8:11:32
aquí requerimos el número que tenemos que especificar
here we require the number we have to specify
8:11:35
algún tipo de número aquí, está bien, así que podemos crear algún tipo de estructura como, um, el nombre del juego será una cadena, las calificaciones del juego serán algún tipo de número
some sort of a number right here okay so we can create some sort of a structure like um the game name will be a string the game ratings will be some sort of a number
8:11:46
y la calificación verdadera del juego será algún tipo de booleano
and the game true rating will be some sort of boolean
8:11:49
así que voy a simplemente usar bool o booleano más bien y
so i'm going to just fire bool or boolean rather and
8:11:52
aquí voy a simplemente especificar verdadero y ahora déjame guardar
here i'm going to just specify true and now let me just save
8:11:55
eso y ejecutar eso aquí puedes ver que nos va a dar como el juego uno
that and run that here you can see it's going to give us like game one
8:11:58
la calificación se establecerá en dos y también el
the rating will be set to two and also the
8:12:02
la calificación real se establecerá en, uh, verdadero aquí, así que esto
real rating will be set to uh true right here so this
8:12:05
es cómo vamos a crear una tupla y así es como vamos a usar nuestras tuplas en typescript ahora aprendamos sobre
is how we are going to be creating a tuple and this is how we are going to be using our tuples in typescript now let's learn about
8:12:11
enums en typescript, así que enum es una forma de
enums in typescript so enum is a way to
8:12:15
definir un conjunto de constantes nombradas, así que
define a set of name constants so
8:12:18
enum te permite definir una colección de valores relacionados que pueden
enum allow you to define a collection of related values that can
8:12:21
ser usados indistintamente en tu código, así que
be used interchangeably in your code so
8:12:24
cómo se verá eso, así es como se verá, como por
how that's going to look like this is how it's going to look like like for
8:12:27
ejemplo, digamos que estás construyendo una aplicación del clima y quieres
example let's say you're building a weather app and you want
8:12:30
definir un conjunto de posibles condiciones climáticas como soleado, nublado, lluvioso y nevado, podrías definir un enum así, primero vas a escribir el enum
to define a set of possible weather conditions like sunny cloudy rainy and snowy you could define an enum like this you're going to be first of all writing the enum
8:12:39
palabra clave reservada, luego puedes darle algún tipo de nombre a eso y
reserved keyword then you can give some sort of a name to that and
8:12:42
luego tienes que escribir las llaves, no tienes que
then you have to write the curly braces you don't have to
8:12:45
especificar alguna notación o anotación para ser preciso
specify some notation or annotation to be precise
8:12:48
y ni siquiera tienes que usar el signo igual para eso y
and you don't even have to use the equal to sign for that and
8:12:52
luego puedes especificar tus constantes como soleado, nublado, lluvioso, nevado
then you can specify your constants like sunny cloudy rainy snowy
8:12:55
o lo que sea, así que en este ejemplo, la condición climática es el nombre del enum y cada uno de los valores, por ejemplo, soleado, nublado, etc., se asigna a valores numéricos automáticos comenzando desde cero
or whatever so in this example weather condition is the name of the enum and each of the values for example sunny cloudy etc is assigned to automatic numeric values starting from zero
8:13:07
está bien, así que este será cero, este será uno, dos y tres
okay so this one will be zero this one will be one two and three
8:13:10
y así sucesivamente, y incluso puedes especificar tus propios valores como
and so on and you can even specify your own values like
8:13:13
esto, está bien, así que solo vas a escribir el signo igual
this okay so you're going to be just writing the equal to sign
8:13:17
y puedes especificar soleado nublado lo que quieras
and you can specify sunny cloudy whatever you want
8:13:20
así es como se verá la sintaxis y ahora déjame darte
this is how the syntax will look like and now let me just give you
8:13:23
una especie de ejemplo y luego conocerás de qué estoy hablando y
some sort of example and then you will get to know what i'm talking about and
8:13:27
sabes, antes de entrar en el ejemplo, primero quiero mostrarte cómo vas a usar el em, olvidé mostrarte allí, así que así es como vas a usarlos, como supongamos que hay una
you know before getting into the example first of all i want to show you how you're going to be using the em i forgot to show you there so this is how you're going to be using them like let's suppose some
8:13:36
especie de variable y luego vas a obtener ese nombre de enum
sort of a variable and then you are going to be getting that enum name
8:13:39
y luego no termina, entonces podrás
and then the don't end then you would be able
8:13:42
especificar qué tipo de propiedad deseas acceder, así que aquí
to specify which kind of property you want to access so here you
8:13:45
puedes ver que el nombre de nuestro enum está establecido en condiciones climáticas
can see the name of our enum is set to weather conditions
8:13:48
y luego dentro de su condición climática tenemos el soleado
and then inside their weather condition we have the sunny
8:13:51
propiedad aquí que actualmente está configurada en soleado y esto
property right here which is currently set to sunny and this
8:13:55
es cómo vamos a obtener esto, así que console.log el clima actual
is how we are going to be getting this so console.log the current weather
8:13:58
es el clima actual y ahora estamos obteniendo soleado aquí como salida, así que así es como vamos a crear un enum y así es como
is current weather and we are now getting sunny right here as output so this is how we are going to be creating an enum and this is how we are
8:14:05
vamos a usar un enum dentro de nuestro proyecto, así que voy a eliminar
going to be using an enum inside our project so i'm going to delete
8:14:08
este código aquí y solo voy a crear mi enum y
this code right here and i'm going to just create my enum and
8:14:12
tenemos sí, ahí vamos, uh
do we have yeah there we go uh
8:14:15
no queremos eso, simplemente eliminemos el enum aquí
we don't want that let's just remove the right here enum
8:14:18
una vez más y clima w-a-t-h-e-r
once again and weather w-a-t-h-e-r
8:14:22
condiciones, ahí vamos y no vamos a proporcionar el
conditions there we go and we're not going to be providing the
8:14:25
signo igual, pero solo vamos a proporcionar las llaves aquí, voy a especificar soleado, nublado, lluvioso y ahora si solo registro eso en la consola o tú
equal to sign but we are going to be just providing the curly braces right here i'm going to specify sunny cloudy rainy and now if i just log there to the console or you
8:14:34
sabes, primero déjame escribir como condición climática
know first of all let me just write like weather condition
8:14:37
punto soleado, soleado, déjame volver y ver
dot sunny sunny let me just go back and see
8:14:40
qué nos dará ahora, déjame guardar eso y ejecutarlo y aquí
what it will gives us now let me just save that and run it and here
8:14:44
puedes ver que nos dará un cero porque este es un cero
you can see it's going to give us a zero because this is a zero
8:14:47
espacio de índice y no especificamos ningún valor
index space and we did not specify any values
8:14:50
así que nos dará por defecto cero aquí, así que
to it so it's going to give us by default zero right here so
8:14:53
estos son todos constantes o enums lo que quieras
these are all constants or enums whatever you want to
8:14:56
supongamos que quieres obtener el valor de
call that let's suppose if you want to get the value of
8:14:59
como no sé lluvioso ya sabes lo que nos dará
like i don't know rainy you already know what it will gives us
8:15:02
pero quiero ejecutarlo de todos modos, nos dará dos aquí porque
but i want to run it anyways it's going to give us two right here because
8:15:06
este es cero, este es uno y este es dos, así que por eso
this one is zero this one is one and this one is two so that's why
8:15:09
ahora estamos obteniendo dos aquí dentro de una consola, ahora lo siguiente
we are now getting two right here inside a console now the next thing
8:15:12
que quiero mostrarte es cómo vamos a asignar valores a nuestras propiedades de enum, así que solo vamos a usar el signo igual y soleado, también podemos usar como no sé nublado
which i want to show you is that how we are going to be assigning a values to our enum properties so we are going to be just using the equal to sign and sunny we can also use like i don't know cloudy
8:15:23
soleado y dinero y algo así, soleado nublado
sunny and money and something like that sunny cloudy
8:15:26
uh cl o nublado supongo que esto
uh cl or udy i guess this
8:15:29
es como se escribe, no estoy muy seguro de eso, pero ahora déjame escribir
is how you spell it i'm not quite sure about that but now let me just write
8:15:32
un lluvioso y voy a crear uno más para el
a rainy and i'm going to just create one more for the
8:15:35
nevado, está bien, nevado, yo
snowy okay snowy i
8:15:39
ni siquiera sé si esa es una palabra real o no, pero lo voy a proporcionar de todos modos y ejecutarlo, nos dará
don't even know if that's a real word or not but i'm going to just
8:15:42
un lluvioso aquí, ¿por qué es eso? porque actualmente estamos
provide it anyways and run that it's going to give us
8:15:45
accediendo al valor de lluvioso y lo estamos proporcionando aquí, así que
a rainy right here why is that because currently we
8:15:48
por eso ahora estamos obteniendo lluvioso, pero si solo quito
are accessing the value of rainy and we are providing it right here so
8:15:51
eso y guardo mi archivo y lo ejecuto y
that's why we are now getting rainy but if i just remove
8:15:54
nos dará soleado, soleado, nublado, nublado, lluvioso
that and save my file and run it and
8:15:57
lluvioso, nevado, nevado, está bien, así que nos dará
it's going to give us sunny sunny cloudy cloudy rainy
8:16:01
todas sus propiedades aquí, ahora lo que quiero
rainy snowy snowy okay so it's going to give us
8:16:04
todas sus propiedades justo aquí ahora lo que quiero
all of their properties right here now what i want
8:16:07
hacer es que quiero almacenar en algún tipo de variable como const actual o clima o algo así, así que la condición del clima y actualmente está nevando aquí
to do is i want to store in some sort of a variable like const current or weather or something like that so weather condition and currently it is snowy here
8:16:18
así que voy a especificar nevado justo aquí y voy a escribir constante
so i'm going to just specify snowy right here and i'm going to just write constant
8:16:21
registrar el clima actual uh
log the current weather uh
8:16:24
es y vamos a renderizar el clima actual justo aquí
is and let's just render the current weather right here
8:16:27
ahora déjame guardar eso y ejecutarlo y aquí puedes ver
now let me just save that and run that and here you can see
8:16:30
el clima actual es nevado aquí así que sí
the current weather is snowy right here so yep
8:16:33
eso fue enum y puedes proporcionar más funcionalidad loca que eso no es nada pero solo lo usamos para como constantes del mundo real aquí así que sí puedes volverte más loco que eso
that was enum and you can provide more crazy functionality than that it is nothing but we just use that for like a real world uh constants right here so yeah you can go crazier than that
8:16:47
aplicación en typescript no, solo estoy bromeando así que
application in typescript no i'm just kidding so
8:16:51
ahora aprendamos sobre clases en typescript pero una
now let's learn about classes in typescript but a
8:16:54
palabra de precaución si no conoces la programación orientada a objetos en javascript así que
word of caution if you don't know objective
8:16:57
no tienes que ver esta sección, quiero decir, si no te importa el
oriented programming in javascript so you
8:17:00
tipo de cosas de oop así que puedes saltarte completamente esta sección
don't have to watch this section i mean like if you don't care about the
8:17:03
ni siquiera tienes que preocuparte por todas las clases y todo
oop kind of stuff so you can totally skip this section
8:17:07
ese tipo de cosas, pero si te importa eso y si ya lo aprendiste, así que bien por ti y
you don't even have to worry about all of the classes and all
8:17:10
bienvenido a la sección si quieres aprender sobre oop tengo un curso completo allí, puedes consultar mi curso completo de javascript y tengo una sección completa sobre oop y la locura de oop
of that kind of stuff but if you do care about that and if you already learned that so good on you and
8:17:17
de todos modos, así que ahora entremos en las clases, así que asumo que ustedes
welcome to the section if you want to learn about oop i have an entire course on there you can check out my complete javascript course and i have an entire section about oop and craziness of oop
8:17:29
ya saben qué es una clase en javascript, no voy
anyway so now let's get into the classes so i'm assuming that you guys
8:17:32
ya sé qué es una clase en javascript, yo
already know what a classes is in javascript i'm
8:17:35
no voy a explicar qué es una clase, pero voy a explicar las clases desde el punto de vista de typescript de todos modos, así que propiedades de clases anotación, así que tú
not going to be explaining what a classes is but i'm going to be explaining the classes in the typescript point of view anyway so classes properties annotation so you
8:17:44
puedes anotar las propiedades de la clase con un tipo, esto te permite definir un tipo de dato de una propiedad
can annotate class properties with a type this allows you to define a data type of a property
8:17:49
y asegura que siempre sea consistente, así que así es como
and ensures that it is always consistent so this is how
8:17:52
se verá la sintaxis, así que aquí puedes ver que tenemos algún tipo de campo
the syntax will look like so here you can see we have some sort of a field
8:17:55
como nombre y también podemos anotar allí como para cadena y también tenemos como edad y podemos anotar allí con un número y incluso también podemos anotar estos nombres
like name and we can also annotate there like for string and we also have like edge and we can annotate there with a number and we can even also annotate these names
8:18:05
también aquí si quisieras, está bien, así que ese fue el básico
as well right here if you wanted to okay so that was the basic
8:18:08
ejemplo de anotación que también te voy a mostrar en un mundo real
annotation example which i'm going to also show you in a real world
8:18:11
ejemplo, pero sabes qué, quiero entrar en
example but you know what i want to get into
8:18:14
los modificadores, pero primero déjame escribir algo de código
the modifiers but you know first of all let me just write some code
8:18:17
entonces llegarás a lo que estoy hablando, así que ahora déjame simplemente quitarlos
then you will get to what i'm talking about so now let me just remove them
8:18:20
y voy a crear una clase aquí y yo
and i'm going to just create a class right here and i'm
8:18:24
voy a dar mi nombre como persona, voy a crear un nombre y
going to give my name of like person i'm going to create a name and
8:18:27
voy a proporcionar un tipo de cadena aquí, esto es totalmente simple
i'm going to provide a type of string right here this is totally simple
8:18:30
y fácil, solo tenemos que especificar los tipos en TypeScript, así que aquí puedes ver que lo configuré como número, también podemos proporcionar un campo aquí, así que ahora déjame escribir como
and easy we just have to specify the types in type script so here you can see i just set that to number we can also provide a field right here so now let me just write like
8:18:38
nombre y podemos cambiar el nombre de eso a como cadena, yo
name and we can change the name of that to like string i
8:18:41
quiero decir, como el tipo de eso a cadena y también podemos proporcionar un borde y
mean like the type of that to string and we can also provide an edge and
8:18:44
el borde se establecerá en número también, está bien, ahora déjame
the edge will be set to number as well okay now let
8:18:47
usar la palabra clave de este resultado y esto se establecerá ahora en nombre y
me just use the this result keyword and this will be now set to name and
8:18:51
también este punto borde se establecerá ahora en borde como
also this dot edge will be now set to edge as
8:18:54
bueno, ahora déjame crear una instancia rápida y simple de esto
well now let me just create a quick simple instance of this
8:18:57
clase aquí, déjame volver, voy a crear una persona y nueva persona y dentro de esta persona voy a dar
class right here let me just go back i'm going to just create a person and new person and inside this person i'm going to give
8:19:04
algún tipo de nombre como, uh, no sé, John estaría bien
some sort of a name like uh i don't know john would be fine
8:19:07
y él tendría como 20 años o algo así y si
and he would be like 20 years old or something like that and if
8:19:10
también registras allí en el archivo del servidor de la consola y ejecutas allí
you also log there to the console server file and run there
8:19:13
y aquí puedes ver que nos dará como persona, el
and here you can see it's going to give us like person the
8:19:16
nombre se establecerá en John y también el borde se establecerá en
name will be set to john and also the edge will be set to
8:19:19
20, aquí ya sabes todas esas cosas, pero solo tienes que
20 right here you already know all of that stuff but you just
8:19:22
especificar estos tipos para referirte aquí, está bien, así que eso es, ahora la siguiente cosa de la que quiero hablar contigo es que también puedes hacer que las propiedades sean de solo lectura, lo que ya aprendimos, pero ahora déjame mostrarte rápidamente una vez más.
have to specify these types to refer here okay so that's that now the next thing which i want to talk to you about is that you can also make the properties read only which we already learned but now let me just show you quickly once again.
8:19:34
Así que voy a escribir como solo lectura y ahí vamos.
So I'm going to just write like read only and there we go.
8:19:37
Así que podemos acceder totalmente a estas propiedades, pero no podemos cambiar el valor de estas propiedades aquí.
So we can totally access these properties, but we cannot change the value of these properties right here.
8:19:43
Así que si solo las guardo y si solo las ejecuto, obviamente vamos a obtener el mismo resultado aquí.
So if I just save them and if I just run it, so obviously we are going to be getting the same result right here.
8:19:48
Pero si intento cambiar el valor de eso a otra cosa, ya sabes lo que ya te mostré allí.
But if I try to like change the value of that to something else, you know what I already showed you there.
8:19:54
No quiero molestarme con eso una vez más. Así que simplemente eliminemos eso de aquí y ahí vamos. Así es como vamos a trabajar
I don't want to bother that once again. So let's just remove that from here and there we go. This is how we are going to be working
8:20:00
las clases en TypeScript, ahora hablemos de algo llamado modificadores
the classes in typescript now let's talk about something called modifiers
8:20:04
en TypeScript, así que ¿qué son los modificadores y por qué deberías preocuparte?
in typescript so what are modifiers and why you should care
8:20:07
por eso, así que en JavaScript no tenemos el
about that so in javascript we do not have the
8:20:10
concepto de modificadores, quiero decir que puedes lograr
concept of modifiers i mean like you can achieve
8:20:13
el mismo resultado como estas palabras clave que estoy a punto de mostrar
the same result like these keywords which i'm about to show
8:20:16
podemos usar eso, pero para eso tenemos que
you we can totally use that but for that we have to
8:20:19
realizar conceptos avanzados como cierres y también tenemos que usar encapsulación, polimorfismo y todas esas palabras grandes que ya discutí
perform advanced concepts like closures and we also have to use encapsulation polymorphism and all of their big words which i already discuss
8:20:28
en mi curso de javascript, si estás interesado y quieres
in my javascript course if you are interested and you want
8:20:31
revisarlo, así que siéntete libre de revisarlo, de todos modos, ¿qué
to check it out so feel free to check it out anyway so what
8:20:34
son los modificadores de acceso o simplemente modificadores, como quieras llamarlos
are access modifiers or just modifiers whatever you want to call
8:20:37
así que en TypeScript puedes usar los modificadores de acceso para controlar
that so in timescript you can use the access modifiers to control
8:20:41
la visibilidad de los miembros de la clase, propiedades y métodos
the visibility of class members properties and methods
8:20:44
ya sabes que el modificador de acceso determina la forma en que los miembros de la clase pueden ser accedidos desde dentro y fuera de la clase, así que, ¿cuántos modificadores de acceso tenemos?
you already know that access modifier determine the way in which class members can be accessed from within and outside the class so how many access modifiers do we have
8:20:55
Solo tenemos tres, al igual que en el lenguaje de programación Java.
We only have three, just like a Java programming language.
8:20:58
Si ya vienes de Java o tal vez si vienes de un entorno de C++, ya conoces todos estos modificadores.
If you're already coming from a Java or maybe if you're coming from a C++ background, so you already know all of these modifiers.
8:21:05
Pero de todos modos, hablemos de ello. Así que aquí puedes ver que solo tenemos estos tres modificadores. Así que el primero, tenemos un público.
But anyways, let's talk about it. So here you can see we have only these three modifiers. So the first one, we have a public.
8:21:12
El segundo, tenemos un privado. Y también tenemos uno protegido. Así que ahora discutamos cada uno de ellos uno por uno.
The second one, we have a private. And we have a protected one as well. So now let's just discuss each of them one by one.
8:21:18
Así que primero que nada, tenemos un modificador público. Así que público, como su nombre indica, selecciona miembros.
So first of all, we have a public modifiers. So public, as the name suggests, select members.
8:21:23
marcados como públicos pueden ser accedidos desde cualquier lugar, tanto
mark as a public can be accessed from anywhere both
8:21:27
dentro como fuera de la clase, pero
inside and outside in the class but
8:21:30
si hablas de un modificador privado, así que el modificador privado
if you talk about a private modifier so the private modifier
8:21:33
como miembro marcado como privado solo puede ser accedido
like member mark as a private can only be accessed
8:21:36
dentro de la clase en la que están definidos
within in the class they are defined
8:21:40
y no fuera. En este caso, puedes acceder a tu modificador tanto dentro como fuera, dentro de un público, pero por otro lado, si estás trabajando con un
in not outside in this case you can access your modifier both inside and outside inside a public but on the other hand if you are working with a
8:21:48
privado, solo puedes acceder a tu propiedad o
private so you can only access your property or
8:21:52
tu método dentro de la clase en la que están definidos en
your method inside the class in which they are defined in
8:21:55
pero no fuera. Pero ahora hablemos del protegido
but not outside but now let's talk about the protected
8:21:58
los miembros marcados como protegidos pueden ser accedidos desde
one members mark as protected can be accessed from
8:22:02
dentro de la clase en la que están definidos así como
within the class they are defined in as well as
8:22:05
cualquier subclase que extienda la clase, así que ya sabes sobre la palabra clave extends, así que si marcas un específico
any subclasses that extends the class so you already know about the extends result keyword so for if you mark a specific
8:22:13
propiedad o método utilizando un modificador protegido
property or method by using a protected modifier
8:22:17
así que solo pueden ser accesibles dentro de su específico
so they can be only accessible inside their specific
8:22:20
clase en la que están definidos y también cuando
class in which they are defined in and also when
8:22:24
extiendes una cierta clase y quieres usar eso, allí pueden
you extend a certain class and you want to use that there they
8:22:27
ser también accesibles, por otro lado, si estás trabajando con un
can be also accessible there on the other hand if you are working with a
8:22:30
privado, solo pueden ser accesibles dentro
private one they can only be accessible within
8:22:34
de la clase, pero no fuera de la clase, pero si estás trabajando con una clase pública, así que pueden ser accesibles donde quieras, así que sí, esa es la
the class but not outside from the class but if you are working with a public class so they can be accessed anywhere you want so yeah that's the
8:22:41
amor de TypeScript, así que cómo se verá eso ahora
love of typescript so how that's gonna look like now
8:22:45
déjame mostrarte que sé que esto es mucho código y no tienes
let me just show you that i know this is a lot of code and you don't
8:22:48
que preocuparte por eso, pero aquí puedes ver que podemos marcar nuestra propiedad por
even have to worry about that but here you can see we can mark our property by
8:22:51
proporcionando el modificador público, el privado o
either providing the public modifier the private or
8:22:54
el protegido aquí mismo, así que por público, puede
the protected one right here okay so by public it
8:22:57
ser accesible en cualquier lugar dentro de nuestro programa, pero si marcas que es privado, solo puede ser accesible dentro de esta clase animal aquí, pero si marcas este protegido
can be accessible anywhere inside our program but if you mark there is a private it can only be accessible inside this animal class right here but if you mark this protected one
8:23:09
puede ser accesible dentro del animal y también
it can be accessible inside the animal and also
8:23:12
si extendemos algún, uh, algún animal como un perro o algo
if we extend some uh some animal like dog or something
8:23:16
así, también puede ser accesible allí y
like that it can also be accessible there and
8:23:19
espero que tenga sentido, si no, sí, ahora
i hope that makes sense if it doesn't yeah now
8:23:22
déjame escribir un poco de código y luego sabrás de qué estoy hablando primero
let me just write some code and then you will get to know what i'm talking about first
8:23:26
de todo, déjame crear mi clase una vez más, así que estoy
of all let me just create my class once again so i'm
8:23:29
simplemente creando una clase, le voy a dar un nombre como bolso, maldita sea, persona una vez más, déjame poner un par de
going to just create a class i'm going to give a name of like purse come the hell man person once again let me just put a few
8:23:36
propiedades como el primer nombre que se establecerá en cadena y también
properties like first name will be set to string and also
8:23:39
tenemos una lista y se establecerá también en cadenas, ahora
we have a lost and it's going to be also set to strings as well now
8:23:43
déjame proporcionar mi primer y se va a igualar a cadena y
let me just provide my first and it's going to be equals to string and
8:23:46
voy a hacer eso público, así que si simplemente escribo público
i am going to make that as public so if i just write public
8:23:49
ahí vamos, ahora está funcionando y también voy a
there we go it is now working and i'm going to also
8:23:52
hacer esto público también, como para el último también, así que
make this one public as well like for the last one as well so
8:23:56
ahora dentro de ahí, lo que quiero hacer es que voy a usar este inicio primero y también este inicio perdido y ahora déjame crear una instancia de ellos, así que voy a volver y así es como vamos
now inside there what i want to do is that i'm going to just use this start first and also this start lost and now let me just create an instance of them so i'm going to go back and this is how we're going
8:24:05
a crear una instancia de ellos, como oh Dios mío, uh
to be creating an instance of them like oh my god uh
8:24:08
persona, sí, la persona está totalmente bien y
person yeah person is totally okay and
8:24:11
ahora déjame registrar ahí en la consola como p1 punto
now let me just log there to the console like p1 dot
8:24:15
no sé punto nombre aquí, así que ahora déjame
i don't know dot first name right here so now let me just
8:24:18
guardar ahí y aquí puedes ver que nos va a dar a John, ¿verdad?
save there and here you can see it's going to give us john right
8:24:21
aquí si intentas registrar el apellido, si solo escribes último
here if you try to log the last name if you just write last
8:24:24
archivo del servidor y ejecuta ahí, nos va a dar la masa
server file and run there it's going to give us the dough
8:24:28
aquí, lo que significa que es totalmente accesible aquí y ahora, si los hago, uh, privados aquí
right here which means like totally accessible right here and now if i make them uh private right here
8:24:34
si simplemente marco este como privado, si los guardo y aquí puedes ver si solo escribo primero
if i just mark this one as private if i save them and here you can see if i just write first
8:24:41
vamos al infierno, hombre, primero y si guardo ahí, ya va a
come the hell man first and if i save there it's gonna already
8:24:44
darnos este error, como que la propiedad primero es privada y solo
give us this error like property first is private and only
8:24:47
será accesible dentro de la clase persona, ¿verdad?
be accessible within the class person right
8:24:51
aquí en la que lo estamos creando, aquí está bien, así que déjame
here in which we are creating it right here okay so let
8:24:54
simplemente crear algún tipo de método, como no sé, obtener nombre, sí, eso es
me just create some sort of a method like i don't know get name yep that's
8:24:57
genial, así que voy a crear este obtener nombre, así que estamos escribiendo
cool so i'm gonna just create this get name so we are writing
8:25:01
una este punto primer nombre y también este punto apellido aquí
a this dot first name and also this dot last name right here
8:25:04
y también estamos anotando ahí, aquí está bien, así que lo que
and we are also annotating there right here okay so what
8:25:07
quiero hacer es entonces comenzar a escribir un obtener, uh, quiero decir, como en lugar
i want to do is then start of writing a get uh i mean like instead
8:25:10
de escribir un primero que no es accesible fuera
of writing a first which is not accessible outside
8:25:13
de esta persona aquí, pero ahora es totalmente accesible dentro de esta clase persona, así que aquí puedes ver que podemos tener acceso totalmente a
from this person right here but it is now totally accessible inside this person class so here you can see we can totally have access to
8:25:22
ahí, así que en lugar de escribir este primero, simplemente voy a copiar esto
there so instead of writing this first i'm going to just copy this
8:25:25
obtener nombre y déjame ponerlo aquí y ejecutarlo
get name and let me just put there right here and execute there
8:25:28
así que ahora, si guardo este archivo, ¿qué crees que será el resultado si
so now if i save this file so what do you think will be the result if
8:25:31
ejecuto este código, está bien, déjame quitar
i run this code okay let me just remove
8:25:35
eso y ejecutarlo una vez más, así que ahora estamos obteniendo john doe, lo que significa que todo está funcionando correctamente y solo podemos usar esta primera propiedad
that and run that once again so we are now getting john doe which means like everything is successfully working and we can only use this first property
8:25:46
que marcamos como privada solo dentro de esto
which we mark as a private only inside this
8:25:50
objeto persona aquí, déjame resaltar que
person object right here let me just highlight that we
8:25:53
solo podemos usar esta propiedad que está marcada como privada
can only use this property which is marked as a private
8:25:56
palabra clave solo dentro de esto
keyword only inside this
8:26:00
clase persona no fuera
person class not outside
8:26:04
de esta clase persona, está bien, así que esto
from this person class okay so this
8:26:08
es cómo estamos llegando allí de todos modos, así que eso fue sobre lo público y también sobre lo privado, así que ahora déjame cuadrar uno más para como
is how we are now getting there anyway so that was about for the public and also for the private as well so now let me just square one more for like
8:26:14
protegido, así que protegido y voy a especificar
protected so protected and i'm going to just specify
8:26:17
como borde o algo así y el borde se establecerá en número total
like edge or something like that and edge will be set to totally number
8:26:21
ahora déjame mostrarles qué va a hacer este protegido por nosotros
now let me just show them so what this protect is going to do for us
8:26:24
este protegido significa que podemos usar esto totalmente
this protected means like we can totally use this
8:26:27
propiedad dentro de esta persona aquí, no
property inside this person right here not
8:26:31
fuera de esta persona, pero si solo extiendes
outside from this person but if you just extend
8:26:35
o si tomamos la funcionalidad de esta persona a otra persona y creamos una instancia de eso, podemos acceder totalmente a ese borde
or if we borrow the functionality from this person to yet another person and we create an instance of that we can totally access that edge
8:26:42
ahí, así que lo que quiero hacer es que aquí voy a escribir
there okay so what i want to do is that here i'm going to just write
8:26:45
como borde y voy a establecer eso en
like edge and i'm going to just set that to
8:26:48
um borde aquí, oh, ya sabes, en esto
um edge right here oh you know on this
8:26:51
comenzar borde, más bien, así que va a funcionar totalmente y no
start edge rather okay so it's going to totally work and it's
8:26:54
nos va a dar ningún error aquí, pero si intentas proporcionar algún tipo
not going to give us any errors right here but if you try to provide some sort
8:26:58
de un número aquí, como 20 en este caso, así que es
of a number right here like 20 in this case so it is
8:27:01
nos va a dar este error como dos argumentos inesperados, pero obtuvimos tres, oh, eso es porque tenemos que registrar eso de todos modos, pero entiendes la idea
going to give us this error like unexpected two arguments but got three oh that's because we have to register that anyways but you get the idea
8:27:10
como que nos dará ese error justo aquí, así que ahora tú
like it will give us that error right here so now you
8:27:13
entiendes la idea como que podemos acceder totalmente a este borde de inicio dentro
get the idea like we can totally access this start edge inside
8:27:16
esta persona y también podemos acceder a ella creando
this person and we can also access it by creating
8:27:20
algún tipo de instancia justo aquí y ahora déjame crear algún tipo de un
some sort of instance right here and now let me just create some sort of a
8:27:23
usuario como clase y luego solo voy a crearme
user like class and then i'm going to just create myself
8:27:26
justo aquí oh sabes qué, un humano esto
right here oh you know what a human this
8:27:30
uno debería ser humano, este debería ser humano, así que solo voy a seleccionar eso, presionar ctrl d y solo voy a cambiar eso a humano y este
one should be human this one should be human so i'm going to just select that hit ctrl d and i'm going to just change that to human and this one
8:27:38
debería ser yo mismo o persona más bien, estoy
should be myself or person rather i'm
8:27:41
a punto de crear una persona y vamos a extender, lo que significa que
going to just create a person and we are going to be extending which means like
8:27:44
vamos a estar tomando la funcionalidad de este
we are going to be borrowing the functionality from this
8:27:47
humano justo aquí y vamos a proporcionarlo justo aquí, así que
human right here and we are going to be providing it right here so
8:27:50
vamos a obtener la funcionalidad del humano y
we are going to be getting the functionality from the human and
8:27:54
así es como se ve y solo necesitamos esta funcionalidad justo aquí, así que tenemos un nombre, tenemos un apellido y tenemos cada cosa aquí y también podemos usar este borde justo aquí, así que supongamos que si solo creo algún tipo de
this is how it looks like and we just only need this functionality right here so we have a first name we have a last name and we have every single thing right here and we can also use this edge right here so let's suppose if i just create some sort of
8:28:06
sabes, déjame borrar eso de aquí, también voy a borrar este
you know let me just delete that from here i'm going to also delete this one
8:28:09
de aquí, déjame volver y solo voy a crear
from here let me just go back and i'm going to just create
8:28:12
una instancia de esta persona justo aquí, no un humano, sino
an instance of this person right here not a human but
8:28:15
una persona, así que solo voy a escribir como cost hosan y
a person so i'm going to just write like cost hosan and
8:28:19
va a ser igual a persona y tenemos que especificar el primero
it's going to be equals to person and we have to specify the first
8:28:22
nombre, así que solo voy a escribir como hosan para el primer nombre
name so i'm going to just write like hosan for the first name
8:28:25
oh, olvidamos incluir la nueva palabra clave de resultado, uh, ¿por qué estamos obteniendo este error? uh, oh, ahí vamos
oh we forgot to include the new result keyword uh why are we getting this error uh oh there we go
8:28:33
acepta tres parámetros, así que tenemos que especificar para
it accepts three parameters so we have to specify for
8:28:36
el último como web dev y también voy a especificar
the last one like web dev and i'm going to also specify
8:28:39
uno para el borde, así que que se establece en el número i
one for the edge so which is set to number i
8:28:43
tengo 20 años y ahí vamos, ahora somos totalmente capaces
am 20 years old and there we go we are now totally able
8:28:46
de acceder a esta propiedad que está configurada como protegida dentro
to access this property which is set to protected inside
8:28:50
esta clase extendida aquí así que ahora déjame solo registrar allí en la consola así que voy a usar como hosan guardar este archivo
this extended class right here so now let me just log there to the console so i'm going to just use like hosan save this file
8:28:56
y ejecutar eso así que ahora estamos oh maldita sea dónde en el mundo está alguien obteniendo el error
and run that so we are now oh god damn it where in the world is anyone getting the error
8:29:03
uh la propiedad edge no tiene inicializador
uh property edge has no initializer
8:29:06
y no está definitivamente asignada en el constructor sí, tienes razón
and not definitely assigned in the constructor yep you're
8:29:09
totalmente cierto hermano déjame solo asignar
totally right brother let me just assign
8:29:12
eso aquí voy a solo poner una coma y estoy
that right here i'm going to just put a comma and i'm
8:29:16
voy a usar como edge y edge se va a establecer en
going to just use like edge and edge is going to be set to
8:29:19
número aquí y vamos a duplicar eso y
number right here and let's duplicate that and
8:29:23
voy a solo establecer eso no número pero ahora va a
i'm going to just set that not number but now it's going
8:29:26
establecerse en uh edge aquí voy a también copiar
to set to uh edge right here i'm going to also copy
8:29:29
este edge y olvidé hacer eso así que voy a solo eliminar este edge de
this edge and i forgot to do that so i'm going to just remove this edge from
8:29:32
aquí y voy a solo especificarlo aquí para
here and i'm going to just specify it right here for
8:29:35
el edge y ahora déjame solo ejecutar eso y aquí puedes ver
the edge and now let me just run that and here you can see
8:29:38
ahora estamos obteniendo el nombre de pila de la persona que se establecerá en hosan el apellido se establecerá en web dev y también el edge se establecerá en 20 y eso es todo bebé eso fue
we are now getting the person first name will be now set to hosan the last name will be set to web dev and also the edge will be set to 20 and that's it baby that was
8:29:47
sobre los modificadores y también para estas anotaciones en clases.
about for the modifiers and also for these annotations in classes.
8:29:53
Está bien, así que sí, supongo que solo queda un tema que se llama los getters y setters.
Okay, so yeah, I guess there is only one topic left which is called the getters and setters.
8:29:58
Sí, ahora solo discutamos los getters y setters y eso sería todo para la sección de OOP de TypeScript.
Yeah, now let's just discuss the getters and setters and that would be it for the OOP section of TypeScript.
8:30:03
Entonces, ¿qué son los getters y setters y por qué deberías preocuparte por ellos?
So what is a getters and setters and why you should care about them.
8:30:06
Los getters y setters se utilizan para acceder y modificar
So getters and setters are used to access and modify
8:30:09
las propiedades de clase y los getters y setters te permiten definir una propiedad en una clase que parece una variable simple pero internamente tiene lógica adicional para obtener y establecer el valor.
class properties and getters and setters allow you to define a property in a class that looks like a simple variable but internally has additional logic for getting and setting the value.
8:30:20
Está bien, así que cómo se verá eso. Así que aquí puedes ver que tenemos una clase y tenemos esta
Okay so how that's going to look like. So here you can see we have a class and we have this
8:30:24
propiedad privada que actualmente está establecida en cero y luego
private property which is currently set to zero and then
8:30:27
podemos solo especificar esta palabra clave get result para obtener el específico
we can just specify this get result keyword to get the specific
8:30:30
propiedad y también podemos usar el set y para establecer
property and we can also use the set and to set
8:30:33
la lógica específica dentro de allí está bien así que no vamos a hacer nada loco así que ahora déjame solo mostrarte eso rápidamente así que
the specific logic inside there okay so we're not going
8:30:36
no vamos a hacer nada loco, así que ahora déjame mostrarte eso rápidamente
to do anything crazy so now let me just show you that totally quickly so
8:30:40
lo que quiero hacer es que primero voy a crear mi clase
what i want to do is that first of all i'm going to just create my class
8:30:44
voy a darle un nombre como mi clase, puedes darle cualquier nombre que quieras, no voy a proporcionar ninguno
i'm going to give a name of like my class baby you can give any class you want i'm not going to be providing any
8:30:50
perímetro recto, pero ahora déjame hacer esta primera propiedad como
perimeter straight but now let me just make this first property as
8:30:53
privada y que será mi propiedad
private and which will be my property
8:30:57
estaría bien y solo voy a anotar eso
would be fine and i'm going to just annotate that
8:31:00
como un número porque vamos a proporcionar el valor inicial del número, ¿verdad?
as a number because we are going to be providing the initial value of number right
8:31:03
aquí para el constructor no quiero escribir ni siquiera el constructor, así que ahora déjame quitar eso, déjame guardar eso, pero debajo de esta propiedad vamos a crear nuestro método get y voy a decir como mi
here for the constructor i don't want to write even the constructor so now let me just remove that let me just save that but underneath this property we are going to be just creating our get method and i'm going to just say like my
8:31:14
propiedad, vamos, mi p r o
proper come on my p r o
8:31:17
p r t y y ahora déjame anotar
p r t y and now let me just annotate
8:31:20
ahí con un número y voy a devolver este punto mi propiedad
there with a number and i'm going to just return this dot my property
8:31:23
que ahora está inicialmente configurada en cero y estamos
which is now initially set to zero and we are
8:31:26
proporcionándolo y estamos proporcionando un tipo de número a eso
providing it and we are providing a type of number to it
8:31:29
así que así es como vamos a obtener algo, ahora aprendamos sobre un setter
so this is how we are going to be getting something now let's learn about a setter
8:31:33
ok, así que voy a escribir una palabra clave set result y mi propiedad va a tomar un valor y el valor debe ser un número y dentro de eso solo estamos configurando
okay so i'm going to just write a set result keyword and my property it's going to take a value and the value should be a number and inside there we are just setting
8:31:40
esta propiedad así, comienza mi propiedad y estamos proporcionando su
this property like this start my property and we are providing their
8:31:43
valor a eso, ok, así que ahora déjame crear una instancia de
value to it okay so now let me just create an instance of
8:31:47
eso, ahora déjame guardar eso e ir atrás y crear una instancia rápida de
that now let me just save there and go back and create a quick instance of
8:31:50
eso, así que voy a usar como const mi instancia, puedes darle cualquier nombre que quieras, pero el nombre no importa, así que mi clase
that so i'm going to just use like const my instance you
8:31:53
y vamos a crear una instancia de eso y ya usamos los getters y setters, pero voy a registrar eso en la consola, así que como valor actual, vamos
can give any name you want but the naming doesn't matter so my class
8:31:57
valor actual, uh y aquí solo tenemos
and let's just create an instance of that and we already use the getters and setters but i'm going to just log there to the console so like current value come on
8:32:05
usar como mi instancia punto mi propiedad
current value uh and here we just have
8:32:08
justo aquí, ok, así que solo tenemos que usar eso, ahora déjame
to use like my instance dot my property
8:32:12
guardar eso y vamos a ejecutar eso justo aquí, así que
right here okay so we just have to only use that now let me just
8:32:15
aquí puedes ver que ahora estamos obteniendo estos datos que están actualmente
save that and let's just run that right here so
8:32:18
aquí puedes ver que ahora estamos obteniendo estos datos que actualmente
here you can see we're now getting this data which is currently
8:32:21
están configurados como privados, pero ahora estamos obteniendo estos datos utilizando esto
set to private but we're now getting this data by using this
8:32:25
función que acabamos de crear aquí, así que ahora si quieres asignar un valor a eso, ¿cómo puedes hacerlo? Y eso es totalmente fácil también, nosotros
function which we just created right here okay so now if you want to assign a value to that so how can you go about doing that and that's totally easy as well we
8:32:33
no tenemos que hacer nada, solo tenemos que escribir como mi instancia punto
we don't have to do nothing but we just have to write like my instance dot
8:32:36
mi propiedad, solo tenemos que acceder a esta propiedad que tenemos
my property we just have to access this property which we have
8:32:39
aquí y también tenemos que especificar algún tipo de número
right here and also we have to specify some sort of a number
8:32:43
como no sé, tal vez 10 estaría bien y así es como vamos
like i don't know maybe 10 would be fine and this is how we're going
8:32:46
a estar asignando un número y ahora déjame solo registrar allí en la consola como ah
to be assigning a number and now let me just log there to the console like ah
8:32:49
simplemente cortemos eso, cortemos esa copia
let's just cut that cut that copy
8:32:52
esta y ponla aquí y ahora dejemos
this one and put it right here and now let
8:32:55
que guarde allí y ejecute allí, inicialmente se configurará en cero y ahora estamos cambiando allí o estamos estableciendo un nuevo valor allí
me just save there and run there initially it's going to be set to zero and now we are changing there or we are setting a new value to there
8:33:02
así que por eso ahora estamos obteniendo este 10 aquí y
so that's why we are now getting this 10 right here and
8:33:05
sí, eso fue todo sobre la sección de OOP para
yep that was it about the oop section for
8:33:08
el typescript y espero que lo hayas disfrutado, ahora aprendamos
the typescript and i hope you enjoyed it now let's learn
8:33:11
sobre interfaces en typescript, así que ahora hablemos de
about interfaces in typescript so now let's talk about
8:33:14
uno de mis temas favoritos en typescript que se llama interfaz
one of my favorite topic in typescript which is called interface
8:33:18
así que qué en el mundo son las interfaces y por qué deberías preocuparte por ellas, así que la interfaz es una forma de definir un contrato para una forma de un objeto, especifica las propiedades y sus tipos que un objeto
so what in the world on interfaces and why you should care about them so interface is a way to define a contract for a shape of an object it specifies the properties and their types that an object
8:33:29
debe tener y la palabra clave es debe tener
must have and the keyword is must have
8:33:32
las interfaces son herramientas poderosas para hacer cumplir una
interfaces are powerful tools for enforcing a
8:33:35
cierta estructura en tu código, así que cómo en el mundo vamos
certain structure in your code so how in the world we are going
8:33:38
a estar creando una interfaz y cómo todo eso funciona, está bien
to be creating an interface and how all of that works okay
8:33:42
como sí, sé que eso es un montón de palabrería que acabo de decir
like yeah I know that's a lot of gibberish which I just said
8:33:45
como cómo en el mundo vamos a estar creando una interfaz y
like how in the world we are going to be creating an interface and
8:33:48
cómo todo eso funciona, así que así es como estamos
how all of that works so this is how we are
8:33:51
definiendo una interfaz, así que primero que todo solo tenemos que escribir una palabra clave de interfaz resultado, luego tenemos que dar algún tipo de nombre para nuestra interfaz, luego tenemos
going to be defining an interface so first of all we have to just write an interface result keyword then we have to give some sort of a name for or interface then we
8:33:58
tenemos que especificar las propiedades y sus tipos y ahí
have to specify the properties and their types and there we
8:34:01
vamos, también podemos definir los métodos que vamos a estar
go we can also define the methods which we are going to be
8:34:04
también discutiendo en unos segundos y si quieres usar la interfaz
also discussing in a few seconds and if you want to use the interface
8:34:08
solo tienes que anotar eso aquí y luego tienes
you just have to annotate that right here and then you have
8:34:11
que especificar todas las propiedades que actualmente esta
to specify all of the properties which currently this
8:34:14
interfaz tiene, así que tenemos nombre, apellido y edad y ahora estamos proporcionando el nombre, apellido y edad aquí, así que esa fue nuestra interfaz básica, pero no es todo
interface has okay so we have first name last name and age and we are now providing the first name last name and age right here so that was our basic interface but that's not it
8:34:25
mientras que las interfaces se utilizan comúnmente para definir la estructura de los objetos
while interfaces are commonly used to define the structure of objects
8:34:29
no se limitan solo a los objetos, las interfaces
they are not limited to just objects interfaces
8:34:32
en TypeScript también se pueden usar para describir la forma
in typescript can be also used for describing the shape
8:34:35
de funciones y también de clases, así que
of a functions and also a classes as well so
8:34:38
vamos a estar usando interfaces tanto para las funciones como para las clases
we are going to be using interfaces for both the functions classes
8:34:41
y también para los objetos, así que ahora
and also for the objects as well so now
8:34:44
hablemos de eso, así que si quieres crear una interfaz para una
let's talk about it so if you want to create an interface for a
8:34:47
función, así es como lo vas a hacer, está bien, así que aquí puedes ver que solo tienes que crear una interfaz, la sintaxis será totalmente la misma, pero si quieres crear algún tipo de estructura para una función.
function so this is how you are going to be doing that okay so here you can see you just have to create an interface like the syntax will be totally the same but if you want to create some sort of a structure for a function.
8:34:57
Así que solo tienes que crear esa estructura aquí. Como en este caso, tomará dos parámetros como X y también Y, y ambos serán números.
So you just have to create that structure right here. Like in this case, it will take a two parameter like X and also the Y and both of them will be number.
8:35:05
Y el tipo de retorno también será un número. Está bien, así es como lo vamos a hacer.
And the return type will be also a number. Okay, so this is how we are going to be doing that.
8:35:08
Aquí puedes ver que tenemos una función de suma y la función de flecha de suma aquí.
Here you can see we have an add function and the add arrow function right here.
8:35:13
Y estamos proporcionando nuestra llamada de interfaz aquí como operación matemática.
And we are providing our interface call right here like math operation.
8:35:17
Ahora estamos proporcionando este X y también el Y. Así que tenemos que especificar eso aquí.
We are now providing this X and also the Y. So we have to specify there right here.
8:35:23
y va a tomar el a y también el b y solo estamos sumando ahí
and it's going to take the a and also the b and we are just adding there
8:35:26
aquí y también podemos usarlo para la resta y
right here and we can also use for the subcrank and
8:35:29
podemos registrar los valores, como para la suma lo vamos a estar usando
we can log the values like for the add we are going to be using it
8:35:32
así y también para la resta podemos proporcionar diferentes
like this and also for subcrank we can also provide different
8:35:35
tipos de valores aquí, sé que suena confuso, como oh Dios mío
kind of values right here i know that sounds confusing like oh my god
8:35:38
solo nos estás mostrando la presentación de diapositivas de algún código, sí yo
you are just showing us the slide show some code yeah i
8:35:41
voy a mostrarte un código en unos segundos, pero primero déjame explicar todas esas cosas en las diapositivas, luego vamos a saltar al código, está bien, así es como
am going to show you a code in a few seconds but first of all let me just explain all of that stuff in the slides then we are going to be jumping into the code okay so this is how
8:35:51
vamos a usar interfaces para una clase, así que aquí puedes ver que tenemos
we are going to be using interfaces for a class so here you can see we have
8:35:54
interfaces y como dije, también podemos proporcionar
interfaces and as i said that we can also provide
8:35:58
un método para eso, así que tenemos una interfaz de vehículo, ¿verdad?
a method for that so we have a vehicle interface right
8:36:01
aquí y como métodos tenemos un inicio y va a
here and as a methods we have a start and it's going to
8:36:04
tomar un amplio porque ni siquiera estamos devolviendo algo de allí y
take wide because we're not even returning something from there and
8:36:07
también tenemos una parada, así que también vamos a anotar allí como un porque tampoco estamos devolviendo algo de allí y aquí puedes ver que vamos a
we also have a stop so we are going to be also annotating there as a because we are also not returning something from there and here you can see we are going to be
8:36:15
usar los implements, está bien, no extends
using the implements okay not extends
8:36:18
sino implements aquí, así que va a implementar la
but implements right here so it's going to implement the
8:36:22
interfaz de vehículo aquí y luego podemos definir i
vehicle interface right here and then we can define i
8:36:25
quiero decir, entonces deberíamos definir el inicio y también la parada
mean like then we should define the start and also the stop
8:36:28
porque tenemos que especificar estas propiedades que actualmente
because we have to specify these properties which are currently
8:36:31
están disponibles para esta interfaz, así que tenemos un inicio y también tenemos
available for this interface so we have a start and we also have
8:36:34
una parada y podemos usarlo así, así que así es como vamos a usar interfaces y tenemos otro tema que se llama
a stop and we can use it like that so this is how we are going to be using interfaces and we have yet another topic which is called
8:36:41
declaración y fusión, voy a discutir eso en unos segundos
declaration and merging i'm going to discuss that in a few seconds
8:36:45
pero primero, ahora vamos a crear una interfaz, la interfaz básica
but first of all now let's just create an interface the basic interface
8:36:48
cómo funciona esto y también vamos a crearla para un
how this works and we're going to be also creating it for a
8:36:51
función y también para la clase, y luego vamos
function and also for the class as well and then we
8:36:54
a saltar a la declaración y fusión, así que
are going to be jumping into the declaration and merging so
8:36:58
voy a seleccionar todo y voy a eliminar eso y definamos nuestra primera interfaz aquí, así que voy a crear una interfaz y la interfaz es una palabra reservada
i'm going to select everything and i'm going to delete that and let's just define our first interface right here so i'm going to just create an interface and interface is a reserved
8:37:06
que significa que tiene algún tipo de significado especial dentro de TypeScript y voy a crear una interfaz simple para computadora.
keyword which means like it has some sort of a special meaning inside a TypeScript and I'm going to just create a simple interface for computer.
8:37:14
La computadora va a tener algún tipo de nombre y también va a tener algún tipo de RAM y la RAM se establecerá en número.
The computer is going to have some sort of a name and it's going to also have some sort of a RAM and the RAM will be set to number.
8:37:20
También voy a proporcionar el disco duro y también se establecerá en número, y ahora, si quieres usar esta interfaz que acabamos de crear aquí, ¿cómo puedes hacerlo?
I'm going to also provide the hard disk drive and it's going to be also set to number as well and now if you want to use this interface which we just created right here so how can you go about doing that?
8:37:31
Primero, vamos a usar eso con un objeto, luego vamos a saltar a
First of all we are going to be using that with an object then we are going to be jumping into
8:37:36
las funciones y todo ese tipo de cosas, así que ahora déjame crear
the functions and all of that kind of stuff so now let me just create
8:37:39
como ejemplo de computadora coma ex
like computer example comma ex
8:37:42
un ejemplo y aquí solo tenemos
a mple and here we just have
8:37:45
especificar el nombre de su interfaz justo aquí, ahí vamos
to specify their interface name right here there we go
8:37:48
solo tenemos que escribir el nombre de la interfaz que estamos declarando
we just have to write the interface name which we are declaring
8:37:51
justo aquí y solo tenemos que especificar justo aquí y también
it right here and we just have to specify right here and we
8:37:54
tenemos que proporcionar el signo igual, ahora nos dará un error instantáneamente y va a decir como sí, tienes que proporcionar el nombre, también tienes que proporcionar el
also have to provide the equal to sign now it will instantly gives us an error and it's going to say like yeah you have to provide the name you also have to provide the
8:38:02
ram y también el disco duro, así que podemos
ram and also the hard disk drive as well so we
8:38:05
proporcionar un nombre y el nombre será como no sé, i7 o
can provide a name and the name will be like i don't know i7 or
8:38:09
algo así y también voy a proporcionar la ram y la ram
something like that and i'm going to also provide the ram and the ram
8:38:12
será de 8 gigabytes y el disco duro será i
will be 8 gigabytes and the hard disk drive will be i
8:38:15
no sé, 100 gigabytes o algo así, ahora déjame volver y ahora déjame registrar todos estos valores aquí, así que solo voy a usar como
don't know 100 gigabytes or something like that now let me just go back and now let me just log all of these values right here so i'm going to just use like
8:38:23
computadora uh vamos, ven oh el
computer uh come on come oh the
8:38:26
nombre es ah examen de computadora
name is ah computer exam
8:38:29
examen oh ahí estamos
exam oh there we
8:38:32
vamos ahora déjame solo copiar eso y ponerlo justo aquí y
go now let me just copy that and put that right here and
8:38:35
voy a acceder al nombre así que ahora déjame acceder al nombre
i'm gonna just access the name so now let me just access the name
8:38:38
y ejecutar eso así que nos va a dar el i7
and run that so it's gonna gives us the i7
8:38:41
justo aquí voy a duplicar eso múltiples veces así que solo voy a cambiar eso a ram también voy a cambiar este a disco duro
right here i'm gonna duplicate that multiple times so i'm gonna just change that to ram i'm gonna also change this one to hard disk
8:38:48
ok no 3ds sino 2ds
drive okay not 3ds but 2ds
8:38:52
así que ahora déjame guardar ahí y aquí puedes ver que nos va a dar
so now let me just save there and here you can see it's gonna gives us
8:38:55
el i7 y también 100 y
the i7 and and also 100 and
8:38:58
todo está funcionando totalmente y así es como vamos
everything is totally working and this is how we are going
8:39:01
a definir la interfaz así es como vamos a usar
to be defining the interface this is how we are going to be using
8:39:04
la interfaz justo aquí así que ese fue el primer ejemplo ahora déjame
the interface right here so that was the first example now let
8:39:07
darte un ejemplo más de interfaz porque las interfaces son supremamente
me just give you one more example of interface because interfaces are supremely
8:39:12
importante aquí, así que ahora déjame darte el ejemplo de la película, está bien, así que voy a
important right here so now let me just give you the example of movie okay so i'm gonna
8:39:17
proporcionar algún tipo de nombre para la película, puedes dar un título si quieres y voy a anotar eso con una cadena, también voy a proporcionar algún tipo de arreglo, vamos, r-a-t-i-n-g-s
just provide some sort of a name for the movie you can give a title if you want and I'm going to annotate that with a string I'm going to also provide some sort of array come on r-a-t-i-n-g-s
8:39:28
y las calificaciones también se establecerán en número y también voy a especificar el
and ratings will be also set to number and I'm going to also specify the
8:39:31
género y el género también se establecerá en cadena
genre and genre will be also set to string
8:39:34
pero lo que quiero mostrarte son algunas cosas que
but what I want to show you is a few things we
8:39:37
también podemos hacer que una cierta propiedad sea de solo lectura, como supongamos que quieres cambiar no la calificación, sino supongamos que si
can also make a certain property read only like let's suppose if you want to just change the not rating but let's suppose if you
8:39:45
quieres hacer que el nombre sea totalmente de solo lectura y para este momento ya sabes lo que significa solo lectura, así que solo puedes especificar esta palabra clave reservada de solo lectura y va a hacer que esta propiedad
want to just make the name totally read only and by now you already know what a read only means so you can just specify this read only reserved keyword and it's going to make this property
8:39:55
sea totalmente de solo lectura aquí y también podemos usar este signo de interrogación
totally read only right here and we can also use this question mark
8:40:00
que ya discutimos, la propiedad opcional o la propiedad de encadenamiento opcional, lo que quieras llamarlo.
which we already discussed, the optional property or optional chaining property, whatever you want to call that.
8:40:05
Así que va a hacer que esta propiedad sea totalmente opcional. Como si quieres proporcionar esta propiedad de género, puedes hacerlo totalmente.
So it's going to make this property totally optional. Like if you want to provide this genre property, you totally can.
8:40:10
Si no quieres proporcionarlo, no tienes que hacerlo. Está bien, así que ahora déjame crear algún tipo de, no sé, película uno.
If you don't want to provide it, you don't have to. Okay, so now let me just create some sort of like, I don't know, movie one.
8:40:17
Y va a ser igual a esta interfaz de película, que ya creamos. Y dentro de eso, solo vamos a especificar el nombre de Star Wars.
And it's going to be equals to this movie interface, which we already created. And inside there, we're going to be just specifying like the name of Star Wars.
8:40:24
Las calificaciones serán 8.9 y el género se establecerá en acción aquí. Está bien, así que sí.
The ratings will be 8.9 and genre will be set to action right here. Okay, so yeah.
8:40:30
ahora voy a volver y solo voy a registrar en la consola como
now i'm going to go back and i'm going to just log to the console like
8:40:33
uh no sé, película uno y ahora déjame
uh i don't know movie one and now let
8:40:36
simplemente guardar eso y aquí nos va a dar todas sus
me just save that and here it's going to give us all of their
8:40:39
propiedades que actualmente tiene esta película, pero supongamos que quiero acceder al nombre, si solo escribo un nombre
properties which currently this movie have but let's suppose if i want to access like the name if i just write a name
8:40:46
enviar mi archivo, obviamente nos va a dar el nombre, nos va a dar
send my file it's going to obviously give us the name it's going to give
8:40:49
Star Wars, ahora déjame simplemente eliminar eso, pero si trato de cambiar el valor de eso a otra película o
us star wars now let me just remove that but if i try to uh rechange the value of that to like uh some other movie or
8:40:58
algo así, ¿qué estamos obteniendo? Ahora estamos obteniendo
something like that so what are we getting we are now getting
8:41:01
el error no se puede asignar a un nombre porque es una propiedad de solo lectura
the error cannot assign to a name because it is a read
8:41:04
no puedes cambiar eso porque lo
only property you cannot change that because we
8:41:07
marcamos como de solo lectura, así que no puedes cambiar el valor de
mark that as a read only so you cannot change the value of
8:41:10
eso, está bien, así que también tienes que tener eso en cuenta, supongamos
that okay so you also have to keep that in mind let's
8:41:13
que si no quieres proporcionar este género, voy a cortar eso de aquí y no está pasando nada aquí, como todo está bien, pero supongamos que si simplemente elimino este signo de interrogación de allí
suppose if you don't want to provide this genre i'm gonna cut that from here and nothing is happening right here like everything is a okay but let's suppose if i just remove this question mark from there
8:41:23
y ahora estamos obteniendo este error genial aquí, está bien
and we are now getting this cool error right here okay
8:41:27
así que sí, esos fueron los conceptos básicos de las interfaces ahora
so yeah that was the basics of interfaces now
8:41:31
creemos interfaces para nuestras funciones, voy a crear un
let's create interfaces for our functions i'm going to create an
8:41:34
interface aquí, darle un nombre como operación matemática
interface right here give a name of like math operation
8:41:37
o algo así y dentro de eso vamos a estar creando
or something like that and inside there we're going to be just creating
8:41:40
la firma aquí, así que x va a ser un número
the signature right here so x is going to be a number
8:41:43
y también y va a ser un número y también vamos a proporcionar un tipo de retorno de número, y ahí vamos
and also the y is going to be a number and we are going to be also providing a return type of number as well and there we go
8:41:50
ahora déjame usar eso aquí, así que supongamos que tenemos una función de suma y
now let me just use that right here so let's suppose we have an add function and
8:41:53
queremos proporcionar esas mismas operaciones matemáticas aquí
we want to provide that same math operations right here
8:41:56
y también vamos a proporcionar el a y
and also we are going to be providing the a and
8:42:00
también el y y vamos a estar usando como a más b
also the y and we're going to be just using like a plus b
8:42:03
oh, no a más y, sino a más b, más bien
oh not a plus y but a plus b rather i
8:42:06
olvidé proporcionar este b aquí, está bien
forgot to provide this b right here okay
8:42:09
¿qué demonios estoy haciendo? y ahora déjame registrar eso
what the hell am i doing and now let me just log there
8:42:12
en la consola como suma 2, coma 2
to the console like add 2 comma 2
8:42:15
o algo así, ahora déjame guardar eso y ejecutar mi archivo, así que
or something like that now let me just save there and run my file so
8:42:19
va a darnos el total aquí, ¿por qué? porque
it's going gives us full right here why is that because
8:42:22
todo está funcionando correctamente, por eso si paso el ratón
everything is successfully working that's why if i hover
8:42:25
mi ratón sobre eso, así que aquí puedes ver que nos va a dar como matemáticas
my mouse over to it so here you can see it's going to give us like math
8:42:28
la operación y el valor de x está establecido en número y
operation and the x value is set to number and
8:42:31
también el valor de y está establecido en número y el valor de retorno
also the y value is set to number and the return value
8:42:34
también está establecido en número, así que todo está bien, así que
is also set to number so everything is okay so
8:42:37
supongamos que quieres crear uno para la resta, así que voy a escribir como restar, bebé, y en lugar de escribir este símbolo de más, voy a
let's suppose if you want to create one for the subtract so i'm going to just write like subtract baby and instead of writing this plus symbol i'm going to
8:42:45
simplemente cambiar eso por el símbolo de menos, déjame duplicar eso
just change that to minus symbol let me just duplicate that
8:42:48
y voy a simplemente quitar 10 de 20 o
and i'm gonna just remove 10 from 20 or
8:42:52
algo así déjame guardar eso así que nos va a dar 10
something like that let me just save that so it's gonna give us 10
8:42:55
ah estamos agregando eso estamos agregando
ah we are adding that we are adding
8:42:58
eso oh eso es porque todavía estamos usando agregar tenemos que
that oh that's because we are still using add we have to
8:43:01
copiar el suscribirse y ponerlo aquí guardar mi archivo y
copy the subscribe and put it right here save my file and
8:43:04
ejecutar eso así que aquí puedes ver que nos va a dar menos 4
run that so here you can see it's gonna give us minus 4
8:43:08
lo cual no es correcto oh estamos haciendo lo contrario de todos modos así que no importa pero así es como
which is not correct oh we are doing the other way around anyway so it doesn't even matter but this is how
8:43:14
vamos a crear una interfaz y así es como vamos a usar eso
we are going to be creating an interface and this is how we are going to be using that
8:43:17
dentro de una función así que ahora aprendamos sobre interfaces con
inside a function so now let's learn about interfaces with
8:43:21
métodos así que también podemos especificar los métodos dentro de un
methods so we can also specify the methods inside an
8:43:24
interfaz así que podemos crear una interfaz de persona justo aquí estoy
interface so we can just create a person interface right here i'm
8:43:27
a proporcionar un nombre y el nombre se establecerá en cadena
going to provide a first name and the first name will be set to string
8:43:30
el apellido también se establecerá en cadena y también voy a especificar que la edad se establecerá en número y decir hola esta persona será
the last name will be also set to string and i'm going to also specify the edge will be set to number and say hello this person will be
8:43:38
también capaz de decir hola justo aquí y no vamos a devolver nada así que por eso tenemos que
also able to say hello right here and we're not going to be returning anything so that's why we
8:43:43
establecerlo en blanco así que ahora déjame crear una función que voy a
have to set there to white so now let me just create a function i'm going
8:43:46
dar un nombre como saludar y también para el perímetro va a
to give a name of like greet and also for the perimeter it's
8:43:49
tomar una persona y por un tiempo va a tomar eso
going to take a person and for a time it's going to take that
8:43:53
uh su interfaz que ya creamos para ello aquí así que
uh their interface which we already created for it here so
8:43:56
esto debería estar en minúsculas y ahí vamos y ahora dentro del cuerpo de esta función no vamos a hacer nada loco pero solo vamos a registrar en la consola como hola y uh persona punto nombre y también
this one should be lowercase and there we go and now inside this function body we're not going to be doing anything crazy but we are going to be just logging into the console like hello and uh person dot first name and also
8:44:08
el apellido de la persona también ahora déjame volver
the person dot last name as well now let me just go back
8:44:11
y voy a usar como persona punto decir hola
and i'm going to just use like person dot say hello
8:44:15
justo aquí y ejecutar eso así que ahora si vendo eso
right here and execute that so now if i sell that
8:44:18
lo que quiero hacer es que quería crear eso
what i want to do is that i wanted to create that
8:44:21
nombre apellido quiero crear un objeto separado justo aquí está
first name last name i want to create a separate object right here it
8:44:24
ya dándonos bien así que solo voy a proporcionar todas estas propiedades
is already giving us right so i'm going to just provide all of these properties
8:44:27
como el nombre de john el apellido de doe la edad sería 30 y decir hola uh solo eliminemos eso justo aquí venda mi archivo y diga
like first name of john the last name of doe the edge would be 30 and say hello uh let's just remove that right here sell my file and say
8:44:36
hola y dentro de ahí solo estamos proporcionando como uh yo
hello and inside there we are just providing like uh i
8:44:39
no sé hola ahí o sabes que solo voy a escribir como hola
don't know hi there or you know i'm going to just write like hi
8:44:42
ahí justo aquí en lugar de hola así es como estamos
there right here instead of hello so this is how we are
8:44:46
vamos a crear uh o así es como vamos a proporcionar una interfaz
going to be creating uh or this is how we are going to be providing an interface
8:44:49
para el objeto también podemos proporcionar su método
for the object as well we can also provide their method
8:44:52
cuerpo justo aquí y aquí puedes ver que tenemos a este john y
body right here and here you can see we have this john and
8:44:56
eso es ahora déjame duplicar eso justo aquí voy a solo
that's that now let me just duplicate that right here i'm going to just
8:44:59
duplicar eso voy a crear una persona más así que
duplicate that i'm going to just create one more person so
8:45:02
voy a cambiar el nombre de eso a como hosain y voy a
i'm going to just change the name of that to like hosain and i'm going to
8:45:06
también cambiar esto no este ven, voy a cambiar
also change this not this one come on i'm going to change
8:45:09
este nombre a hosain y también vamos a
this name to hosain and also let's
8:45:12
simplemente cambiar este nombre a webdev y el borde
just change this name to webdev and the edge
8:45:15
será 20 y solo voy a decir como qué tal
will be 20 and i'm going to just say like what's good
8:45:18
o sabes qué uh qué tal sería
or you know what uh what's good would
8:45:21
bien, así que ahora déjame usar ese método de cuadrícula bien
be fine okay so now let me just use that grid method right
8:45:24
aquí que ya creamos justo aquí voy a solo
here which we already created right here i'm going to just
8:45:27
crear ese método de cuadrícula y voy a especificar el
create that grid method and i'm going to specify the
8:45:30
john y también hosan justo aquí así que ahora déjame solo guardar
john and also hosan right here so now let me just save
8:45:33
eso y ahora solo vamos a ejecutar eso justo aquí estamos
that and now let's just run that right here we
8:45:36
obteniendo todos los resultados pero eso no se ve tan genial así que voy a
are getting all of the results but that's not looking that much cool so i'm going
8:45:40
simplemente ejecutarlo una vez más y estamos obteniendo como hola
to just run it once again and we are getting like hello
8:45:43
john doe hola ahí hola hosan webdev qué
john doe hi there hello hosan webdev what's
8:45:46
tal bien, así que así es como vamos a definir
good okay so this is how we are going to be defining
8:45:49
nuestra interfaz así es como vamos a usar esa interfaz
our interface this is how we are going to be using that interface
8:45:52
dentro de esta función así es como vamos a crear un objeto basado
inside this function this is how we are going to be creating an object based
8:45:56
en esa misma interfaz aquí tenemos dos objetos y
on that same interface right here we have two objects and
8:45:59
así es como vamos a proporcionar un valor para esta misma interfaz
this is how we are going to be providing a value for this same interface right
8:46:02
aquí ahora déjame darte un ejemplo más porque quiero darte muchos
here now let me just give you one more example because i want to give you a lot
8:46:05
de ejemplo para estas interfaces porque
of example uh for these interfaces because i
8:46:08
sé que muchos instructores dicen como oh Dios mío las interfaces son extremadamente horribles y no puedo dar muchos ejemplos oh maldita sea me duele un poco la garganta
know a lot of instructors say like oh my god interfaces are supremely awful and i cannot give a lot of examples oh god damn it my throat kind of hurts
8:46:21
tengo que dejar de hacer eso ahora déjame escribir mi interfaz
i gotta stop doing that now let me just write my interface
8:46:24
una vez más y voy a crear una interfaz de canción y
once again and i'm going to just create an interface of song and
8:46:27
voy a escribir un nombre de canción también puedes proporcionar un título lo que sea
i'm going to just write a song name you can also provide a title whatever
8:46:31
y también voy a proporcionar un nombre de cantante y
and i'm going to also provide a singer name and
8:46:34
el nombre del cantante será una cadena y también para el
singer name will be string and also for the
8:46:37
imprimir información de la canción vamos a imprimir información de la canción uh lo que vamos a hacer es que vamos
print song info come on print song info uh what we are going to be doing is that we are
8:46:44
a proporcionar el nombre de la canción y el nombre de la canción se establecerá en
going to be providing the song name and the song name will be set to
8:46:47
cadena y también voy a especificar el nombre del cantante
string and i'm going to also specify the singer name
8:46:50
y el nombre del cantante también se establecerá en cadena y también vamos a proporcionar
and the singer name will be also set to string and we're going to be also providing
8:46:54
eso para el retorno también ahora déjame volver y
it for the return as well now let me just go back and
8:46:57
voy a crear una canción aquí y va a ser igual a la
i'm going to just create a song one right here and it's going to be equals to the
8:47:00
interfaz de canción y ahora dentro de este objeto vamos a usar
song interface and now inside this object we're going to be using
8:47:03
como el nombre de la canción y va a ser igual a como natural está bien y el cantante
like song name and it's going to be equals to like natural okay and the singer
8:47:10
el nombre será igual a imagine y
name will be equals to imagine and
8:47:13
también imprimir información de la canción y
also print song info and
8:47:17
vamos a proporcionar el nombre de la canción primero que todo y también vamos a proporcionar
we are going to be providing the song name first of all and we are going to be also providing
8:47:21
el nombre del cantante y dentro de ahí qué
the singer name and inside there what
8:47:24
quieres hacer vamos a simplemente retornar
do you want to do we are going to be just returning
8:47:27
como no sé canción y primero
like I don't know song and first
8:47:30
de todo tenemos que renderizar el nombre del cantante así que no un cantante sino un nombre de canción aquí y luego también tenemos que
of all we have to render the singer name so not a singer but a song name right here and then we also have to
8:47:37
renderizar el cantante también
render the singer also as well
8:47:40
así que voy a usar como nombre del cantante
so i'm going to just use like singer name singer if
8:47:44
ya tienes eso, déjame copiar el nombre del cantante y
you already have that let me just copy the singer name and
8:47:47
ponlo aquí, pero ¿por qué estamos obteniendo este error?
put it right here but why on earth we are getting this error oh
8:47:50
olvidé incluir estas anotaciones aquí, ahí vamos, ahora
i forgot to include these annotations right here there we go now
8:47:53
se ve mejor, voy a guardar este archivo y voy a
that's looking better i'm going to save this file and i'm going to
8:47:56
simplemente usar eso aquí, así que voy a usar como canción uno punto
just use that right here so i'm going to use like song one dot
8:47:59
imprimir canción, imprimir información de la canción y voy a proporcionar natural, ya proporcionamos el
print song print song info and i'm going to just provide natural we already provide the
8:48:06
pero sí, lo haré aquí una vez más y voy a proporcionar como imagina
but yeah i'm gonna just do it right here once again and i'm going to provide like imagine
8:48:12
uh dragón aquí, así que ahora déjame guardar eso y ejecutar eso
uh dragon right here so now let me just save that and execute that
8:48:16
una vez más, así que aquí puedes ver que ahora estamos obteniendo el nombre de la canción que
once again so here you can see we are now getting the song name which
8:48:19
se establecerá en natural y también tenemos un cantante, imagina dragón
will be set to natural and we also have a singer imagine dragon
8:48:22
aquí todo está bien y eso
right here everything is okay and that
8:48:25
estaba aquí sobre interfaces usando con función y también con métodos, ahora aprendamos sobre cómo vamos a extender las interfaces
was just here about for interfaces using with function and also with methods as well now let's learn about how we are going to be extending the interfaces
8:48:35
o tomar la funcionalidad de la interfaz padre
or borrowing the functionality from the parent interface
8:48:38
a la interfaz hija, así que ¿cómo puedo hacer eso?
to the children interface so how can i go about doing that
8:48:41
voy a crear una interfaz aquí y le voy a dar un
i'm going to create an interface right here and i'm going to give a
8:48:44
nombre como detalles de la película, la primera propiedad que voy a establecer
name of like movie details the first property i'm going to set
8:48:47
eso como solo lectura y voy a establecer eso como nombre y
that to read only and i'm going to just set that to name and
8:48:51
cadena, también voy a poner una calificación, así que las calificaciones serán
string i'm going to also put a rating to it so the ratings will be
8:48:54
establecidas como número y también para imprimir película
set to number and also for the print movie
8:48:57
información aquí, ¿qué quieres hacer? Solo queremos proporcionar un nombre
info right here what do you want to do we just want want to provide a name
8:49:00
va a tomar una cadena, también tenemos que proporcionar un precio
it's going to take a string we also have to provide a price
8:49:03
también y el precio se establecerá como número
as well and the price will be set to number
8:49:06
y también queremos proporcionar calificaciones, uh, y las calificaciones
and we also want to provide a ratings uh and the ratings
8:49:09
también se establecerá como número, así que ahora simplemente proporcionemos el retorno, así que vamos a estar usando una cadena o un número aquí, ahora fuera de eso, ¿qué quieres hacer? Solo queremos
will be also set to number as well now let's just provide for the return so we are going to be either using a string or number right here now outside from there what do you want to do we just want to
8:49:21
extender ambas interfaces, así que voy a escribir interfaz, le voy a dar un nombre de
uh extend both of the interfaces so i'm going to just write interface i'm going to give a name of
8:49:25
como género de película y voy a extender
like movie genre and i'm going to extend
8:49:28
extiende esta película
ext nds extends this movie
8:49:32
detalle aquí, así que lo que estoy haciendo es que
uh detail right here so what i'm doing is that
8:49:35
estoy creando una nueva interfaz y estoy
i'm creating a new interface and i am
8:49:38
tomando toda la funcionalidad que actualmente
borrowing all of the functionality which we currently
8:49:41
tenemos dentro de esta interfaz para este género de película
have inside this interface to this movie genre
8:49:44
aquí, así que esto es lo que estoy haciendo ahora mismo y voy a escribir como género y establecer eso como cadena, está bien, y lo que quiero hacer
right here okay so this is what i'm doing right now and i'm going to just write like genre and set that to string okay and what i want to do
8:49:52
es crear una película aquí, como const película uno
i'm going to just create a movie right here like const movie one
8:49:55
y va a ser igual a algún tipo de película como película
and it's going to be equals to some sort of a movie like movie
8:49:58
género, así que ahora estamos usando este género de película
genre so now we are using this movie genre
8:50:01
lo que significa que también estamos extendiendo la funcionalidad de
so which means like we are also extending the functionality from
8:50:05
esta película, así que primero tenemos que satisfacer esta
this movie d so we have to first of all satisfy this one
8:50:08
entonces tenemos que satisfacer este género de película o este
then we have to satisfy this movie genre or this
8:50:11
género específico aquí, así que ahora déjame escribir un código, entonces entenderás
specific genre right here so now let me just write a code then you'll get
8:50:14
de qué estoy hablando, así que voy a usar como nombre y voy a
to know what i'm talking about so i'm going to just use like name and i'm
8:50:17
llenarlo con este aquí, así que el primero requiere un nombre, ya proporcioné ese nombre y requiere las calificaciones, ya proporcioné las
going to just fill it with this one right here so the first one requires a name i already provided that name and it requires the ratings i already provided the
8:50:25
calificaciones, entonces estamos usando este género de película
ratings then we are using this movie genre
8:50:28
aquí puedes poner eso al final, puedes ponerlo en cualquier lugar
right here you can put that at the end you can put it anywhere
8:50:31
que quieras, pero yo lo puse aquí, así que tenemos un género como
you want but i just put it right here so we have a genre as
8:50:34
bueno, y luego tenemos la información de la película de sprint, así que
well and then we have the sprint movie info so
8:50:37
satisfacemos ambas interfaces, ¿verdad?
we satisfy both of these interfaces right
8:50:40
aquí en este caso lo que estamos haciendo es que estamos tomando
here in this case what we are doing is that we are borrowing
8:50:43
toda la funcionalidad de esta interfaz y la estamos poniendo aquí en esta interfaz, está bien, luego estamos proporcionando ese género de película
all of the functionality of this interface and we are putting it right here in this interface right here okay then we are providing that movie genre
8:50:52
interfaz aquí, lo que significa que ahora tenemos que satisfacer ambos
interface right here so which means like we have to now satisfy both
8:50:56
de estas interfaces como esta interfaz y también esta
of these interfaces like this interface and also this
8:50:59
interfaz también, así que ahí vamos, ya hemos proporcionado valores
interface as well so there we go we already provided values
8:51:02
para ellos y así que ahora déjame crear una respuesta, así que como const
for them and so now let me just create a response so like const
8:51:05
respuesta y vamos a proporcionar una película uno punto imprimir
response and we're going to be providing a movie one dot print
8:51:09
información de la película aquí y voy a especificar
movie info right here and i'm going to just specify
8:51:12
como John Wick y también voy a proporcionar, no sé, el precio de 100 y las calificaciones de Ed y ahí vamos, ahora puedo
like john wick and i'm going to also provide uh i don't know the price of 100 and the ratings of ed and there we go now i can
8:51:20
registrar eso en la consola con éxito, ahora déjame ejecutar eso y
log there to the console successfully now let me just run that and
8:51:24
aquí puedes ver que tenemos un nombre de película de John Wick, el precio
here you can see we have a movie name of john wick the price
8:51:27
es 100 y también tenemos las calificaciones de Airtroy aquí, increíble
is 100 and also we have the ratings of airtroy here amazing
8:51:31
así que sí, así es como vamos a extender la interfaz de
so yeah this is how we are going to be extending interface from
8:51:35
otra interfaz, ahora finalmente aprendamos sobre
another interface now finally let's learn about
8:51:38
interfaces con clases, así que lo que
interfaces with classes baby so what
8:51:41
quiero hacer es que voy a crear una interfaz llamada vehículo y dentro de esta interfaz tendríamos como dos métodos, no sé
i want to do is that i'm going to just create an interface given name of like vehicle and inside this interface we would have like uh two method like i don't know
8:51:48
iniciar y también va a ser
start and it's going to be also
8:51:52
amplio porque no vamos a obtener algún
a wide because we're not going to be getting some
8:51:55
tipo de declaración de retorno, así que va a ser amplio y también tenemos
sort of a return statement so it's going to be wide and we also have
8:51:58
uno de detener también, voy a ejecutar este también y
a stop one as well i'm going to execute this one as well and
8:52:01
va a ser amplio también, ahora déjame crear una clase, voy a
it's going to be wide as well now let me just create a class i'm
8:52:04
darle un nombre como coche y vamos a usar
going to give a name of like car and we are going to be using
8:52:07
los implementos aquí, i-m-p-l-e-m-e-n-t-s, si puedo deletrear eso hoy y vehículo, así que vamos a proporcionar este vehículo aquí
the implements right here i-m-p-l-e-m-e-n-t-s if i can spell that today and vehicle okay so we are going to be providing this vehicle right here
8:52:17
así que ahora estamos usando esta interfaz de vehículo dentro de este
so now we are using this vehicle interface inside this
8:52:21
coche o estamos implementando eso, así que solo tenemos que
car or we are implementing that so we have to just
8:52:24
usar esta palabra clave de resultado de implementación aquí, así que estoy
use this implement result keyword right here okay so i'm
8:52:27
simplemente satisfaciendo esta interfaz que ya estamos usando, así que voy a usar como el método iniciar y simplemente voy a escribir como coche es
going to just satisfy this interface which we're already using so i'm
8:52:30
voy a usar como método de inicio y voy a escribir como el coche está
going to use like start method and i'm going to just write like car is
8:52:33
arrancando y ahora voy a duplicar eso, proporcionar una coma, cambiar eso a detener y, por cierto, no tenemos que especificar la coma, ni siquiera sé por qué hice eso y el coche está deteniéndose
starting and now i'm going to just duplicate that provide a comma change that to stop and by the way we don't have to specify the comma i don't even know why i did that and car is stopping
8:52:46
o detenido s-t-o-d-p-e-d
or stopped s-t-o-d-p-e-d
8:52:49
vamos a eliminar eso, voy a volver y
let's just remove that i'm going to go back and
8:52:52
así es como vamos a estar usando eso, así es como vamos a estar
this is how we are going to be using that this is how we are going to be
8:52:55
definiendo nuestra interfaz y así es como vamos a estar usando eso y esto
defining our interface and this is how we are going to be using that and this
8:52:58
es cómo vamos a estar satisfaciendo todas las propiedades o
is how we are going to be satisfying all of the properties or
8:53:02
métodos en este caso de esta interfaz de vehículo aquí
methods in this case of this vehicle interface right here
8:53:05
bien, así que ahora, ¿cómo en el mundo vamos a estar usando esto? solo voy a usar como costo mi coche y va a ser igual a nuevo
okay so now how in the world we are going to be using this i'm going to just use like cost my car and it's going to be equals to new
8:53:11
coche porque esta es una clase y ahora podemos
car because this is a class and we can now
8:53:14
usar como mi coche.iniciar, podemos iniciar el coche ahora
use like my car.start we can start the car now
8:53:17
déjame solo iniciar el coche y guardarlos y el coche
let me just start the car and save them and car
8:53:20
está arrancando aquí, si quiero detenerlos, voy a
is starting right here if i want to stop them i'm going
8:53:23
duplicar eso y cambiar eso a detener, guardar mi archivo y
to just duplicate that and change that to stop save my file and
8:53:26
ejecutar eso, así que tenemos el coche está arrancando y también
run that so we have car is starting and we also
8:53:29
tenemos el coche está detenido aquí, bien, así es como vamos a estar usando las interfaces con clases, así que ahora solo queda un tema que se llama fusión de declaraciones.
have car is stop right here okay so this is how we are going to be using the interfaces with classes baby so now there is only one topic left which is called a declaration merging.
8:53:41
Así que ahora hablemos de fusión de declaraciones. Una vez que la interfaz está declarada, no se puede modificar directamente.
So now let's talk about declaration merging. So once the interface is declared, it cannot be directly modified.
8:53:46
Sin embargo, TypeScript permite lo que se conoce informalmente como fusión de declaraciones o extensiones de interfaz, que a menudo se malinterpreta como una reapertura.
However, TypeScript allows what is informally referred to as declaration merging or interface extensions, which is often misconstructed as a reopening.
8:53:57
Algunas personas lo llaman reapertura. Así que todos estos tres nombres funcionan si quieres llamarlo como quieras. Entonces, ¿qué es una fusión de declaraciones?
Some people like call it reopening. So all of these three names work if you want to call it whatever you want to call it. So what is a declaration merging?
8:54:05
La fusión de declaraciones en TypeScript se refiere a la capacidad de extender o argumentar una declaración existente, incluidas las interfaces también.
Declaration merging in TypeScript refers to the ability to extend or argument an existing declaration, including interfaces as well.
8:54:12
Y esto puede ser útil cuando deseas agregar nuevas propiedades o métodos a una interfaz existente sin modificar la declaración original.
And this can be useful when you want to add new properties or methods to existing interface without modifying the original declaration.
8:54:19
Bien, entonces, ¿cómo en el mundo vamos a hacer eso? La sintaxis es totalmente simple.
Okay, so how in the world we are going to be doing that? The syntax is totally simple.
8:54:25
Como una vez que definimos algún tipo de interfaz, proporcionamos una propiedad, proporcionamos nuestro método y queremos más tarde proporcionar algo más.
Like once we define some sort of an interface, we provide a property, we provide our method, and we want to later provide something else.
8:54:32
Así que podemos hacer eso o si quieres cambiar los existentes
So we can totally do that or if you want to change the existing
8:54:35
así que vamos a estar usando esta exacta
ones so we are going to be using this exact
8:54:38
la misma sintaxis como este nombre exacto esta exacta
same syntax like this exact name this exact
8:54:42
sintaxis y en este caso vamos a proporcionar estas nuevas propiedades
syntax and in this case we are going to be providing this new properties
8:54:45
aquí como modal se establecerá en cadena y también
right here like modal will be set to string and also
8:54:48
tenemos un método de parada aquí en este caso tenemos una marca de cadena
we have a stop method right here in this case we have a brand of string
8:54:51
y también tenemos un método de inicio pero ahora en este caso
and we also have a start method but now in this case
8:54:54
estamos usando una fusión de declaraciones o también puedes decir la
we are using a declaration merging or you can also say the
8:54:58
extensión de interfaz o algunas personas también la llaman
interface extension or some people also call
8:55:01
Dios no lo quiera, reabrir una interfaz
it god forbid reopening an interface
8:55:04
así que sí, así es como vamos a usar eso, así que solo tienes que
so yeah this is how we are going to be using that so you just
8:55:07
especificar el nombre de tu interfaz y luego solo tienes que satisfacer
have to specify your interface name and then you just have to satisfy
8:55:10
eso, pero así es como vamos a hacer una declaración
that but this is how we are going to be doing a declaration
8:55:13
fusión, así que lo que quiero hacer es que voy a eliminar todo el código y ahora hablemos de una fusión de declaraciones, así que solo voy a escribir como interfaz original, ¿verdad?
merging so what i want to do is i'm going to delete all of the code and now let's talk about a declaration merging so i'm going to just write like original interface right
8:55:22
aquí, así que primero vamos a crear la interfaz original, así que
here so first of all we are going to be creating original interface so
8:55:25
interfaz y solo le voy a dar un nombre como
interface and i'm going to just give a name like
8:55:29
coche y dentro de este coche tendríamos una marca y
car and inside this car we would have a brand and
8:55:32
se va a establecer en cadena y también voy a proporcionar un método de inicio aquí
it's going to be set to string and i'm going to also provide a start method right here
8:55:35
así que el método de inicio se establecería en blanco aquí
so start method would be set to white right here
8:55:38
así que más tarde en algunos casos si quiero cambiar una propiedad específica o si quiero proporcionar una nueva, entonces lo que vamos a hacer es que vamos a hacer una declaración
so later in some cases if i want to change specific property or if i want to provide a new one to it so then what we are going to be doing we are going to be doing a declaration
8:55:48
fusión o también puedes decir como extensión de interfaz
merging or you can also say like interface extend
8:55:52
y o lo que quieras llamarlo ahora
and or whatever you want to call that now
8:55:55
déjame eliminar esas cosas de aquí y solo voy a escribir modelo
let me just delete that stuff from here and i'm going to just write model
8:55:58
y el modelo se establecerá en cadena y
and model will be set to string and
8:56:01
también voy a especificar la parada y este va a ser el método y
i'm going to also specify the stop and this is going to be the method and
8:56:05
voy a establecer eso en blanco, ahora déjame crear mi coche así que
i'm going to just set that to white now let me just create my car so
8:56:08
voy a crear como costo mi coche y va a ser la interfaz de coche y vamos a satisfacer
i'm going to just create like cost my car and it's going to be uh the car interface and we are going to be just satisfying
8:56:14
todos sus métodos y así es como vamos a satisfacer todos sus métodos, así que tenemos una marca de bmw, tenemos un método de inicio, también tenemos un método de parada, pero ¿olvidamos algo más?
all of their methods and this is how we're going to be satisfying all of their methods so we have a brand of bmw we have a start method we also have a stop method but did we forgot something else
8:56:26
marca, oh, también olvidamos esto, uh, el
brand oh we also forgot this uh the
8:56:29
modelo, ni siquiera sé qué es un modelo, pero voy a escribir un
model i don't even know what a model is but i'm gonna just write a
8:56:32
modelo de, sí, este m3, muchas gracias, IA, así que ahora déjame guardar eso y así es como vamos a
model of yep this one m3 thank you so much ai so now let me just save that and this is how we
8:56:41
satisfacerlos, así que ahora déjame seguir adelante y usar eso
are going to be satisfying them so now let me just go ahead and use that
8:56:44
aquí, así que voy a registrar en la consola como mi coche
right here so i'm going to just log to the console like my car
8:56:48
punto, no sé, método de inicio, voy a guardar
dot i don't know start method i'm going to just save
8:56:51
ellos y ejecutar eso, así que nos va a dar inicio
them and run that so it's going to gives us start
8:56:54
y indefinido, uh, oh, eso es porque
and undefined uh oh that's because
8:56:57
ya estamos registrando en la consola, por eso obtenemos este indefinido
we are already console logging there that's why we get this undefined
8:57:00
así que ahora déjame quitar eso y guardar, solo nos va a dar inicio, aquí podemos incluso detener nuestro coche, simplemente detengámonos
so now let me just remove that and save that it's going to only give us start for here we can even stop our car let's just stop
8:57:07
ordenar coche, bebé, detener, ejecutar ahí
order card baby stop run there
8:57:11
y va a detener, ordenar coche, primero va a iniciarlo y
and it's going to stop order card it's going to first of all start it and
8:57:14
luego también lo va a detener aquí y puedes tener acceso a
then it's going to also stop it right here and you can have access to
8:57:17
la marca y también al modelo, así que eso
the brand and also the model as well and that
8:57:20
fue sobre la inmersión profunda en las interfaces en
was it about the deep dive into the interfaces in
8:57:23
typescript, así que ahora hablemos de una de las mejores características
typescript so now let's talk about one of the best feature
8:57:26
en typescript, que se llama genéricos, así que ¿qué demonios son los genéricos y por qué deberías preocuparte por ellos? En typescript, los genéricos te permiten crear un componente reutilizable
in typescript which is called generics so what in the world are generics and why you should care about them so in typescript generics allow you to create a reusable component
8:57:35
que funciona con una variedad de tipos, como los genéricos lo hacen
that work with a variety of types like generics makes it
8:57:38
posible para ti definir clases de función e interfaces que pueden trabajar con diferentes tipos de datos sin tener que duplicar nuestro código y aquí la palabra clave es diferentes tipos de datos, ahora podrías estar pensando como hosan
possible for you to define function classes and interfaces that can work with different data types without having to duplicate our code and here the keyword is different data types now you might be thinking like hosan
8:57:50
¿no es eso cualquier tipo? Como si usamos el tipo any, podemos
isn't that any type like if we use the any type we can
8:57:53
proporcionar cualquier tipo de dato, no, los genéricos son totalmente diferentes a eso, así que también podemos crear una función genérica y también podemos crear un genérico
provide any data type no generics are totally different than that so we can also create a generic function and we can also create a generic
8:58:01
clases, que también vamos a aprender en esta sección ahora
classes which we are going to be also learning in this section now
8:58:04
déjame darte una especie de código sin usar un
let me just give you some sort of a code without using a
8:58:08
función genérica y luego vamos a refactorizar ese código para
generic function and then we are going to be refactoring that code to
8:58:11
usar una función genérica, así que aquí puedes ver que tenemos como tres flechas
use a generic function so here you can see we have like three arrow
8:58:14
funciones justo aquí, la primera solo tomará un valor de cadena
functions right here the first one will only take a string value
8:58:17
como aquí tenemos que especificar el valor de cadena justo aquí porque
like here we have to specify string value right here because
8:58:20
aquí estamos anotando nuestro perímetro como una cadena, así que aquí puedes ver que tenemos que especificar una cadena correcta
here we are now annotating or perimeter as a string so here you can see we have to specify a string right
8:58:27
aquí si especificas, no sé, algún tipo de número o yo
here if you specify like i don't know some sort of a number or i
8:58:30
no sé si algún tipo de valor booleano, así que nos lanzará un
don't know if some sort of like a boolean value so it's going to throw us an
8:58:33
error y aquí puedes ver que para la siguiente función tenemos
error and here you can see for the next function we have
8:58:36
que especificar el número, si especificas algo más como
to specify the number if you specify something else like
8:58:40
cadena o booleano o algo así, nos lanzará
string or boolean or something like that it's going to throw
8:58:43
un error, ¿por qué es eso? porque aquí estamos
us an error why is that because here we are
8:58:46
requerimos el número justo aquí, como estamos anotando nuestro perímetro como un número, así que aquí tenemos que especificar el número
requiring the number right here like we are annotating our perimeter as a number so here we have to specify number
8:58:53
justo aquí y ahora el final también hará lo mismo, como para booleano
right here and now the final one will also do the same like for boolean
8:58:56
tenemos que especificar un booleano justo aquí, si especificamos algún
we have to specify a boolean right here if we specify some
8:58:59
tipo de número o cadena, nos lanzará un error, así que ahora, una forma de resolver este problema es usar una de las horribles características de TypeScript que se llama
sort of a number or string it's going to throw us an error so now the one way to solve this problem is to use one of the awful typescript feature which is called
8:59:09
cualquier tipo, así que tenemos que eliminar esta cadena, también tenemos que eliminar este número y también el booleano, así que aquí tenemos que simplemente reemplazarlos con cualquier tipo y eso lo resolverá para nosotros, pero eso no es una buena práctica.
any so we have to remove this string we also have to remove this number and also the boolean so here we have to just replace them with any type and that's going to do it for us but that's not a best practice.
8:59:19
Tenemos que encontrar alguna manera de crear algún tipo de función y proporcionar algún tipo específico para esa función y luego tenemos que especificar algún tipo de valor basado en ese tipo específico.
We have to figure out some way so that we create some sort of a function and we provide some specific type for that function and then we have to specify some sort of a value based on that specific type.
8:59:30
Así que para eso vamos a usar genéricos y cómo vamos a crear un genérico?
Okay so for that we are going to be using generics and how we are going to be creating a generics?
8:59:35
Así es como vamos a crear un genérico, es totalmente fácil
This is how we are going to be creating a generics like totally easy
8:59:39
pero la cosa es que aquí puedes ver que para estas funciones, déjame decir que aquí puedes ver que para
but the thing is here you can see for these function let me just say that here you can see for
8:59:45
estas funciones estamos proporcionando específicamente o
these functions we are specifically providing or
8:59:48
estamos anotando específicamente eso a la cadena, al número y también al booleano, y ¿cómo se llaman estas cosas? se llaman área de perímetro de función justo aquí, como
we are specifically annotating that to the string to the number and also to the boolean as well and what are these things called these are called a function perimeter area right here like
9:00:00
todas estas cosas se llaman perímetro de función justo aquí. Ahora, por otro lado, déjame mostrarte esto.
All of these things are called a function perimeter right here. Now, on the other hand, let me just show you this.
9:00:06
Este es un perímetro de tipo justo aquí.
This is a type perimeter right here.
9:00:09
Como cada vez que quieras crear algún tipo de función genérica, aquí, esta área, también podemos especificar un tipo justo aquí.
Like anytime you want to create some sort of a generic function, here, this area, we can also specify a type right here.
9:00:16
O también podemos simplemente abreviarlo a T. En este caso, solo lo abrevié a T. Pero también puedes escribir un tipo si lo deseas.
Or we can also just abbreviate that to T. In this case, I just abbreviate that to T. But you can also write a type if you wanted to.
9:00:21
Así que esta área aquí, puedes ver que solo la resalto. Esta área se conoce como un perímetro de tipo.
So this area here, you can see that I just highlight that. This area is known as a type perimeter.
9:00:28
como qué tipo de tipo vamos a especificar aquí para la función específica
like which kind of type we are going to be specifying right here for the specific function
9:00:33
esta área que puedes ver aquí es una función
this area which you can see right here is a function
9:00:37
área de perímetro aquí también quiero que
perimeter area right here also i want you
9:00:40
notices que también esta área es un tipo
to notice like also this area is a type
9:00:43
área de perímetro aquí como para esta área tenemos que
perimeter area right like for this area we have to
9:00:47
especificar algún tipo de valor como podemos proporcionar una cadena, podemos proporcionar un número, también podemos proporcionar un booleano aquí y nos dará resultados basados en eso como aquí puedes
specify some sort of a value like we can either provide a string we can provide a number we can also provide a boolean right here and it's going to give us results based on that like here you can
9:00:55
ver que el primero nos va a dar un hola porque ahora estamos anotando
see the first one is going to give us a hello because we are now annotating
9:00:58
eso o estamos especificando el valor para este perímetro
that or we are specifying the value for this perimeter
9:01:02
área aquí el tipo de cadena así que aquí puedes ver que
area right here the string type so here you can see we
9:01:05
tenemos que especificar el valor de la cadena aquí y nos dará el resultado
have to specify the string value right here and it's going to give us the result
9:01:08
de la cadena, luego para el número estamos proporcionando un número
of string then for the number we are providing a number
9:01:11
y también estamos obteniendo el número aquí, luego finalmente para el booleano
and we are also getting the number right here then finally for the boolean
9:01:14
estamos proporcionando un booleano y finalmente estamos obteniendo el valor booleano aquí, así que sí, hubo mucha charla, así que ahora déjame darte algún tipo de ejemplo y luego entenderás de qué estoy hablando.
we are providing a boolean and finally we are getting the boolean value right here okay so yeah there was a lot of talking so now let me just give you some sort of example and then you will get to know what I'm talking about.
9:01:24
Así que lo primero que quiero hacer es crear muchas funciones y no van a ser funciones genéricas.
So the first thing which I want to do is I'm going to create a lot of function and they are not going to be a generic function.
9:01:30
Así que solo voy a crear una función regular como TypeScript o JavaScript aquí.
So I'm going to just create a regular like TypeScript or JavaScript function right here.
9:01:34
El primero será para imprimir un número aquí y
The first one will be for the print number right here and
9:01:37
tomará el perímetro de un ítem o algo así y lo voy a anotar con un número y también voy a especificar un valor por defecto como venir por defecto y aquí solo voy a especificar el número aquí
it's going to take the perimeter of like item or something like that and I'm going to annotate that with a number and I'm going to also specify a default value to like come on default and here I'm going to just specify the number right here
9:01:47
y también olvidé incluir el tipo de retorno también
and I also forgot to include the return type as well
9:01:50
así que tomará un número y también el número así que ahora déjame
so it's going to take a number and also the number as well so now let
9:01:53
regresar y aquí dentro de esta función qué tienes que
me just go back and here inside this function what do you have to
9:01:57
hacer, vamos a estar devolviendo el ítem y también el valor por defecto
do we are going to be just returning the item and also the default value
9:02:00
aquí así que en lugar de escribir un valor por defecto
right here okay so instead of writing a default
9:02:03
voy a cambiar eso a un valor por defecto
I'm going to just change that to like a default value
9:02:06
o algo así y aquí puedes ver que el error ha desaparecido, así que
or something like that and here you can see that error is gone so
9:02:09
ahora, si quiero ejecutar este código, ¿qué tengo que hacer para eso? Bueno, solo voy a escribir como no sé, const número va a ser igual
now if I want to run this code so what do I have to do for that well I'm going to just write like I don't know const number it's going to be equal
9:02:15
con este imprimir número número aquí y puedo especificar
with this print number number right here and i can specify
9:02:18
cualquier número que quiera y ahora déjame solo registrar en la consola esto
any number i want and now let me just log to the console this
9:02:21
número aquí, ¿qué está pasando? imprimir
number right here what is going on print
9:02:25
número espera dos parámetros aquí, así que solo voy a especificar como 12
number expect two parameter right here so i'm going to just specify like 12
9:02:28
y 20 aquí, ahora déjame solo guardar eso y ejecutar mi archivo
and 20 right here now let me just save that and run my file
9:02:32
así que aquí puedes ver que nos va a dar un arreglo de 12 y también 20 aquí, lo cual está bien, así que supongamos que si especifico algo más como una cadena, ahora déjame escribir algo
so here you can see it's going to give us array of 12 and also 20 right here which is okay so let's suppose if i specify something else like string now let me just write like something
9:02:42
y también voy a especificar el booleano aquí como verdadero y
and i'm going to also specify the boolean right here like true and
9:02:45
ahora, si vendo eso y si lo ejecuto, nos va a dar este error
now if i sell that and if i run that it's going to give us this error
9:02:48
como argumento de tipo cadena no es asignable a un perímetro
like argument of type string is not assignable to a perimeter
9:02:51
de tipo número aquí, tienes que hacer algo al respecto
of type number right here you got to do something about that
9:02:54
así que ahora déjame solo quitar eso de aquí ahora
so now let me just uh remove that from here now
9:02:57
déjame solo proporcionar uno y también voy a especificar dos aquí, así que
let me just provide one and i'm going to also specify two right here so
9:03:00
lo que significa que solo podemos especificar el número
which means like we can only specify the number
9:03:03
valores aquí, no podemos especificar la cadena, no podemos especificar el booleano ni nada de eso, así que lo siguiente que quiero hacer es solo
values right here we cannot specify the string we cannot specify the boolean or anything like that so the next thing which i want to do is i'm going to just
9:03:10
uno para, no sé, para una cadena, como no sé, imprimir
one for like i don't know for a string like i don't know print
9:03:14
cadena o algo así y creo que eso
string or something like that and i guess that
9:03:17
sería todo, así que ahora déjame duplicar eso y cambiar este
would be it so now let me just duplicate that and change this one
9:03:20
a cadena para una cadena y también imprimir cadena
to stir for a string and also print string
9:03:23
aquí y en este caso no podemos
right here and in this case we are not able to
9:03:26
proporcionar, déjame solo escribir una cadena aquí y por
provide let me just write a stir right here and by
9:03:30
cierto, olvidé también cambiar estos a cadena
the way i forgot to also change these to string
9:03:33
aquí, así que ahora déjame solo cambiar eso a cadena y
right here so now let me just change that to string and
9:03:37
aquí puedes ver que ahora nos está dando un error si paso el mouse sobre él, así que
here you can see it is now giving us an error if i hover my mouse over to it so
9:03:40
también nos está dando esa misma área, como argumento de tipo número es
it is also giving us that same area like argument of type number is
9:03:43
no se puede asignar a un perímetro de tipo cadena, así que sí, tenemos
not assignable to a perimeter of type string so yeah we
9:03:46
que especificar algún tipo de valor de cadena aquí, así que voy a escribir como
have to specify some sort of a string value right here so i'm going to just write like
9:03:50
uh no sé, hola y también voy a especificar la palabra
uh i don't know hello and i'm going to also specify word
9:03:53
o algo así y ahora si envío mi archivo y
or something like that and now if i send my file and
9:03:56
ejecuto eso y simplemente eliminemos eso de aquí y
run that and let's just remove that from here and
9:03:59
déjame volver a ejecutar eso una vez más, así que aquí puedes ver que va a dar
let me just rerun that once again so here you can see it's going to give
9:04:02
nos hola y también la palabra aquí, así que ahora déjame también escribir una función para los booleanos también, así que voy a escribir como imprimir bool o booleano, más bien voy a cambiar el tipo a booleano
us hello and also the word right here so now let me just also write one function for the booleans as well so i'm going to just write like print bool or boolean rather i'm going to change the type to boolean
9:04:14
y ahora voy a duplicar esta línea
and now i'm going to just duplicate this line
9:04:17
de código, cambia este a bool o algo así y
of code change this one to bool or something like that and
9:04:20
imprimir bool aquí o booleano, más bien
print bool right here or boolean rather
9:04:24
así que nos va a dar ese error como argumento de tipo cadena no es asignable
so it's going to give us that error like argument of type string is not assignable
9:04:27
a un perímetro de tipo booleano, tenemos que especificar algún
to a perimeter of type boolean we have to specify some
9:04:30
tipo de valor booleano aquí, está bien, así que si solo escribo como verdadero y falso y ahora si guardo eso y
sort of boolean value right here okay so if i just write like true and false and now if i save that and
9:04:36
simplemente registremos ese bool en la consola también, déjame guardar este archivo
let's just log that bool to the console as well let me just save this file
9:04:39
y ejecutarlo, así que aquí puedes ver que ahora estamos obteniendo verdadero y
and run there so here you can see we are now getting true and
9:04:43
también el valor falso aquí, lo que significa que todo está
also the false value right here which means like everything is
9:04:46
totalmente funcionando bien, pero el problema
totally working a-okay but the problem
9:04:49
que estamos enfrentando actualmente es que tenemos que
which we are currently facing is that uh we have
9:04:52
especificar un número para este imprimir número aquí, tenemos que especificar una cadena para la función imprimir cadena y tenemos que especificar el booleano para esta función imprimir booleano aquí.
to specify number for this print number right here we have to specify string for the print string function and we have to specify the boolean for this print boolean function right here.
9:05:01
Como, no podemos proporcionar un número para el booleano. No podemos proporcionar un número para una cadena y también booleano para una cadena. No podemos proporcionar booleano o número.
Like, we cannot provide a number for the boolean. We cannot provide a number for a string and also boolean for a string. We cannot provide boolean or number.
9:05:09
Quiero decir, no podemos proporcionar booleano o cadena para esta función imprimir número aquí. Tenemos que hacer algo al respecto.
I mean, like, we cannot provide boolean or string for this print number function right here. We have to do something about that.
9:05:14
Bueno, la primera respuesta es, ahora déjame simplemente eliminar eso y también estas otras funciones. Ahora, déjame simplemente eliminar eso.
Well, the first answer is, now let me just remove that and also these other functions as well. Now, let me just remove that.
9:05:21
Puedo especificar el tipo any aquí. Si solo escribo
I can just specify the any type right here. if i just write
9:05:24
any, ni siquiera tengo que anotar any, ¿verdad?
any i don't even have to like annotate any right
9:05:28
aquí, pero de todos modos, si solo guardo eso, ahora déjame registrar en el
here but anyways if i just save that now let me just log to the
9:05:31
consola este número y voy a especificar um
console this num and i'm going to specify um
9:05:34
sí, un número será para el primero y para
yeah a number will be for the first one and for
9:05:37
el segundo voy a escribir algo y no va a
the second one i'm going to just write like something and it's not going
9:05:41
tomar tres parámetros así que sí, eso es todo, ahora déjame guardar allí y ejecutar allí y aquí puedes ver que nos dará uno para un número y también algo como una cadena justo aquí, ahora nuestro
to take three parameters so yeah that's it now let me just save there and run there and here you can see it's going to give us one for a number and also something as a string right here now our
9:05:50
problema está totalmente resuelto, pero quiero hacerte una pregunta
problem is totally solved but i want to ask you a question
9:05:53
como en este código, ¿dónde en el mundo está
like in this code where in the world is
9:05:56
typescript desempeñando su papel? Bueno, en ningún lado como
typescript playing their role well nowhere like
9:05:59
ni siquiera estamos usando un typescript para eso, solo estamos escribiendo este extra
we are not even using a typescript for that we are just writing this extra
9:06:02
código justo aquí, no estamos usando typescript en ninguna parte dentro
code right here we are not using typescript anywhere inside
9:06:06
de este código y typescript se trata de tipos y
this code and typescript is all about types and
9:06:09
tenemos que hacer algo al respecto, está bien, así que para hacer algo al respecto vamos a refactorizar todo ese código que acabo de escribir justo aquí, tú
we have to do something about that okay so to do something about that we are going to be refactoring all of that code which i just wrote right here you are
9:06:17
vas a refactorizar todo ese código a una simple
going to be refactoring all of that code to one simple
9:06:20
función que se llama función genérica y
function which is called generic function and
9:06:23
créeme, la sintaxis es totalmente simple
trust me the syntax is totally simple
9:06:26
y asombrosa, así que ahora déjame crear una función genérica justo
and awesome so now let me just create a generic function right
9:06:29
aquí, así que cada vez que quieras crear una función genérica, no
here so anytime you want to create a generic function we
9:06:32
vamos a hacer nada especial, pero solo vamos a crear nuestra función
are not going to be doing anything special but we are going to be just creating our function
9:06:36
así, déjame resaltar eso para ti, vamos a
just like that let me just highlight there for you we're
9:06:39
proporcionar primero la palabra clave de resultado de la función, luego un nombre específico para nuestra función, luego el área del perímetro y también nuestras llaves aquí, pero ahora
going to first of all providing the function result keyword then specific name for our function then the perimeter area and also our curly braces right here but now
9:06:47
voy a especificar algún tipo de nombre justo aquí, déjame acercar un poco, estoy
i'm going to just specify some sort of a name right here let me just zoom in a bit i'm
9:06:50
voy a especificar algún tipo de nombre como tipo de dato único
going to specify some sort of a name like unique data type
9:06:54
vamos, typs, supongo que eso estará bien o
come on typs i guess that's going to be fine or
9:06:57
la función de tipos de datos únicos estaría bien, en lugar de eso, y voy a
unique data types function would be fine rather and i'm
9:07:00
también eliminar estos parámetros y voy a cambiar eso a como
going to also remove this params and i'm going to just change that to like
9:07:03
no sé, elemento, y voy a anotar simplemente
i don't know item and i'm going to just annotate
9:07:07
no sé el ítem y solo voy a anotar eso con algo pero primero déjame escribir una coma y luego el valor por defecto así que no voy a anotar allí y tampoco voy a proporcionar ninguna anotación para el valor de retorno.
that with something but you know first of all let me just write a comma and then the default value so i'm not going to even annotate there and i'm not going to provide any annotation for the return value as well.
9:07:17
Así que lo primero que tienes que tener en cuenta cada vez que quieras crear una función genérica es cuántos tipos de datos esta función va a tomar como valor.
So the first thing that you have to keep in mind anytime you want to create a generic function is that how many data types this function is going to take as a value.
9:07:25
Así que en este caso voy a especificar uno aquí solo para este ejemplo específico.
So in this case I'm going to just specify one right here just for this specific example.
9:07:30
No vamos a hacer nada loco ahora mismo pero lo haremos muy pronto. Así que voy a escribir un signo menor que.
We're not going to do anything crazy enough right now but we will very soon. So I'm going to just write a less than sign.
9:07:35
Vamos, signo menor que y aquí tenemos que especificar el tipo aquí y voy a cerrar eso.
Come on less than sign and here we have to specify type right here and I'm going to close that.
9:07:41
esta área es un área de parámetro de tipo aquí
this area is a type parameter area right here
9:07:44
y también esta área es un parámetro de función
and also this area is a function parameter
9:07:47
área aquí así que ahora que dejamos claro eso
area right here so now that we make clear that
9:07:50
puedes especificar cualquier tipo que quieras aquí
you can specify any type you want right here this
9:07:53
es un área de parámetro de tipo aquí como tenemos que especificar
is a type parameter area right here like we have to specify
9:07:56
algún tipo para eso así que el tipo se declara pero su
some sort of a type for that so type is declared but its
9:07:59
valor nunca se lee, está bien, así que vamos a encargarnos de eso en unos segundos. Ahora, lo siguiente que tienes que hacer es que tenemos que usar este tipo en algún lugar dentro de nuestro
value is never read okay so we are going to take care of that in a few seconds now the next thing which you have to do is that we have to use this type somewhere inside our
9:08:07
función, así que donde lo vamos a estar usando, voy a copiar eso
function so where we are going to be using there i'm going to copy that
9:08:10
y voy a anotar eso para el ítem. Ahora déjame
and i'm going to annotate that for the item now let me just
9:08:13
escribir ítem y voy a especificar este tipo aquí y
write item and i'm going to just specify this type right here and
9:08:16
también lo voy a especificar para el valor por defecto también
i'm going to also specify it for the default value as well
9:08:19
y también lo voy a especificar para el valor de retorno de esto
and i'm going to also specify it for the return value of this
9:08:23
función también o sabes que vamos a estar retornando como dos valores así que solo voy a escribir un arreglo de tipo y también el tipo aquí justo como para esto
function as well or you know what we're going to be returning like two values so i'm going to just write array of type and also the type right here just like for this
9:08:31
función estamos retornando como, uh, dos valores aquí
function we are returning like uh two values right here
9:08:35
así que ahora solo los estamos anotando así, está bien
so we are now just annotating them like this okay
9:08:38
así que así es como vamos a crear nuestra función genérica y sé
so this is how we are going to be creating our generic function and i know
9:08:41
que va a parecer un poco raro pero confía en mí, esto no es
that's gonna look a bit weird but trust me this is not
9:08:44
algo tan raro de aprender en typescript pero sí, déjame
that much weird thing to learn in typescript but yeah let me
9:08:48
decirlo una vez más, primero vamos a crear algún tipo de función general de script o typescript, podemos darle cualquier nombre que queramos y luego tenemos que especificar algún tipo de un
just say that once again first of all we are going to be creating some sort of a general script or typescript function we can give it any name we want and then we have to specify some sort of a
9:08:56
tipo aquí como esta área se conoce como un perímetro
type right here like this area is known as a perimeter
9:09:00
área que tienes que especificar algún tipo de valor
area you have to specify some sort of a value for
9:09:03
este perímetro aquí y luego lo estamos reutilizando
this perimeter right here and then we are reusing that
9:09:06
perímetro aquí y también aquí así como también para
perimeter right here and also here as well and also for
9:09:09
este tipo de retorno también, así que actualmente ni siquiera estamos especificando
this return type as well so currently we are not even specifying
9:09:12
o ni siquiera estamos devolviendo algo de nuestra función, así que eso es
or we are not even returning something from our function so that's
9:09:15
por qué ahora estamos obteniendo este error aquí, pero ahora lo que quiero hacer es que voy a devolver ese elemento y también el
why we are now getting this error right here but now what i want to do is that i'm going to just return that item and also the
9:09:23
valor predeterminado también, así que ahora déjame devolver
default value as well okay so now let me just return
9:09:26
que la siguiente cosa que quiero hacer es que, ya sabes, déjame guardar este archivo
that the next thing which i want to do is that you know what let me just save this file
9:09:29
y va a formatear mi código así, pero ahora
and it's going to format my code like that but now
9:09:33
tenemos que usar esta función única aquí o única
we have to use this um unique function right here or unique
9:09:36
función de tipo de datos en algún lugar, voy a copiar el nombre de eso, así que
data type function somewhere i'm going to copy the name of that so
9:09:39
ahora déjame hacerte una pregunta, voy a colocar eso aquí, así que ahora
now let me just ask you a question i'm going to just place that right here so now
9:09:43
déjame hacerte una pregunta, como qué en el mundo vamos a hacer ahora mismo, bueno, lo primero que tienes que hacer es que tenemos que especificar algún tipo de valor
let me just ask you a question like what in the world we are going to be doing right now well the first thing which you have to do is that we have to specify some sort of a value
9:09:51
para este tipo aquí, así que cómo vamos a hacer eso, así es como lo vamos a hacer, voy a escribir un signo menor que y aquí tenemos que
for this type right here so how we are going to be doing that this is how we are going to be doing that i'm going to just write a less than sign and here we have to
9:09:59
especificar qué tipo de tipo vamos a proporcionar para este tipo específico de perímetro aquí.
specify like which kind of type we are going to be providing for this specific type perimeter right here.
9:10:04
Como esto va a ser el área del perímetro y aquí tenemos que especificar algún tipo de argumento para este tipo específico aquí.
Like this is going to be the perimeter area and here we have to specify some sort of an argument for this specific type right here.
9:10:09
Así que en este caso, ya sabes, voy a especificar un número aquí. Así que voy a escribir número y tendré que cerrar eso.
So in this case you know what I'm going to just specify like number right here. So I'm going to just write number and I'm going to have to close that.
9:10:16
La siguiente cosa que tienes que hacer es que esta área está totalmente terminada.
The next thing which you have to do like this area is totally done.
9:10:19
Ahora, la siguiente cosa que tienes que hacer es que tenemos que encargarnos de
Now the next thing which you have to do is that we have to take care of
9:10:22
el parámetro de la función aquí o la función toma dos
the function parameter right here or function takes two
9:10:25
parámetros, como el primer parámetro texto es el elemento y
parameters like the first parameter text is the item and
9:10:28
el segundo que toma es un valor predeterminado aquí, así que ahora tenemos que
the second one it takes is a default value right here so now we have to
9:10:31
especificar algún tipo de valor para el elemento y también para el
specify some sort of a value for the item and also for the
9:10:35
valor predeterminado aquí, así que voy a escribir todos mis paréntesis
default value right here so i'm going to just write my all like parentheses
9:10:38
así que déjame quitar eso por un segundo, así que ahora déjame especificar algún tipo de valor para el elemento y también para este valor predeterminado aquí, está bien, así que voy a
like that you know let me just remove that for a second so now let me just specify some sort of a value for the item and also for this default value right here okay so i'm going to
9:10:46
solo especificar como 10 para el ítem y también 24 el predeterminado
just specify like 10 for the item and also 24 the default
9:10:49
valor aquí así que eso está totalmente satisfecho así que ahora
value right here so that is totally satisfied so now
9:10:52
aquí voy a escribir este código una vez más que no confundió
here i'm going to just write this code once again that did not
9:10:55
así que esto es cómo vamos a estar registrando o creando
confuse you so this is how we are going to be registering or creating
9:10:59
nuestra primera función genérica y así es como vamos a estar
our first generic function and this is how we are going to be
9:11:02
usando eso así que también puedes envolver eso con el console log pero tú
using that so you can also wrap that with the console log but you
9:11:05
sabes qué déjame solo lanzar algún tipo de variable como const res y
know what let me just throw in some sort of variable like const res and
9:11:08
va a ser igual a esta llamada de función genérica y ahora déjame solo registrar este res aquí en la consola está bien así que si guardo este archivo y
it's going to be equals to this generic function call and now let me just log this res right here to the console okay so if i save this file and
9:11:15
ahora déjame solo ejecutar eso así que nos va a dar como 10 y
now let me just run that so it's going to give us like 10 and
9:11:18
también el 20 aquí que es totalmente
also the 20 right here which is totally
9:11:21
increíble puedes volver a ver este video si
amazing you can like re-watch this video if
9:11:24
querías pero no tienes que hacerlo como explico cada cosa sobre
you wanted to but you don't have to like i explain every single thing about
9:11:27
genéricos aquí así que ahora la pregunta es aquí
generics right here so now the question is here
9:11:31
podemos especificar el número aquí podemos también especificar la cadena también sí, totalmente puedes ahora déjame solo duplicar eso y aquí en lugar de escribir un número voy a especificar cadena aquí
we can specify the number right here can we also specify the string as well yep you totally can now let me just duplicate that and here instead of writing a number i'm going to just specify string right here
9:11:43
pero aquí también tenemos que especificar la cadena video así que voy a solo
but here we also have to specify the string video so i'm going to just
9:11:46
escribir como no sé hola y también voy a
write like i don't know hello and i'm going to also
9:11:49
escribir palabra aquí y solo vamos a
write word right here and let's just
9:11:52
cambiar eso a como revolver o algo así este será
change that to like stir or something like that this one will be
9:11:55
solo num y voy a duplicar eso
just num and i'm going to duplicate that
9:11:58
cambiar este a num y este a revolver para
change this one to num and this one to stir for
9:12:02
una cadena ahora déjame solo guardar mi archivo y ahora si ejecuto ahí qué crees que será el resultado ya sabes el resultado pero hey aquí puedes ver que ahora estamos obteniendo hola y nosotros
a string now let me just save my file and now if i run there what do you think will be the result you already know the result but hey here you can see we are now getting hello and we
9:12:11
también estamos obteniendo la palabra aquí así que quiero que pienses en genérico
are also getting the word right here so i want you to think about generic
9:12:14
las funciones son como un componente un componente
functions is like a component a component
9:12:17
que puedes usar en todo tu proyecto aquí puedes ver que lo estamos usando para un
which you can use throughout your project here you can see we're using it for a
9:12:21
número también podemos usar eso para una cadena y también podemos usarlo
number we can also use that for a string and we can also use it
9:12:24
también podemos usar eso para una cadena y también podemos usarlo
for boolean as well so now let me just write a boolean and here we have to just um change that to bool or something like that i'm going to duplicate this kind of code and let me just write a bool and instead of writing hello
9:12:35
déjame quitar ese hola de aquí y verdadero y
let me just remove that hello from here and true and
9:12:39
no sé verdadero una vez más o sabes déjame escribir un falso
i don't know true once again or you know let me just write a false
9:12:42
justo aquí ahora déjame guardarlos y si ejecuto
right here now let me just save them and if i run
9:12:45
mi código ya sabes lo que nos dará, nos dará verdadero y
my code you already know what it will gives us it's going to give us true and
9:12:49
falso justo aquí para los valores, así que si esta es la primera vez
false right here for the values so if this is the first time
9:12:52
que estás viendo una función genérica, puede parecer un poco intimidante
you're watching a generic function so it may look a little bit intimidating
9:12:55
pero confía en mí, no lo es, aquí tenemos que especificar algún tipo de perímetro para, vamos, para un tipo y aquí
but trust me it's not here we have to specify some sort of a perimeter for um come on for a type and here we
9:13:02
tenemos que especificar nuestro propio perímetro para una función específica
have to specify our own perimeter for a specific function
9:13:05
si quisieras, totalmente puedes, pero si no quieres
if you wanted to you totally can but if you don't want to
9:13:08
no tienes que hacerlo, está bien, así que ahora déjame quitar este tipo, voy
you don't have to okay so now let me just remove this type i'm
9:13:12
a mantener presionado ctrl y presionar d, presionar d, d, d
going to just hold ctrl and hit d hit d d d
9:13:15
en lugar de escribir este tipo, también puedes cambiarlo a t
instead of writing this type you can also change that to t
9:13:18
justo aquí, está bien, ahora déjame guardarlos y así es como
right here okay now let me just save them and this is how
9:13:21
normalmente escribimos para funciones genéricas justo aquí y ahora te voy a dar muchos ejemplos usando funciones genéricas, así que vas a tener una
we usually write for generic function right here and now i'm going to give you a lot of example by using generic functions so you're going to have a
9:13:30
gran experiencia ahora mismo, así que sabes, antes de continuar
lot of experience right now so you know what before we move on
9:13:33
a los siguientes temas, quiero explicar una cosa más
to next topics uh i want to explain one more thing
9:13:36
ahora déjame quitar eso, también quitar este también
now let me just remove there also remove this one as well
9:13:39
déjame crear algún tipo de interfaz, así que ahora déjame escribir como interfaz
let me just create some sort of interface so now let me just write like interface
9:13:43
voy a dar un nombre como perro, dentro de este perro vamos a
i'm gonna give a name of like dog inside this dog we're gonna
9:13:46
tener algún tipo de nombre que será string y también la raza en sí
have some sort of a name which will be string and also the breed itself
9:13:50
y la raza también será string justo aquí, así que sabes, en lugar de proporcionar un número o un string o un booleano, también podemos especificar nuestro propio tipo o nuestra propia interfaz justo aquí
and the breed will be also string right here so you know instead of providing a number or a string or a boolean we can also specify our own type or our own interface right here
9:14:00
a una función genérica, así que cómo vamos a hacer eso
to a generic function so how we are going to be doing that so
9:14:03
así es como vamos a hacer eso, así que voy a escribir cons perro
this is how we are going to be doing that so i'm going to just write cons dog
9:14:06
uno o algo así y va a ser igual a ese específico
one or something like that and it's going to be equal to that specific
9:14:09
función así que lo primero que tienes que hacer es que tenemos que especificar algún tipo
function so the first thing that you have to do is that we have to specify some sort
9:14:13
de un valor para este perímetro aquí así que vamos
of a value for this perimeter right here so we are going
9:14:16
a especificar el tipo de perro así que ahora déjame solo especificar
to be specifying the type of dog so now let me just specify
9:14:19
eso y también podemos especificar nuestros propios valores para
that and we can also specify our own values for
9:14:22
este elemento y también para el valor predeterminado así que lo que quiero hacer es que voy a especificar algún tipo de valor
this item and also for the default value as well so what i want to do is that i'm going to specify some sort of value
9:14:28
para el nombre uh no puedo sí
for the name uh i totally can't yeah
9:14:31
sabes déjame solo proporcionar como algún tipo de un nombre aquí y el
you know let me just provide like some sort of a name right here and the
9:14:34
nombre será no sé amigo o algo así no soy tan bueno con los perros
name will be i don't know buddy or something like that i'm not that much good with dogs
9:14:37
ahora déjame solo escribir raza y la raza será esta raza
now let me just write breed and the breed will be this breed
9:14:41
aquí no puedo ni pronunciar este nombre déjame también proporcionar un
right here i can't even pronounce this name let me also provide a
9:14:44
coma y también voy a especificar el nombre una vez más y el
comma and i'm going to also specify the name once again and the
9:14:47
nombre se establecerá en predeterminado y también déjame solo
name will be set to default and also let me just
9:14:50
proporcionar algún tipo de raza y la raza será como
provide some sort of a breed and the breed will be like
9:14:53
desconocida o algo así ahora déjame solo vender allí el
unknown or something like that now let me just sell there the
9:14:56
siguiente cosa que quiero hacer es que voy a solo registrar allí en una consola como perro uno vamos
next thing which i want to do is i'm going to just log there to a console like dog one let's
9:14:59
solo vender allí y ejecutar allí así que nos va a dar como nuestro
just sell there and run there so it's going to give us like our
9:15:02
nombre de este nombre que puedes ver aquí como el nombre
name of this name which you can see right here like the name
9:15:05
de birdie la raza de esta raza y también tenemos otro
of birdie the breed of this breed and also we have another
9:15:08
uno como el nombre se establecerá en predeterminado y la raza se establecerá en desconocida
one like name will be set to default and breed will be set to unknown
9:15:12
ok así que esos son ahora déjame solo limpiar
okay so that's them now let me just clear
9:15:15
esto y eso está allí así que ahora la siguiente cosa que quiero hacer es que voy a eliminar cada cosa de aquí y ahora déjame solo darte un ejemplo más que será funciones genéricas para obtener pares de clave valor aleatorios de un objeto.
this out and that's there so now the next thing which i want to do is that i'm going to remove every single thing from here and now let me just give you one more example which which will be generic functions to get a random key value pairs from an object.
9:15:27
Así que cómo vamos a hacer eso? Bueno, primero que nada, tenemos que crear nuestras funciones genéricas.
So how we are going to be doing that? Well, first of all, we have to create our generic functions.
9:15:32
Así que déjame solo escribir obtener par de clave valor aleatorio o algo así.
So let me just write get random key value pair or something like that.
9:15:37
Y voy a especificar el tipo de, ya sabes, primero que nada, déjame solo escribir mi firma genérica aquí.
And I'm going to specify the type of, you know, first of all, let me just write my generic signature right here.
9:15:43
Así que va a tomar un T como parámetro de tipo aquí. Y voy a especificar algún tipo de objeto.
So it's going to take one T like type parameter right here. And I'm going to specify some sort of object.
9:15:49
Y voy a anotar eso como una clave. déjame proporcionar una clave
And I'm going to annotate that as a key. let me just provide a key
9:15:52
y va a tomar esa clave como una cadena y
and it's going to take that key as a string and
9:15:55
también fuera de este objeto también vamos a proporcionar nuestro
also outside from this object we are going to be also providing our
9:15:58
propio tipo aquí que especificamos aquí dentro de este perímetro
own type right here which we specified right here inside this perimeter
9:16:02
área está bien, así que eso es o
area okay so that's that or
9:16:05
sabes que no fuera de entonces, déjame cortar eso y ponerlo aquí
you know what not outside from then now let me just cut that and put it right here
9:16:08
y ahora déjame especificar el valor de retorno, así que voy a
and now let me just specify for the return value so i'm going to
9:16:11
simplemente escribir como, no sé, el objeto de clave que será una cadena y también voy a especificar el valor que se establecerá en tipo o sí, su tipo que vamos a especificar
just write like uh i don't know the object of key which will be string and i'm going to also specify the value which will be set to type or yeah their type which we are going to be specifying
9:16:21
en unos segundos, así que eso es, ahora déjame guardar ahí y
in a few seconds so that's that now let me just save there and
9:16:24
si paso el mouse sobre eso, así que función cuyos tipos declarados
if i hover my mouse over to it so function whose declared types
9:16:27
no son ni indefinidos, ni void, ni any, debe devolver como
is neither undefined void nor any must return as
9:16:30
algunos valores, vamos TypeScript, dame un respiro ahora
some values come on timescript give me a break now
9:16:33
déjame escribir el código, entonces sabrás de qué estoy hablando, así que
let me just write the code then you will get to know what i'm talking about so
9:16:37
sabes, déjame escribir algún tipo de declaración de retorno para que deje de dar
you know let me just write some sort of a return statement so it stopped giving
9:16:40
me ese error aquí, así que ahora déjame escribir nuestra lógica, así que voy a escribir como const keys y va a ser igual a este objeto punto keys aquí y aquí tenemos que especificar nuestro
me that error right here so now let me just write our logic so i'm going to just write like cons keys and it's going to be equals to this object dot keys right here and here we have to specify our
9:16:49
objeto que estamos obteniendo como un perímetro y
object which we are getting as a perimeter and
9:16:52
también déjame obtener una clave aleatoria o clave aleatoria
also let me just get a random keys or ran key
9:16:55
o algo así y va a ser igual a esas claves y aquí tenemos que
or something like that and it's going to be equals to that keys and here we
9:16:58
usar nuestro math.floor y déjame poner un
have to use our math.floor and let me just put a
9:17:02
math.random, así que queremos obtener un número aleatorio de ahí de
math.random so we want to get a random number from there from
9:17:05
donde de las claves punto vamos claves
where from the keys dot come on keys
9:17:08
punto oh Dios mío, no ahí, punto izquierda, ahí vamos, así que eso es, ahora debajo de estas claves aleatorias, ¿qué quieres hacer? solo tenemos que devolver algo, así que ¿qué quieres
dot oh my god not there dot left there we go so that's that now underneath these random keys what do you want to do we just have to return something so what do you want to
9:17:17
devolver? solo queremos devolver la clave de la clave aleatoria y
return we just want to return the key of random key and
9:17:20
también voy a devolver el valor y el valor que voy a devolver
i'm going to also return the value and the value i'm going to just return
9:17:23
el objeto y aquí tenemos que especificar esa clave aleatoria aquí ahora
the object and here we have to specify that random key right here now
9:17:27
déjame guardar eso, pero no sé por qué estamos obteniendo este error
let me just save that but i don't know why we are getting this error right
9:17:30
aquí, en lugar de escribir este arreglo, tenemos que cambiar eso
here oh instead of writing this array we have to change that
9:17:33
a objeto, así que ahora déjame cambiar ese objeto y también eliminar
to object so now let me just change that object and also remove
9:17:36
eso, así que sí, ahora déjame usar eso aquí, así que lo primero que quiero hacer es crear algún tipo de objeto, luego de ese objeto vamos
that so yeah now let me just use that right here so the first thing which i want to do is that i'm going to just create some sort of object then from that object we are going
9:17:44
a obtener algún tipo de claves aleatorias aquí, así que ahora déjame hacer eso, así que lo primero que quiero hacer es crear algún tipo de objeto de cadena, así que const string
to be getting some sort of a random um keys right here so now let me just do that so the first thing which i want to do is i'm going to just create some sort of a string object so const string
9:17:53
o bj o objeto, más bien, y va a ser igual
or bj or object rather and it's going to be equals
9:17:56
a este objeto y voy a proporcionar la propiedad de un
to this object and i'm going to just provide the property of a
9:17:59
b de banana y también uno para la cereza
and it's going to be equals to apple and i'm going to also specify the
9:18:02
b de plátano y también uno para la cereza
b of banana and also one for the cherry
9:18:06
o no sé, lo que quieras llamar eso, así que sí, eso es, ahora déjame solo registrar en la consola o sabes que ni siquiera estamos usando nuestro
or i don't know whatever you want to call that so yeah that's then now let me just log to the console or you know we are not even using our
9:18:13
función, así que ahora déjame solo usar mis funciones genéricas para obtener
function so now let me just use my generic functions to get
9:18:16
valores aleatorios de este objeto aquí, así que solo voy a escribir como
random values from this object right here so i'm going to just write like
9:18:19
obtener valores aleatorios, el nombre de mi función y
get random values my function name and
9:18:22
lo primero que tienes que hacer es que tenemos que satisfacer el tipo
the first thing which you have to do is that we have to satisfy the type
9:18:25
bien, así que el tipo que voy a proporcionar es como una cadena, ¿verdad?
okay so the type i'm going to provide like a string right
9:18:28
aquí porque actualmente estamos trabajando con una cadena y luego tenemos que especificar el valor que este objeto está tomando, así que ya creé este objeto aquí, así que voy a copiarlo y ponerlo aquí, así que ahora déjame solo registrar allí en la consola, así que constres
here because currently we are working with a string and then we have to specify the value which this object is taking right so i already created this object right here so i'm going to copy there and put it right here so now let me just log there to the console so constres
9:18:40
y registrar allí en la consola como res semi archivo y ejecutar
and log there to the console like res semi file and run
9:18:43
ahí, así que nos va a dar como la clave de a y
there so it's going to give us like key of a and
9:18:46
el valor de manzanas, así que ahora déjame solo volver a ejecutar allí una vez más y
value of apples so now let me just rerun there once again and
9:18:50
nos va a dar la clave de c y el valor será cereza o
it's going to give us the key of c and the value will be sherry or
9:18:53
cereza, lo que quieras llamar eso y aquí puedes ver
cherry whatever you want to call that and here you can see
9:18:56
tenemos la clave de b y el valor de plátano aquí, así que
we have the key of b and the value of banana right here so
9:19:00
nos va a dar claves aleatorias de este objeto aquí, así que así es como vamos a estar probando para una cadena, así que ahora déjame solo duplicar
it's going to give us a random keys from this object right here so this is how we are going to be testing for a string so now let me just duplicate
9:19:06
eso y ponerlo aquí al final, voy a cambiar
at that and put that right here at the end i'm going to change
9:19:09
ese objeto de número y va a ser igual a como
that number object and it's going to be equals to like
9:19:12
una especie de número como voy a cambiar este a uno y
some sort of a number like i'm going to change this one to one and
9:19:15
este a dos y este a
this one to two and this one to
9:19:19
tres aquí voy a cambiar también estos a b
three right here i'm going to also change these a b
9:19:22
y c así que voy a cambiar eso a uno y dos y
and c so i'm going to just change that to one and two and
9:19:25
también este a tres y voy a
also this one to three and i'm going
9:19:28
usar mi función, mi función genérica para ser preciso, así que primero voy a usar eso para obtener valores aleatorios y en este caso tenemos
to use my function my generic function to be precise so first of all i'm going to use that get random values and in this case we
9:19:35
que especificar el número porque estamos tomando el número aquí y aquí tenemos que especificar para los paréntesis, tenemos que especificar este objeto, así que ahora déjame copiar y colocar eso aquí
have to specify the number because we are taking the number right here and here we have to specify for the parentheses we have to specify this object so now let me just copy then place that right here
9:19:45
y ahora voy a registrar eso en la consola como, en lugar de escribir res, voy a escribir como par de números aleatorios y ahora déjame registrar ahí par de números aleatorios no cadena
and now i'm going to also log there to the console like uh instead of writing res i'm going to write like random number pair and now let me just log there random number pair not string
9:19:57
déjame copiar y ponerlo aquí, enviar mi archivo y ejecutar
let me just copy then put it right here send my file and run
9:20:00
así que nos va a dar la clave, quiero decir, nos va a dar
so it's going to give us the key i mean like it's going to give us
9:20:03
sí, la clave de dos y el valor de dos aquí, está bien
yeah the key of two and the value of two right here okay
9:20:06
así que ahora déjame volver a ejecutar eso una vez más, así que nos va a dar
so now let me just rerun there once again so it's going to give us
9:20:09
la clave de tres y también el valor de tres, así que sí, probamos
the key of three and also the value of three so yeah we test
9:20:13
eso y está funcionando totalmente bien, ahora lo siguiente
it and it is working totally a-okay now the next
9:20:16
cosa que quiero hacer es que voy a crear una función genérica que filtre
thing which i want to do is that i'm going to just create a generic function that filter
9:20:19
arreglo basado en una condición, así que sí, totalmente
array based on a condition so yeah we totally
9:20:22
podemos proporcionar condiciones también, así que ahora déjame quitar este código de aquí y por cierto, puedes encontrar todo el código en mi repositorio de GitHub
can provide conditions as well so now let me just remove this coding from here and by the way you can find all of the coding in my gahub repository
9:20:29
y el enlace estará en la descripción a continuación, así que ahora déjame crear una función, voy
and link will be in the description below so now let me just create a function i'm
9:20:32
a darle un nombre como filtrar arreglo
going to give a name of like filter array
9:20:35
o algo así y también voy a especificar el
or something like that and i'm going to also specify the
9:20:39
parámetro de tipo y en este caso también tendré que
type parameter and in this case i'm going to also have to
9:20:42
especificar este arreglo aquí y el tipo se establecerá en tipo
specify this array right here and the type will be set to type
9:20:45
de arreglos y también voy a especificar la condición, así que
of arrays and i'm going to also specify the condition so
9:20:48
condición, ahí vamos, y la condición será el ítem y también su tipo aquí y va a devolver el booleano, vamos
condition there we go and the condition will be item and also their type right here and it's going to return the boolean come on
9:20:56
booleano, si puedo obtener eso, déjame volver y
boolean if i can get that let me just go back and
9:20:59
para el valor de retorno voy a especificar el tipo de arreglos correcto
for the return value i'm going to specify the type of arrays right
9:21:02
aquí así que ahora déjame escribir mi código, así que voy a escribir como
here so now let me just write my code so i'm going to just write like
9:21:05
devolver array punto filtrar o javascript como o
return array dot filter or javascript like or
9:21:09
método de filtrado de javascript regular y voy a especificar el ítem
regular javascript filter method and i'm going to specify the item
9:21:12
en este caso y aquí tenemos que escribir nuestra condición y para
in this case and here we have to write our condition and for
9:21:15
esta condición tenemos que especificar el perímetro del ítem correcto
this condition we have to specify the perimeter of item right
9:21:18
aquí así que ahora lo siguiente que tienes que hacer es que tenemos que crear algún tipo de arreglo para que podamos iterar sobre el arreglo y podamos realizar algún tipo de lógica
here so now the next thing which you have to do is that we have to create some sort of array so that we can iterate over through the array and we can perform some sort of a logic
9:21:25
en ese arreglo así que voy a escribir como const arreglo de números y es
on that array so i'm going to just write like const number array and it's
9:21:28
va a ser igual a como no sé uno dos tres cuatro
going to be equals to like i don't know one two three four
9:21:32
cinco seis siete ocho nueve diez supongo
five six seven eight nine ten i guess
9:21:35
diez estaría bien así que lo que quiero hacer es que voy a obtener un e1
ten would be fine so what i want to do is that i'm going to just get a e1
9:21:38
números de eso así que voy a usar como const e1 números
numbers from that so i'm going to just use like const e1 numbers
9:21:41
y va a ser igual a mi arreglo filtrado uh
and it's going to be equals to my filter array uh
9:21:44
función genérica aquí así que lo primero que quiero hacer es que voy a especificar el número y lo siguiente que quiero hacer es que voy a especificar el arreglo de números aquí que es este número
generic function right here so the first thing which i want to do is i'm going to just specify the number and the next thing which i want to do is that i'm going to just specify the number array right here which is this number
9:21:53
arreglo y lo siguiente que tienes que hacer es que tenemos que especificar la condición
array and the next thing which you have to do is that we have to specify the condition
9:21:56
función aquí así que voy a proporcionar una coma y
function right here so i'm going to provide a comma and
9:21:59
ahora déjame especificar la función de condición así que voy a especificar el
now let me just specify the condition function so i'm going to specify the
9:22:03
número y también voy a usar como si num mod
number and i'm going to also just use like if num mod
9:22:06
2 es igual a cero triple igual a cero así que
2 is equals to zero triple equals to zero so
9:22:09
nos va a dar los números e1 ahora déjame registrarlos en la consola como e1
it's going to give us the e1 numbers now let me just log there to the console like e1
9:22:13
números ahora déjame volver y guardar mi archivo y
numbers now let me just go back and save my file and
9:22:16
así es como se ve ahora déjame ejecutar mi código así que nos va a dar como 2 4 6 8 y 10 que son totalmente
this is how it looks like now let me just run my code so it's going to give us like 2 4 6 8 and 10 which are totally
9:22:23
correctos y estos son números pares en matemáticas
correct and these are even numbers in mathematics
9:22:26
y sí y también typescript también está bien
and yeah and also typescript as well okay
9:22:29
así que lo que quiero hacer es que el siguiente ejemplo es
so what i want to do is that the next example is
9:22:33
usando el array de cadenas así que déjame crear un array
using the array of strings so let me just create array
9:22:36
de cadenas así que const array de cadenas y va a ser igual a
of strings so const string array and it's going to be equals to
9:22:39
como uh no sé manzana y también plátano
like uh i don't know apple and also banana
9:22:43
y también algún tipo de cereza o cherry como quieras llamarlo y muerto o lo que sea
and also some sort of a sherry or cherry whatever you want to call that and dead or whatever
9:22:48
así que ahora déjame obtener palabras cortas de este array así que voy a usar
so now let me just get a short words from this array so i'm going to use
9:22:52
como palabras cortas y va a ser igual a
like short words and it's going to be equals to
9:22:55
como filtrar array mi función genérica y voy a especificar la cadena
like filter array my generic function and i'm going to specify the string
9:22:58
valor y para mi perímetro actual voy a especificar
value and for my actual perimeter i'm going to specify
9:23:01
como array de cadenas que ya estamos creando y ahora déjame
like string array which we are already creating and now let
9:23:04
simplemente especificar la condición uh y para esta condición
me just specify the condition uh and for this condition
9:23:08
va a tomar una palabra y palabra vamos palabra punto longitud uh es menor que seis así que solo nos da eso así que como palabras cortas
it's going to take a word and word come on word dot length uh is less than six so only gives us them so like short words
9:23:17
si envío mi archivo y ejecuto eso así que solo nos va a dar el array corto
if i send my file and run that so it's going to only give us the short array
9:23:21
así que aquí puedes ver que tenemos una manzana y también tenemos
so here you can see we have an apple and we also have
9:23:24
un muerto así que sí eso también es totalmente correcto y
a dead so yeah that's also totally correct and
9:23:27
sí ahora la siguiente cosa que quiero hacer es que voy a
yeah now the next thing which i want to do is that i'm
9:23:30
también crear una interfaz aquí así que ahora déjame crear
going to also create an interface right here so now let me just create
9:23:33
una interfaz voy a escribir como interfaz y también voy a especificar el nombre de la fruta y el nombre se establecerá en algún tipo de cadena y también voy a especificar algo
an interface i'm going to just write like interface and i'm going to also specify the fruit name to it and the name will be set to some sort of a string and i'm going to also specify some
9:23:42
de un color como cadena también ahora déjame
sort of a color like string as well now let me just
9:23:45
usar const fruta array de frutas
use const fruit fruit array
9:23:49
y aquí tenemos que anotar eso con
and here we have to annotate that with
9:23:53
nuestra interfaz de fruta aquí y va a ser igual a este array y
our fruit interface right here and it's going to be equals to this array and
9:23:57
aquí podemos especificar muchas frutas aquí como no sé
here we can specify a lot of fruits right here like i don't know
9:24:00
manzana y también el color se establecerá en rojo y no deberían ser array debería ser un objeto en lugar de eso así que ahora déjame
apple and also the color will be set to red and they shouldn't be array it should be an object rather so now let me just
9:24:08
cambiar eso a objeto déjame proporcionar mi coma y solo
change that to object let me provide my comma and just
9:24:11
para un poco más como no sé plátano plátano
for a little bit more like i don't know banana banana
9:24:14
es amarillo, sí, y yo
is yellow yep and i'm
9:24:18
también voy a especificar el jerez de rojo, así que también voy a hacer esto en mayúscula R y también esto en mayúscula R, así que ahora déjame usar mi
going to also specify the sherry of red as well i'm going to also make this one uppercase r and also this one uppercase r as well so now let me just use my
9:24:28
función genérica que es filtrar array, déjame usar eso en este array aquí, así que
generic function which is filter array let me just use that on this array right here so
9:24:33
lo que quiero hacer es que solo voy a obtener frutas rojas
what i want to do is i'm going to just get a red fruits
9:24:36
del array, así que va a ser igual a filtrar array
from the array so it's going to be equals to filter array
9:24:40
y aquí tenemos que especificar esa fruta y cerrar eso y
and here we have to specify that fruit and close that and
9:24:43
la siguiente cosa que tienes que hacer es que también tenemos que satisfacer nuestro
the next thing which you have to do is that we also have to satisfy our
9:24:46
perímetro área, así que ahora déjame copiar eso y poner nuestro array
perimeter area so now let me just copy that and put our array
9:24:49
y también voy a especificar nuestra condición, así que fruta
and i'm going to also specify our condition so fruit
9:24:52
y aquí lo que tienes que hacer es que tenemos que especificar si la fruta
and here what you have to do we have to specify if fruit
9:24:55
punto color es igual a rojo
dot color is triple equals to red
9:24:59
así que, ¿qué quieres hacer? Solo queríamos registrar sus frutas rojas
so what do you want to do we just wanted to log their red fruits
9:25:02
aquí, así que si guardo mi archivo y ejecuto eso, así que va a
right here so if i sell my file and run that so it's
9:25:05
darnos estas frutas aquí, el color
going to give us these fruits right here the color
9:25:08
será rojo, así que aquí puedes ver que tenemos un nombre de manzana y
will be red so here you can see we have a name of apple and
9:25:12
el color es rojo y también tenemos un jerez o cereza y el color también es rojo, así que ahora estamos llegando allí dentro de una consola, lo que significa que están funcionando perfectamente y aprendimos
the color is red and we also have a sherry or cherry and the color is also red so we are now getting there inside a console so which means like they are totally working a-okay and we learned
9:25:23
mucho sobre funciones genéricas, pero eso no es todo
about generic functions a lot but that's not it
9:25:27
bebé, tenemos que hacer mucho más que eso, ahora déjame hablarte de
baby we gotta do a lot more than that now let me just talk to
9:25:30
una función genérica que toma múltiples
you about generic function but which takes multiple
9:25:33
tipos, ahora déjame crear una función genérica que invierte el orden
types now let me just create a generic function which reverts the order
9:25:37
de dos valores, así que voy a crear mi función genérica
of two values so i'm going to just create my generic function so
9:25:40
así que voy a darle un nombre como par inverso
i'm going to give a name of like reverse pair
9:25:43
o algo así, y en este caso tenemos que especificar dos tipos de perímetro aquí, está bien, así que dos
or something like that and in this case we have to specify two types of perimeter right here okay so two
9:25:50
tipos de perímetro, puedes abreviarlo como t y
types of perimeter you can abbreviate that to t and
9:25:53
u, o puedes abreviarlo como quieras y
u or you can abbreviate that to anything you want and
9:25:56
ahora déjame escribir como valor uno justo aquí
now let me just write like value one right here
9:26:00
y para el valor uno vamos a especificar t y ahora
and for the value one we are going to be specifying t and now
9:26:03
déjame también escribir un valor de dos y para el valor dos
let me just also write a value of two and for the value two
9:26:06
podemos especificar el u justo aquí así que ahora déjame regresar
we can specify the u right here so now let me just return
9:26:09
el u y t y vamos a estar invirtiendo el orden de eso como que no vamos a hacer nada loco pero solo tenemos que escribir como
the u and t and we are going to be just reversing the order of that like we're not going to be doing anything crazy but we just have to write like
9:26:16
valor dos y valor uno justo aquí y ahí vamos
value two and value one right here and there we go so
9:26:19
ahora déjame crear algún tipo de ejemplo como invertido
now let me just create some sort of example like reversed
9:26:22
uh cambiemos eso a const invertido
uh let's just change that to const reversed
9:26:25
par y va a ser igual al par invertido correcto
pair and it's going to be equals to the reverse pair right
9:26:28
aquí y dentro tenemos que especificar como hola y
here and inside there we have to specify like hello and
9:26:32
también 20 o algo así y ahora déjame registrar en la consola este invertido voy a copiar luego colocarlo justo aquí
also 20 or something like that and now let me just log to the console this reversed i'm going to copy then place it right here
9:26:38
guardar mi archivo ahora déjame ejecutar eso así que nos va a dar como uh 20 y hola justo aquí
save my file now let me just run that so it's going to give us like uh 20 and hello right here
9:26:45
aquí estamos especificando hola y 20 así que
here we are specifying hello and 20 so
9:26:48
nos va a dar como 20 y hola no sé por qué pero
it's going to give us like 20 and hello i don't know why but it
9:26:51
ahora nos está dando algún tipo de error así que ahora déjame limpiar la terminal una vez
is now giving us some sort of an error so now let me just clear out the terminal once
9:26:55
más y volver a ejecutar eso así que en este caso nos va a dar
again and rerun that so in this case it's going to give
9:26:58
como 20 y hola lo cual es totalmente asombroso así que aquí
us like 20 and hello which is totally amazing so here
9:27:01
puedes ver cómo vamos a estar especificando múltiples tipos
you can see this is how we are going to be specifying multiple types
9:27:04
de perímetro justo aquí así que la última cosa que tienes que
of perimeter right here so the final thing which you have to
9:27:07
aprender sobre genéricos es clases genéricas así que no estamos
learn about generics is a generic classes so we are not
9:27:10
a hacer nada loco pero vamos a estar creando una clase y
going to be doing anything crazy but we are going to be just creating a class and
9:27:14
voy a dar un nombre como caja y aquí tenemos que especificar el
i'm going to just give a name of like box and here we have to specify the
9:27:17
dinámico o no dinámico pero el perímetro para
dynamic or not a dynamic but the perimeter for
9:27:20
un tipo justo aquí así que voy a especificar la propiedad de
a type right here so i'm going to specify the property of
9:27:23
privado y contenido justo aquí también va a
private and content right here it's going to also
9:27:27
etiquetar su perímetro aquí y para el constructor, ¿qué tienes que hacer? voy a eliminar este perímetro y solo voy a establecer eso como contenido inicial aquí
tag their perimeter right here and for the constructor what do you have to do i'm going to remove this perimeter and i'm going to just set that to initial content right here
9:27:34
y el contenido inicial también se establecerá en este tipo y solo voy a decir como esto punto contenido
and initial content will be also set to this type and i'm going to just say like this dot content
9:27:39
ahora es igual a este contenido inicial aquí debajo
is now equals to this initial content right here underneath
9:27:43
ahí vamos a definir dos métodos, así que obtener contenido y
there we are going to be defining two methods so get content and
9:27:46
obtener contenido no va a tomar ningún perímetro, así que dentro de ahí
get content is not going to take any perimeter so inside there
9:27:49
¿qué quieres hacer? solo queremos devolver como esto punto
what do you want to do we just want to return like this dot
9:27:52
contenido solo para obtener el contenido aquí y podemos
content just to get the content right here and we can
9:27:55
también establecer el contenido, así que establecer c1 t y t y
also set the content so set c1 t and t and
9:27:59
voy a especificar como nuevo contenido y ese nuevo contenido
i'm going to just specify like new content and that new content
9:28:02
etiquetará ese perímetro y no voy a devolver nada de
will tag that perimeter and i'm not going to return anything from
9:28:05
ahí, así que solo voy a especificar el vacío para ello, ahora déjame ir
there so i'm going to just specify the void to it now let me just go
9:28:08
de regreso y aquí tenemos que escribir como esto.contenido es ahora
back and here we have to just write like this.content is now
9:28:11
igual al nuevo contenido aquí, ahora déjame vender eso
equals to the new content right here now let me just sell that
9:28:14
y ejecutar eso, ahora la siguiente cosa que quiero hacer es que
and execute that now the next thing which i want to do is that
9:28:17
voy a crear una instancia de eso, así que voy a usar
i'm going to just create instance of that so i'm going to use
9:28:20
como nueva caja y aquí tenemos que especificar algún tipo de valor para
like new box and here we have to specify some sort of a value for
9:28:24
el perímetro o tipo perímetro, así que solo voy a usar
the perimeter or type perimeter so i'm going to just use
9:28:27
como cadena y solo voy a proporcionar un valor real para esa función canción o no función, sino clase como hola tipo script y ahora déjame
like string and i'm going to just provide an actual value for that function song or not function but class like hello type script and now let me just
9:28:35
almacenar en algún tipo de variable como caja de cadena o
store in some sort of variable like string box or
9:28:38
algo así y ahora déjame registrar en la consola como caja de cadena
something like that and now let me just uh log to the console like string box
9:28:42
uh, que tenemos aquí y solo vamos a obtener o
uh which we have right here and we are going to be just getting or
9:28:46
ejecutar este método aquí como obtener contenido y
executing this method right here like get content and
9:28:49
ahora déjame ejecutar eso, volver, así es como el código
now let me just execute that go back this is how the code
9:28:52
se ve y ahora si ejecuto allí, así que nos va a usar, uh
looks like and now if i run there so it's going to use us uh
9:28:55
vaya, no nos está dando un error, oh, no debería ser igual a, tenemos que anotar eso, vamos, déjame guardar
wow it's not giving us an error oh it should not be equals to we have to annotate that come on let me just save
9:29:04
ahí y vuelve a ejecutar una vez más, así que nos va a dar hola
there and rerun there once again so it's going to give us hello
9:29:07
typescript aquí, pero podemos hacer cosas más locas que
timescript right here but we can do crazier stuff than
9:29:10
ahí, así que también puedo establecer el contenido, así que solo voy a
there so i can also set the content so i'm going to just
9:29:13
escribir como no sé string box punto
write like i don't know string box dot
9:29:16
establecer contenido y puedo especificar cualquier contenido que
set content and i can specify any content i
9:29:19
quiero como nuevo contenido, editar o algo así
want like new content edit or something like
9:29:22
eso y sabes que solo voy a poner
that and you know i'm going to just put
9:29:25
este aquí y duplicar ahí y ponerlo también al final como
this one right here and duplicate there and put it also at the end as
9:29:29
bueno, así que ahora déjame guardar ahí y ejecutar una vez más, así que
well so now let me just save there and run there once again so
9:29:32
nos va a dar como hola typescript y
it's going to give us like hello typescript and
9:29:35
nuevo contenido editar aquí, está bien, así que lo cual es totalmente
new content edit right here okay so which is totally
9:29:38
está bien, así que ahora déjame también ejecutar esta clase específica
okay so now let me just also run this specific class
9:29:41
para los números también, así que solo voy a eliminar eso
for the numbers as well so i'm going to just remove that
9:29:45
de aquí y déjame acercar, voy a crear un
from here and let me just zoom in i'm going to create a
9:29:48
cuadro de número y va a ser igual a como nuevo cuadro
number box and it's going to be equals to like new box
9:29:51
y para el perímetro voy a especificar número y también
and for the perimeter i'm going to specify number and also
9:29:54
20 o algo así y debajo de eso también vamos a estar
20 or something like that and underneath that we're going to be also
9:29:58
usando como sabes, déjame registrar el valor en la consola como
using like you know let me just log the value to the console like
9:30:01
número cuadro punto obtener contenido y ejecutar
number box dot get content and execute
9:30:04
eso si guardo ahí y ejecuto, así que nos va a dar como 20 totalmente
that if i save there and run there so it's going to give us like 20 totally
9:30:07
funcionando, ahora déjame usar eso para establecer el valor número
working now let me just use that for setting the value number
9:30:12
cuadro, vamos, si puedo solo oh Dios mío, cuadro de número
box come on if i can just oh my god number box
9:30:15
ahí vamos, punto establecer contenido ahora va a tomar como 100 aquí y también voy a registrar ahí en la consola, así que
there we go dot set content is now going to take like 100 right here and i'm going to also log there to the console so
9:30:21
ahora déjame copiar eso y colocar eso aquí, archivo semi y ejecutar
now let me just copy that and place that right here semi file and run
9:30:24
ahí, así que nos va a dar como 20 y también el 100
there so it's going to give us like 20 and also the 100
9:30:28
palabra aquí así que sí, eso fue todo sobre genéricos
word here so yeah that was it about generics
9:30:31
en typescript y espero que los ames, está bien
in typescript and i hope you love them okay
9:30:35
así que sí, a continuación vamos a aprender sobre la reducción de tipos en
so yeah next we are going to be learning about type narrowing in
9:30:38
typescript, así que ahora aprendamos sobre la reducción de tipos en typescript, así que la reducción de tipos es el proceso de refinar el tipo de una variable dentro de un bloque condicional de código y esto te permite escribir código más preciso y seguro en cuanto a tipos.
typescript so now let's learn about type narrowing in typescript so type narrowing is the process of refining a variable type within a conditional block of code and this allows you to write more precise and type save code.
9:30:49
Así que, ¿cómo vamos a lograr una reducción de tipos? Hay muchas maneras de lograr la reducción de tipos, pero en esta sección específica solo vamos a aprender sobre los guards de tipo, el instanceof y también los tipos de inserción.
So how in the world we are going to be achieving a type narrowing? There are a lot of ways to achieve the type narrowing but in this specific section we are going to be just learning about type guards, the instance of and also insertion types.
9:31:01
Está bien, así que ahora empecemos desde el primero, que son los guards de tipo.
Okay so now let's just start from the first one which is the type guards.
9:31:04
Así que los guards de tipo son mecanismos que ayudan a TypeScript a entender y reducir los tipos de manera más precisa y un guard de tipo común es el operador typeof aquí mismo.
So type guard are mechanism that help TypeScript understand and narrow down the types more precisely and one common type guard is the type of operator right here.
9:31:13
¿Cómo se verá el código? Así es como se verá el código
So how the code is going to look like? This is how the code is going to look like
9:31:16
así que puedes tomar una captura de pantalla de eso o simplemente puedes pausar
so you can take a screenshot of that or you can just pause
9:31:19
el video y escribir el código tú mismo, pero ahora voy
the video and write the code by yourself but now i'm
9:31:22
a seguir adelante y escribir el código y entonces sabrás de qué estoy hablando, así que
going to go ahead and write the code and then you'll get to know what i'm talking about so
9:31:25
lo primero que quiero hacer es definir un tipo de unión como
the first thing which i want to do is i'm going to just define a union type like
9:31:29
mi tipo y va a ser igual a una cadena o un
my type and it's going to be equals to a string or a
9:31:32
número aquí mismo, así que ahora debajo de eso también vamos a crear una función, le voy a dar un nombre como ejemplo o función, va a tomar un valor y el tipo de valor será mi tipo aquí mismo
number right here so now underneath there we're going to be also creating a function i'm going to give a name of like example or function rather it's going to take a value and the value type will be my type right here
9:31:43
y para la declaración de retorno, ¿qué tienes que hacer? Solo voy a especificar
and for the return statement what do you have to do i'm going to just specify
9:31:46
el void porque no vamos a devolver ningún valor de allí, así que
the void because we are not going to be returning any value from there so
9:31:49
por eso especificamos void aquí mismo, así que ahora déjame usar mi primer
that's why we specify void right here so now let me just use my first
9:31:53
guard de tipo que se llama typeof aquí mismo
type guard which is called a type of right here
9:31:56
si el tipo del valor es estrictamente igual a string
if the type of the value is triple equals to string
9:31:59
así que, ¿qué quieres hacer? Solo queremos registrar en la consola value.toUpperCase aquí y ahora déjame ejecutar eso, así que si guardo mi archivo, ¿qué estamos
so what do you want to do we just want to log to the console value.2 uppercase right here and now let me just execute that so if i save my file so what are we
9:32:08
haciendo actualmente aquí? Así que si paso el mouse sobre el valor
currently doing right here so if i hover my mouse over to the value
9:32:11
así que, ¿qué estamos obteniendo? Ahora estamos obteniendo que el valor está ahora
so what are we getting we are now getting the value is now
9:32:14
actualmente establecido en string, así que, ¿qué está pasando si
currently set to string so what's going on if
9:32:17
simplemente lo pongo aquí arriba y ahora déjame guardar allí y
i just put there right here at the top and now let me just save there and
9:32:20
aquí puedes ver muy rápidamente que nos dará este error aquí si yo
here you can see very quickly it's going to give us this error right here if i
9:32:23
si paso el mouse sobre esto, nos dará este error como um
hover my mouse over to it so it's going to give us this error like um
9:32:26
la propiedad.2 mayúsculas no existe en un tipo mi
property.2 uppercase does not exist on a type my
9:32:30
tipo aquí, pero si lo pongo aquí dentro de esta declaración if, ahora le estamos diciendo al compilador de typescript si el tipo de
type right here but if i put there right here inside this if statement we are now telling the timescript compiler if the type of
9:32:37
valor está configurado como cadena, entonces ejecuta este código
value is set to string then run this code
9:32:40
si eso no está configurado como cadena, ¿qué quieres hacer? Solo queremos
if that's not set to string so what do you want to do we just want to
9:32:43
registrar en la consola como valor.2 fijo aquí
log to the console like value.2 fixed right here it
9:32:46
va a ser algún tipo de número, como si solo estamos vinculando eso al compilador
is going to be some sort of a number like we are just linking that to the compiler
9:32:49
así que dentro de este bloque de código, typescript sabe
so within this block of code typescript knows
9:32:53
que el valor será cadena y fuera de eso
that the value will be string and outside from that
9:32:56
primer bloque ahora fuera de este bloque de código dentro del bloque else, este compilador de typescript ya sabrá que el valor será
first block now outside from this block of code inside the else block this typescript compiler will already know that the value will be
9:33:04
algún tipo de número, así que si paso el mouse sobre eso, aquí puedes
some sort of a number so if i hold my mouse over to that so here you
9:33:07
ver que ahora estamos obteniendo el número correcto, así que así es como vamos a estar restringiendo
can see we are now getting the number right so this is how we are going to be narrowing
9:33:11
los tipos aquí, así que ahora déjame usar eso, voy a volver y
the types right here so now let me just use that i'm going to go back and
9:33:14
solo voy a llamar a mi función con la cadena de
i'm going to just call my function with the string of
9:33:17
hola, así que nos dará como hola en mayúsculas aquí, así que si
hello so it's going to give us like uppercase hello right here so if
9:33:20
guardo mi archivo y ejecuto eso, nos dará mayúsculas
i save my file and run that so it's going to give us uppercase
9:33:24
hola aquí, lo cual es totalmente genial, ahora déjame duplicar eso o, ya sabes, déjame escribir una función de ejemplo una vez más y si solo escribo como 20
hello right here which is totally cool now let me just duplicate that or you know let me just write an example function once again and if i just write like 20
9:33:31
así que nos dará 20 aquí, así que si guardo ahí o no 20
so it's going to give us 20 right here so if i save there or not 20
9:33:35
20.00 porque usamos este método
20.00 because we use this method
9:33:38
de fijar aquí y especificamos dos, así que eso es
of to fix right here and we specify two so that's
9:33:41
por qué ahora estamos obteniendo este punto cero cero aquí, así que
why we are now getting this dot zero zero right here so
9:33:44
esa fue la primera forma de restringir tipos, ahora aprendamos sobre
that was the first way of type narrowing now let's learn about
9:33:47
una restricción de tipo con el operador instanceof aquí
a type narrowing with the instance of operator right here
9:33:50
así que el operador instanceof es otro guardia de tipo que te permite verificar si un objeto es una instancia de una clase o un constructor particular
so the instance of operator is another type guard that allow you to check whether an object is an instance of a particular class or a constructor
9:33:58
función, así que así es como se verá el código y sé
function so this is how the code is going to look like and i know
9:34:01
eso es mucho código así que aquí puedes ver que tenemos primero
that's a lot of code so here you can see we have first of
9:34:04
dos clases aquí y luego estamos creando algún tipo de función
all like two classes right here and then we are creating some sort of a function
9:34:07
y para el tipo de perímetro que estamos pasando
and for the type of perimeter we are passing
9:34:10
ya sea la clase de perro o la clase de gato y no estamos regresando
either the dog or the cat class and we're not returning
9:34:13
algo así que por eso pusimos void aquí así que sabes qué, déjame escribir este código
something so that's why we put void right here so you know what let me just write this code
9:34:17
y luego te darás cuenta de lo que estoy hablando así que ahora déjame quitar eso y voy a definir una clase, le voy a dar un nombre como perro y ahora no voy a
and then you will get to know what i'm talking about so now let me just remove that and i'm going to just define a class i'm going to give a name of like dog and now i'm not going to
9:34:25
molestarme en proporcionar una función constructora, solo voy a usar como una barra
and bother providing a constructor function i'm going to just use like a bar
9:34:28
método aquí no vamos a estar regresando algo de
method right here we are not going to be returning something from
9:34:31
ahí así que voy a escribir un blanco y dentro de esta función solo vamos a usar como lobo o algo así, voy a duplicar esto
there so i'm going to just write a white and inside this function we are going to be just using like wolf or something like that i'm going to duplicate this
9:34:38
clase aquí ahora déjame crear una para el gato como
class right here now let me just create one for the cat as
9:34:42
bueno y para el gato tendríamos un maullido
well and for the cat we would have a meow
9:34:45
así o supongo que así es como se escribe maullido o algo así y aquí voy a escribir como maullido, algo así.
like that or i guess this is how you spell it meow or something like that and here i'm going and also just write like meow, something like this.
9:34:54
Así que sabes qué, déjame guardar mi archivo. Y así es como vamos a crear dos clases.
So you know what, let me just save my file. And this is how we are going to be creating two classes.
9:34:59
Y ahora lo siguiente que tienes que hacer es que tenemos que crear una función.
And now the next thing which you have to do is that we have to create a function.
9:35:02
Y dentro de esa función, vamos a usar la reducción de tipo utilizando el operador instanceof aquí.
And inside that function, we're going to be using the type narrowing by using the instance of operator right here.
9:35:08
Así que le voy a dar un nombre como sonido de animal. Y va a tomar el perímetro de animal.
So I'm going to give a name of like animal sound. And it's going to take the perimeter of animal.
9:35:13
Y también voy a proporcionar el tipo de, sabes qué, no sonido de animal.
And I'm going to also provide the type of, you know what, not animal sound.
9:35:18
Animal, supongo que animal estaría bien. y para el
Animal, I guess animal would be fine. and for the
9:35:22
tipo voy a especificar ya sea la clase de perro o
type i'm going to specify either the dog class or
9:35:25
la clase de gato que estamos creando aquí arriba así que tenemos
the cat class which we are creating right here up above so we
9:35:28
esta clase de perro y también tenemos esta clase de gato aquí así que
have this dog class and we also have this cat class right here so
9:35:31
no vamos a estar regresando algo de eso así que solo voy a especificar el
we are not going to be returning something from that so i'm going to just specify the
9:35:34
palabra aquí y ahora déjame verificar si el animal
word right here and now let me just check if the animal
9:35:37
es el tipo o no tipo pero la instancia de
is the type or not type but the instance of
9:35:41
un perro así que qué quieres hacer en ese caso solo queremos
a dog so what do you want to do in that case we just want
9:35:44
escribir un animal punto ladrar justo aquí y voy a ejecutar eso
to write an animal dot bark right here and i'm going to execute that
9:35:47
animal está anotado con el perro justo aquí no
and now here you can see if i hold my mouse over to there the
9:35:51
un gato sino con un perro porque aquí puedes ver
animal is annotated with the dog right here not
9:35:54
estamos usando la reducción de tipo estamos reduciendo
a cat but with a dog because here you can see
9:35:57
sobre tipo justo aquí así que por eso dentro de este bloque de
we are using the type narrowing we are narrowing down
9:36:00
código el tipo de animal debería ser un perro
over type right here so that's why inside this block of
9:36:03
el tipo de animal debe ser un perro
code the animal type should be a dog
9:36:06
aquí mismo, así que ahora para la clase else, ¿qué quieres hacer? Déjame escribir eso y voy a escribir animal.purr y ahora déjame ejecutar eso
right here so now for the else class what do you want to do let me just write that and i'm going to just write animal dot meow and now let me just execute that right
9:36:15
aquí, así que si paso el mouse sobre este, aquí puedes
here so if i hold my mouse over to this one so here you can
9:36:18
ver que para este tenemos un animal de gato si
see for this one we have an animal of cat if
9:36:21
paso el mouse sobre este primero, nos va a dar el animal de
i hold my mouse over to this first one it's going to give us the animal of
9:36:24
perro aquí mismo, así que sí, eso es
dog right here so yeah that's that
9:36:27
ahora déjame usar eso aquí, así que voy a crear dos instancias
now let me just use that right here so i'm going to just create two instances
9:36:30
así que voy a escribir como mi perro, va a ser igual a nuevo
so i'm going to write like my dog it's going to be equals to like new
9:36:34
perro y ejecutar eso, y también voy a crear mi gato, va a ser igual al gato aquí y no vamos a
dog and execute that and i'm going to also create my cat it's going to be equals to the cat right here and we're not going
9:36:41
proporcionar nada porque no requerimos nada
providing anything because we did not require anything
9:36:44
así que ahora déjame usar mi sonido de animal y voy a especificar mi
so now let me just use my animal sound and i'm going to specify my
9:36:47
perro, pero sabes qué, déjame registrar en la consola mi perro, así que
dog but you know what let me just log to the console my dog so
9:36:50
puedes ver, ya sabes todas esas cosas, pero ahora déjame
you can see uh you already know all of that stuff but now let
9:36:53
registrar en la consola, enviar mi archivo y ejecutar allí, así que
me just log to the console there send my file and run there so
9:36:56
aquí puedes ver que nos va a dar el perro y también las cláusulas del gato aquí
here you can see it's going to gives us the dog and also the cat clauses right here
9:37:00
bien, así que eso es genial, ahora tenemos que proporcionar este perro y también este gato a este sonido de animal aquí, así que voy a especificar mi perro y nos va a dar como salida el lobo
okay so that's cool now we have to provide this uh dog and also this cat to this animal sound right here so i'm going to just specify my dog and it's going to give us for the output of wolf
9:37:11
o lobo lobo supongo, porque actualmente estamos
or wolf wolf i guess because currently we
9:37:14
proporcionando este lobo lobo, así que nos va a dar ese resultado y
are providing this wolf wolf so it's going to give us that result and
9:37:17
si solo escribo como sonido de animal una vez más y si solo escribo como mi
if i just write like animal sound once again and if i just write like my
9:37:20
gato y nos va a dar maullido o
cat and it's going to give us meow or
9:37:24
algo así y ahora déjame guardar mi archivo y si simplemente
something like that and now let me just save my file and if i just
9:37:27
ejecuto eso, nos va a dar lobo lobo para el primero y
run that it's going to give us wolf wolf for the first one and
9:37:30
nos va a dar maullido para este gato aquí, así que sí, y así es como vamos a reducir nuestros tipos usando un operador de tipo de TypeScript aquí.
it's going to give us meow for this cat right here so yeah and this is how we are going to be narrowing down our types by using a TypeScript type of operator right here.
9:37:40
Así que ahora aprendamos sobre la reducción de tipos usando los tipos de intersección en TypeScript.
So now let's learn about a type narrowing by using the intersection types in TypeScript.
9:37:45
Así que ya sabes, como ya discutí, qué son las intersecciones, pero si no lo sabes, déjame leértelo.
So you already know like I already discussed what intersections is but if you don't know that let me just read that for you.
9:37:51
Así que los tipos de intersección en TypeScript te permiten combinar múltiples tipos
So intersection types in TypeScript allow you to combine multiple types
9:37:55
en un solo tipo y el tipo resultante tendrá todas las propiedades de cada tipo individual y puedes crear un tipo de intersección usando el operador 'y' aquí y así es como se verá el código.
into a single type and the resulting type will have all the properties of each individual type and you can create an intersection types using the and operator right here and this is how the code is going to look like.
9:38:05
Así que aquí puedes ver que tenemos dos tipos, como el primero que tenemos
So here you can see we have two types of like the first one we have
9:38:08
un empleado, el segundo que tenemos es un gerente y ahora solo estamos
an employee the second one we have a manager and we are now just
9:38:11
usando este operador de intersección aquí o tipo de intersección
using this intersection operator right here or intersection type
9:38:15
lo que quieras llamar eso y ahora combinará ambos
whatever you want to call that and it will now combine both of these
9:38:18
valores o estos tipos a este aquí y podemos usar
values or these types to this one right here and we can use
9:38:21
eso en cualquier lugar que queramos, así que ahora déjame escribir un código para eso y luego tú
that anywhere we want so now let me just write a code for that and then you
9:38:24
sabrás de qué estoy hablando, así que voy a eliminar todo ese código y
will get to know what i'm talking about so i'm going to just delete all of that code and
9:38:28
voy a hacer zoom y primero voy a definir nuestros dos tipos aquí, como empleado o algo así y dentro
i'm going to zoom in and i'm going to first of all define our two types right here like employee or something like that and inside
9:38:36
entonces voy a especificar el id como número y también el nombre
then i'm going to specify the id of number to it and also the name
9:38:39
será algún tipo de cadena y eso es todo, ahora yo
will be some sort of a string and that's that now i
9:38:42
ya olvidé incluir el signo igual y aquí
already forgot to include the equal to sign and here
9:38:45
tengo que escribir un gerente y el gerente va a ser igual
i have to just write a manager and the manager is going to be equals
9:38:49
a un departamento d-e-p-a-r-t-a-m-e-n-t
to a department d-e-p-a-r-t-m-e-n-t
9:38:52
y para el departamento voy a especificar la cadena y para
and for the department i'm going to specify the string and for
9:38:55
el rol voy a especificar la cadena también y así que estos son todos dos tipos, ahora déjame crear, eh, o no crear, pero ahora déjame usar
the role i'm going to specify the string as well and so these are all two types now let me just create uh or not create but now let me just use
9:39:03
mi tipo de intersección aquí, así que voy a escribir como tipo
my intersection type right here so i'm going to just write like type
9:39:06
de gerente m a n a
of manager m a n a
9:39:09
g sobre el gerente uh gerente con
g on manager uh manager with
9:39:13
m información del empleado algo así como
m employee info something like
9:39:16
que ahora será igual al empleado y el
that will be now equals to the employee and the
9:39:19
gerente aquí así que ahora voy a usar eso aquí así que
manager right here so now i am going to use that right here so
9:39:22
voy a escribir como gerente vamos a usar minúsculas y gerente y ahora déjame anotar eso con este gerente
i'm going to just write like manager come on lowercase cons and manager and now let me just annotate that with this manager
9:39:29
con la información del empleado va a ser igual
with employee information is going to be equals
9:39:33
a este objeto aquí así que primero de
to this object right here so first of
9:39:36
todo voy a especificar valores para el id luego voy a especificar el
all i'm going to specify values to the id then i'm going to specify the
9:39:39
valor para el nombre y también para el departamento y el rol aquí porque
value to the name and also to the department and role right here because
9:39:42
actualmente estamos combinando ambos en este aquí y nosotros
currently we are combining both of them to this one right here and we
9:39:45
ahora estamos proporcionando eso aquí para este objeto así que tengo que escribir
are now providing that right here for this object so i have to write
9:39:48
todos sus valores así que el id ahora se establecerá en uno, dos, tres o algo así y también voy a especificar algún tipo de nombre como alex merson o algo así y también voy a proporcionar un departamento
all of their values so id will be now set to like one two three or something like that and i am going to also specify some sort of a name like alex merson or something like that and i'm going to also provide a department
9:40:00
el departamento será ingeniería y también el rol será
the department will be engineering and also the role will
9:40:03
algún tipo de líder de equipo o algo así y
be some sort of like team lead or something like that and
9:40:06
finalmente ahora déjame registrar eso en la consola voy a volver y
finally now let me just log there to the console i'm going to go back and
9:40:09
ahora déjame registrar en la consola como manager.id
now let me just log to the console like manager.id
9:40:13
si solo escribo id y ahora déjame ejecutar eso
if i just write id and now let me just execute that
9:40:16
así que nos dará como uno, dos, tres aquí y ahora déjame duplicar eso unas cuantas veces y solo voy a obtener como nombre y también voy a obtener el
so it's going to give us like one two three right here and now let me just duplicate that a few times and i'm going to just get like name and i'm going to also get the
9:40:25
departamento y también para el rol también
department and also for the role as well
9:40:28
así que si guardo mi archivo y ejecuto eso nos dará uno
so if i save my file and run there it's going to give us one
9:40:31
dos, tres, cuatro id alex merston como nombre y ingeniería
two three four id alex merston as a name and engineering
9:40:34
como departamento y el rol será líder de equipo aquí está bien
as a department and role will be team leader right here okay
9:40:38
así que eso fue todo sobre nuestra reducción de tipos en typescript
so that was it about our type narrowing in typescript
9:40:41
así que ahora déjame hacer una configuración genuina para escribir un typescript
so now let me just make a genuine setup for writing a typescript
9:40:44
código porque actualmente hemos estado usando esta extensión llamada
code because currently we've been using this extension called
9:40:48
este código se ejecuta aquí y confía en mí, amamos esta extensión, pero el problema es que en real
this code run right here and trust me we love this extension but the thing is that in real
9:40:54
nuestro proyecto no vamos a usar el coderunner, tenemos que
our project we are not going to be using the coderunner we have to
9:40:58
compilar nuestro código de typescript a javascript porque
compile our typescript code to the javascript because
9:41:01
nuestro compilador no tiene idea
our compiler don't have any idea
9:41:04
como qué demonios es un tipo, qué demonios es
like what the hell is a type what the hell is
9:41:07
todo ese operador de inserción, todas las cosas que
all of that insertion operator all of the thing that
9:41:10
aprendimos sobre typescript, el compilador no tiene idea de eso
we learned about typescript the compiler don't have any idea for
9:41:13
así que usamos javascript para el front end y también para el back end y no usamos el código de typescript para el front end, para el back end tenemos que compilar nuestro código TypeScript en código JavaScript.
that so we use javascript for the front end and also for the back end and we don't use the typescript code for the front end for the back end we have to compile our TypeScript code into the JavaScript code.
9:41:25
Entonces, ¿cómo vamos a hacer eso? Bien, para hacer eso, quiero decir, para compilar nuestro código en código JavaScript, no tenemos que hacer nada, solo tenemos que escribir un TSC, que ya instalamos al principio del curso.
So how we are going to be doing that? Okay, so to do that, I mean like to compile our code into a JavaScript code, we don't have to do nothing, but we just have to write a TSC, which we already installed in the beginning of the course.
9:41:38
Y solo vamos a escribir un guion y cerca. Y si presiono enter, ¿qué estamos obteniendo?
And we are going to be just writing a dash and near. And if I hit enter, and what are we getting?
9:41:42
Ahora estamos obteniendo este archivo de configuración TS aquí. Y hay muchas cosas dentro de este archivo de configuración TS.
We are now getting this TS config file right here. And there are a lot of stuff inside this TS config file.
9:41:49
Ahora déjame cerrar mi terminal aquí y voy a abrir mi tsconfig
Now let me just close my terminal right here and I'm going to open my tsconfig
9:41:53
archivo y aquí puedes ver que tenemos una cantidad loca de
file and here you can see we have like crazy amount of
9:41:56
cosas aquí, puedes aprender más sobre este tsconfig
stuff right here you can learn more about this tsconfig
9:41:59
archivo por tu cuenta, pero solo voy a expandir algunas cosas
file by your own but I'm going to just expand a few things
9:42:03
aquí, así que ahora déjame continuar e ir a este tsconfig
right here so now let me just go ahead and go to this tsconfig
9:42:07
aquí, si presiono enter, nos llevará a este tsconfig aquí, tendré que ir a la parte superior y así es como se verá aquí, así que puedes
right here if I hit enter it's going to bring us to this tsconfig right here I'm going to have to go to the top and this is how it's going to look like right here so you can
9:42:15
aprender sobre opciones del compilador, verificación de tipos, módulos, emitir javascript
learn about a compiler option type checking modules emit javascript
9:42:18
soporte y todo ese tipo de cosas, pero lo que
support and all of that kind of stuff but what
9:42:21
actualmente nos interesa es cómo en el mundo vamos a
we are currently interested in is that how in the world we are going to
9:42:24
compilar nuestro código, bueno, no tenemos que hacer nada
be compiling our code well we don't have to do nothing
9:42:28
déjame acercar un poco, no tenemos que hacer nada, pero solo
let me just zoom in a bit we don't have to do nothing but we
9:42:31
tenemos que abrir nuestra terminal aquí y también ya
just have to open our terminal right here and we also already
9:42:34
tenemos nuestro archivo de configuración ts aquí, así que todo
have our ts config file right here so everything
9:42:37
ya está configurado, así que solo tenemos que usar como tsc y
is already set up so we just have to use like tsc and
9:42:41
entonces tenemos que incluir la ruta específica del archivo que
then we have to include the specific path of the file which
9:42:44
quieres compilar, así que solo voy a escribir ind y si
you want to compile so i'm going to just write ind and if
9:42:47
presiono tab y si presiono enter aquí, nos va a dar
i hit tab and if i hit enter right here it's going to give us
9:42:50
ese archivo javascript aquí, así que aquí puedes ver que ahora
that javascript file right here so here you can see it is now
9:42:53
nos está dando este archivo index.js aquí, pero
giving us this index.js file right here but
9:42:56
tendríamos algún tipo de problema si abro este javascript
we would have some sort of a problem if i open this javascript
9:43:00
aquí estamos obteniendo todo ese mismo código, no el mismo código, pero ahora estamos obteniendo totalmente un código javascript, ¿verdad?
file right here we are getting all of that same code right not the same code but we are now getting totally a javascript code right
9:43:06
aquí, pero la cosa es que estamos usando la palabra reservada
here but the thing is that we are using the one
9:43:09
y esta no es la forma más nueva
reserved keyword and this is not the newer way
9:43:13
de escribir un código de script general, oh, sabes qué, déjame darte algún tipo de ejemplo
of writing a general script code oh you know what let me just give you some sort of example
9:43:16
como, uh, voy a ir a mi código typescript aquí
like uh i'm gonna go ahead and go to my typescript code right here
9:43:19
voy a eliminar cada cosa que actualmente tengo aquí y
i'm gonna remove every single thing which i currently have right here and
9:43:22
voy a crear algún tipo de función de error como const add y va
i'm going to just create some sort of error function like const add and it's
9:43:25
a ser igual a, como, uh, no sé, x y
going to be equals to like uh i don't know x and
9:43:29
la x se establecerá en número y también voy a especificar la y y la y también será un número y ahora déjame
the x will be set to number and i'm going to also specify the y and the y will be also a number and now let me just
9:43:35
anotar eso como un número también y
annotate that to a number as well and
9:43:38
también voy a especificar la x más y aquí como
i'm going to also specify the x plus y right here as
9:43:42
un valor de retorno y ahora déjame volver y aquí puedes
a return value and now let me just go back and here you
9:43:45
ver que esta es la forma más nueva de escribir un código javascript
can see this is the newer way of writing a javascript code
9:43:48
como aquí puedes ver que estamos usando la función de flecha y todo eso, así que
like here you can see we are using the arrow function and all of that so
9:43:51
ahora, si quieres compilar eso, ahora déjame compilar eso aquí si
now if you want to compile that now let me just compile that right here if
9:43:54
solo uso este tsc aquí, déjame limpiar
i just use this tsc right here let me just clear
9:43:58
ahí y si solo uso como tsc y luego esto
there and if i just use like tsc and then this
9:44:01
index.js o no js en este caso, tenemos que escribir
index.js or not js in this case we have to right
9:44:04
este ts aquí si presiono enter, así que ahora
this ts right here if i hit enter so now
9:44:08
va a reemplazar todo su código anterior por este código aquí así que
it's going to replace all of their previous code to this code right here so
9:44:11
déjame mostrarte que si envío mi archivo aquí puedes ver que ahora está usando
now let me just show you that if i send my file so here you can see it is now using
9:44:15
la expresión de función pero esta es la forma más antigua de crear
the function expression but this is the older way of creating
9:44:18
una función como aquí puedes ver que estamos usando la palabra clave de un resultado y
a function like here you can see we are using the one result keyword and
9:44:21
estamos usando la palabra clave de resultado de función y también estamos devolviendo
we are using the function result keyword and we are also returning
9:44:24
ahí justo aquí pero en el typescript aquí usamos esta función de flecha y no estamos obteniendo las funciones de flecha aquí así que cómo en el mundo vamos a hacer
there right here but in the typescript right here we use this arrow function and we are not getting the arrow functions right here so how in the world we are going to be doing
9:44:33
ahí así que bien pero ahí tenemos que continuar y
there so well but there we have to go ahead and
9:44:36
ir a nuestro archivo de configuración y voy a desplazarme
go to our configuration file and i'm going to just scroll
9:44:39
hacia abajo y qué estamos obteniendo ahora estamos obteniendo este objetivo justo aquí y el objetivo ahora está configurado actualmente en es 2016 o es 16 como quieras llamarlo así que voy a simplemente
down and what are we getting we are now getting this target right here and the target is now currently set to the es 2016 or es 16 whatever you want to call that so i'm going to just uh
9:44:51
hacer clic en este hash justo aquí y voy a especificar el
click on this hash right here and i'm going to specify the
9:44:55
objetivo y si presiono aquí puedes ver que nos llevará a
target and if i hit so here you can see it's going to bring us to
9:44:58
esta documentación del objetivo justo aquí puedes aprender más sobre eso si quieres pero básicamente lo que significa este objetivo es en qué tipo de versión de javascript tenemos que compilar este código typescript en
this target documentation right here you can learn more about that if you wanted to but basically what this target means is that in which kind of version of javascript we have to compile this typescript code into
9:45:10
bien así que actualmente está configurado por defecto en este es 2016
okay so currently it is by default set to this es 2016
9:45:13
voy a simplemente eliminar eso y voy a mantener presionado ctrl y presionar espacio así que nos dará 2015 16 17 18 19 hasta este 2023
i'm going to just remove that and i'm going to just hold ctrl and hit space so it's going to give us 2015 16 17 18 19 till this 2023
9:45:22
y también tenemos el esnext justo aquí pero actualmente
and also we have the esnext right here but currently
9:45:26
quiero simplemente compilar mi código a la forma es6 así que
i want to just compile my code to the es6 way so
9:45:29
voy a hacer clic en este es6 justo aquí y si guardo mi archivo
i'm gonna just click on this es6 right here and if i save my file
9:45:32
nada sucederá así que sí quiero
nothing will happen so yeah i want
9:45:35
que tengas eso en mente nada sucederá si simplemente
you to keep that in mind nothing will happen if i just
9:45:38
elimino este archivo y ahora en lugar de escribir
delete this file and now instead of writing
9:45:41
como tsc e index y todo eso solo tenemos que escribir este tsc que dice bebé solo tenemos que
like tsc and index and all of that we just have to write this tsc that said baby we just
9:45:48
escribir este dsc y si presiono enter aquí aquí
have to write this dsc and if i hit enter right here here
9:45:51
puedes ver que nos dará ese archivo compilado y ahora
you can see it's going to give us that compile file and now
9:45:54
esperemos que si abro eso me dará esa flecha
hopefully if i open that it's going to give us that arrow
9:45:57
función justo aquí lo que significa que ahora estamos usando
function right here which means like we are now using
9:46:00
la nueva forma de escribir un typescript, quiero decir, como código javascript, ¿verdad?
the newer way of writing a typescript i mean like javascript code right
9:46:04
aquí, así que eso es totalmente asombroso, eso fue aproximadamente para el
here so that's totally amazing so that was at about for the
9:46:07
objetivo y ahora aprendamos sobre la compilación
target and now let's learn about um compilation
9:46:10
así que aquí puedes ver que va a compilar todos los archivos aquí, vamos a
so here you can see it's going to compile all of the file right here let's
9:46:14
suponer que tengo muchos archivos, ahora déjame solo eliminar eso, estoy
suppose if i have a lot of files now let me just delete that i'm
9:46:17
simplemente eliminando eso aquí, así, y estoy
going to just delete that right here just like that and i'm
9:46:20
simplemente creando algunas otras funciones
going to just create a few other uh function
9:46:23
aquí, ahora déjame duplicar eso y le voy a dar un nombre
right here now let me just duplicate that and i'm going to give a name
9:46:26
como multiplicar o algo así y
of like multiply or something like that and
9:46:29
en lugar de escribir este símbolo de más, simplemente lo cambiaré a como
instead of writing this plus symbol i'm going to just change that to like
9:46:32
un símbolo de multiplicación aquí, no tenemos que preocuparnos por el código ahora, voy a cortar este código de aquí y simplemente voy a crear un archivo, darle un nombre de algo, ahora déjame hacerlo un poco más grande
a time symbol right here we don't have to worry about the code right now i'm going to cut this code from here and i'm going to just create a file give a name of like something now let me just make that a bit bigger
9:46:42
voy a crear un archivo llamado mult.ts
i'm going to create a file given name of like mult.ts
9:46:46
para multiplication.typescript, está bien, así que en realidad
for multiplication.typescript okay so for real
9:46:49
en el proyecto mundial vamos a tener muchos archivos de typescript, así que en
world project we are going to have a lot of typescript files so in
9:46:52
este caso solo tenemos como mult.ts aquí, estoy
this case we just have like mult.ts right here i'm
9:46:55
simplemente poniendo mi código dentro de este mult.ts aquí y
going to just put my code inside this mult.ts right here and
9:46:59
también voy a crear una carpeta llamada src
also i'm going to just create a folder given name of like src
9:47:02
o sabes, no tengo que crear una carpeta, no ahora, ahora
or you know i don't have to create a folder not right now now
9:47:06
déjame mostrarte eso, así que aquí puedes ver que tenemos este mult.ts
let me just show you that so here you can see we have this mult.ts
9:47:09
archivo aquí, también voy a cortar este código de aquí y ahora déjame
file right here i'm going to also cut this code from here and now let
9:47:12
simplemente crear un archivo más, darle un nombre de add.ts para
me just create one more file give a name of like add.ts for
9:47:15
sumar dos números, así que simplemente voy a colocar este código aquí, ahora déjame
adding two numbers so i'm going to just place this code right here now let me just
9:47:18
regresar para que ustedes puedan ver todo un poco mejor, así que aquí
go back so you guys can see everything a bit better so here you
9:47:21
pueden ver que tenemos tres archivos, el primero que tenemos es este archivo add.ts
can see we have three files the first one we have is this add.ts file
9:47:24
luego tenemos un archivo de multiplicación como multiplication.ts y
then we have a multi like multiplication.ts file and
9:47:28
también voy a escribir como restar aquí dentro de este um archivo de índice así que voy a escribir una resta o algo así y voy a poner mi menos aquí así que si guardo eso
i'm going to also just write like subtract right here inside this um index file so i'm going to just write a subtract or something like that and i'm going to just put my minus right here so if i save that
9:47:39
así que actualmente tenemos tres archivos aquí el primero que tenemos
so currently we have three files right here the first one we have
9:47:42
es agregar que es responsable de sumar dos números luego tenemos
is add which is responsible for adding two numbers then we
9:47:45
un índice que es responsable de restar dos
have a index which is responsible for subtracting two
9:47:48
números y luego tenemos un mult para multiplicación está bien
numbers and then we have a mult for multiplication okay
9:47:51
así que si solo escribo tsc aquí en este caso
so if i just write tsc right here in this case
9:47:54
si solo escribo tsc y si presiono enter y
if i just write tsc and if i hit enter and
9:47:57
aquí puedes ver que va a compilar todo el código, todos los archivos que actualmente tenemos dentro de nuestro directorio así que si abro este mult va a
here you can see it's going to compile all of the code right all of the file which we currently have inside our directory so if i open this mult it's going to
9:48:05
proporcionar ese mismo código aquí, va a compilar eso y
provide that same code right here it's going to compile that and
9:48:08
si abro este, lo mismo ocurrirá para el agregar y todo eso
if i open this one same will go for the add and all of that
9:48:11
pero en algunas situaciones no queremos compilar todos los archivos
but in some situation we don't want to compile all of the file
9:48:14
solo queremos compilar un archivo específico como un cierto
we just only want to compile a certain file like a certain
9:48:17
archivo de typescript así que ahora déjame eliminar este archivo de compilación y
typescript file so now let me just delete this compilation file and
9:48:21
ahora voy a buscar los archivos
now i'm going to go ahead and search for the files
9:48:24
aquí así que supongo que eran archivos archivos voy a presionar enter aquí así que nos llevará a esta documentación
right here so i guess that was a files files i'm going to hit enter right here so it's going to bring us to this documentation
9:48:31
aquí así que encuentra especifica la lista permitida de los archivos
right here so find specify the allowist of the file
9:48:34
para incluir en el programa ocurrirá un error si no
to include in the program an error will occur if you
9:48:37
tienes ese archivo ya creado aquí así que cómo
don't have that file already created right here so how
9:48:40
la sintaxis se verá así es como se verá la sintaxis
the syntax is going to look like this is how the syntax is
9:48:43
pero quiero que tengas en cuenta algo, será debajo de esta opción del compilador no
going to look like but i want you to keep in mind something it
9:48:46
estará debajo de esta opción del compilador no
will be underneath this compiler option not
9:48:50
dentro de ahí como para esta opción del compilador tenemos muchas cosas ahora déjame mostrarte que si voy al archivo de configuración ts voy a ir a la parte superior
inside there like for this compiler option we have a lot of things now let me just show you that if i go to the ts config file i'm going to go to the top
9:48:59
primero que nada, aquí puedes ver que solo tenemos un objeto
first of all so here you can see we have only one object
9:49:02
justo aquí dentro de este json que actualmente está configurado a
right here inside this json so which is currently set to
9:49:05
estas opciones del compilador si voy a la parte inferior no tenemos
this compiler options if i go to the bottom we don't
9:49:08
no tenemos nada, solo tenemos eso, así que si
have anything we just only have that so if
9:49:11
quieres proporcionar sus archivos, voy a poner una coma ahí y
you want to provide their files i'm going to just put a comma there and
9:49:15
voy a copiar eso justo aquí, voy a copiar eso y
now let me just even copy that right here i'm going to copy that and
9:49:18
voy a colocar eso justo aquí y voy a eliminar casi todo aquí, pero quiero dejar como, no sé, tal vez
place that right here and i'm going to just remove almost every single thing right here but i want to just leave like i don't know maybe
9:49:25
índice, así que voy a escribir index.ts aquí, voy a
index so i'm going to just write index.ts right here i'm going
9:49:28
guardar mi archivo ahora mismo, está bien, así que si solo guardo mi archivo
to save my file right now okay so if i just save my file
9:49:31
ahora mismo y si lo ejecuto una vez más así, tsc
right now and if i run there once again like that tsc
9:49:35
una vez más y si presiono enter en este caso, es
once again and if i hit enter in this case it's
9:49:38
solo va a compilar este index.ts
going to only compile this index.ts
9:49:41
aquí, así que aquí puedes ver que solo va a compilar eso
right here so here you can see it's going to only compile that
9:49:44
y va a ignorar el resto del archivo aquí, así que sí, esa fue la primera forma de compilar algo o ignorar algo usando estos archivos, ahora déjame
and it's going to ignore the rest of the file right here so yeah that was the first way of compiling something or ignoring something by using these files now let me So let me just show you the include and also the exclude as well.
9:49:55
así que voy a comentar esta línea. Y ahora déjame buscar
So I'm going to comment this line out. And now let me just search for
9:49:58
incluir, así que incluir, ¿qué tipo de archivo
include so include like which kind of file
9:50:01
quieres incluir para ser compilado? Está bien, así que puedes
you want to include to be compiled okay so you can
9:50:04
aprender más sobre eso, así que así es como se verá el directorio
learn more about that so this is how the directory will look like
9:50:07
como todos estos archivos que puedes ver aquí, no serán
like all of these files which you can see right here they will not be
9:50:10
compilados y el resto de ellos serán compilados, así que
compiled and the rest of them will be compiled so
9:50:13
sabes qué, voy a cortar eso de aquí y
you know what i'm going to just cut that from here and
9:50:17
voy a crear una carpeta llamada src y también voy a crear una más para el disco porque en la carpeta del disco vamos a
i'm going to just create a folder given name of like src and i'm going to also create one more for the disk because in the disk folder we are going to
9:50:24
proporcionar nuestro archivo de compilación como el código compilado
we're providing our compilation file like the compiled code
9:50:27
así que nos ocuparemos de eso un poco más tarde, pero voy a cortar
so we're going to take care of that bit later but i'm going to just cut
9:50:30
todos esos archivos y los voy a poner dentro de este src
out all of that files and i'm going to just put it inside this src
9:50:33
directorio justo aquí y ahora dentro de este archivo de configuración ds
directory right here and now inside this ds config file
9:50:36
¿qué tengo que hacer? Solo voy a especificar este incluir
what do i have to do i'm going to just specify this include
9:50:39
justo aquí, está bien, así que ahora déjame copiar eso y voy a
right here okay so now let me just copy that and i'm
9:50:43
voy a escribir comillas dobles y proporcionar eso incluye y
going to just write double quotes and provide that include and
9:50:46
aquí tenemos que especificar el arreglo pero también tendré que especificar esa coma aquí para deshacerme de ese error aquí está bien así que voy a simplemente
here we have to specify the array but i'm going to also have to specify that comma right here to get rid of that error right here okay so i'm going to just
9:50:54
copiar eso y ahora déjame colocar eso aquí así que
copy that and now let me just place that right here so
9:50:57
lo que significa esta sintaxis es que cada cosa
what this syntax means is that every single thing
9:51:00
que están actualmente disponibles dentro de la carpeta src
which are currently available inside the src folder
9:51:03
quiero que compiles todos ellos como no dejes ninguno
i want you to compile all of them like leave none
9:51:06
de ellos compila todos ellos así que si solo guardo eso y
of them compile all of them so if i just save that and
9:51:10
ahora si solo escribo un comando tsc una
now if i just write a tsc command one
9:51:13
vez más así que si solo escribo tsc y si presiono enter va a compilar todo ese archivo aquí así que aquí puedes ver que va a compilar todos estos archivos y no quiero eso
more time so if i just write tsc and if i hit enter so it's going to compile all of that file right here so here you can see it's going to compile all of these files and i don't want that
9:51:22
como en algunas situaciones querríamos compilar todos sus archivos
like in some situation we would want to compile all of their files
9:51:25
pero muchas veces no queremos compilar todos los archivos así que
but a lot of times we don't want to compile all of the files so
9:51:28
cómo en el mundo vamos a omitir eso voy a abrir allí una vez más
how in the world we are going to be omitting that i'm going to open there once again
9:51:32
así que ahora déjame mostrarte la documentación también puedes incluso especificar
so now let me just show you the documentation as well you can even also specify
9:51:35
un solo archivo si quisieras como supongamos que quieres compilar
a single file if you wanted to like let's suppose if you want to just compile
9:51:38
este index.ts aquí voy a escribir index.ts
this index.ts right here i'm going to just write index.ts
9:51:42
aquí y si guardo allí y ahora déjame ejecutar mi tsc una vez más y si presiono enter solo nos dará ese index.js aquí
right here and if i save there and now let me just run my tsc one more time and if i hit enter so it's going to only gives us that index.js right here
9:51:50
como solo compilará este index.ts pero no queremos eso
like it will only compile this index.ts but we don't
9:51:53
podemos usar también el excluir aquí así que voy a
want that we can also use the exclude right here so i'm
9:51:56
simplemente escribir como excluir excluir
going to just write like exclude exclude
9:51:59
y nos llevará a esta documentación aquí voy a
and it's going to bring us to this documentation right here i'm
9:52:02
copiar allí y debajo de este voy a
going to copy there and underneath this one i'm
9:52:06
especificar este excluir aquí y voy a
going to specify this exclude right here and i'm going
9:52:09
simplemente escribir el arreglo y dentro de este arreglo vamos a especificar todos los archivos que quieres ignorar para la compilación así que voy a simplemente
to just write the array and inside this array we are going to be specifying all of the files which you want to ignore for the compilation so i'm going to just
9:52:16
escribir la carpeta src porque dentro de esta src
write src folder because inside this src
9:52:19
carpeta vamos a compilar o ignorar el
folder we are going to be compiling or ignoring the
9:52:23
archivo así que ahora supongamos que quiero ignorar este archivo de multiplicación
file so now let's suppose if i want to just ignore this multiplication file
9:52:26
pero quiero compilar el resto de ellos, así que solo vamos a escribir
but i want to compile the rest of them so we are going to be just writing
9:52:29
como mult o supongo que eso era mult
like mult or i guess that was mult
9:52:32
mult punto ts aquí voy a proporcionar este mult
mult dot ts here i'm going to just provide this mult
9:52:36
punto t y dentro de ahí déjame copiar eso una vez más, uh, voy a copiar como cada cosa aquí, como quiero compilar cada
dot t and inside there let me just copy that once again uh i'm going to just copy like every single thing right here like i want to compile every
9:52:44
cosa así que solo voy a pasar esto
single thing so i'm going to just pass this
9:52:47
sintaxis aquí como quiero que compiles cada cosa pero
syntax right here like i want you to compile every single thing but
9:52:50
quiero que solo elimines este mult o quiero
i want you to just remove this mult or i want
9:52:53
que solo ignores este archivo mult.ts, está bien, así que
you to just ignore this mult.ts file okay so
9:52:56
ahora déjame compilar eso y si presiono enter, así que aquí puedes
now let me just compile that and if i hit enter so here you can
9:52:59
ver que va a compilar todo el archivo, pero no compilará
see it's going to compile all of the file but it will not compile
9:53:03
este archivo mult.ts aquí, así que aquí puedes
this mult.ts file right here so here you can
9:53:06
ver que tenemos este índice y también tenemos este add.js aquí, lo cual está totalmente bien, así que ahora voy a eliminar esto
see we have this index and we also have this add.js right here which is totally okay so now i'm going to just delete this
9:53:13
add y también este archivo de compilación de índice y ahora vamos a
add and also this index compilation file and now let's
9:53:16
aprender sobre el exterior aquí, exterior
learn about the outer right here outer
9:53:19
voy a presionar enter aquí para que puedas aprender más
i'm gonna hit enter right here so you can learn more
9:53:22
sobre este exterior, como lo que hará por ti, pero ahora dejemos
about this outer like what it will do for you but now let
9:53:26
que te muestre en acción, así que para este exterior vamos
me just show you in action so for this outer we
9:53:29
a especificar dónde queríamos poner nuestro código compilado
are going to be specifying where we wanted to put our compiled
9:53:32
pero ahora si solo uso tsc una vez más, va a
code but now if i just use like tsc one more time it's
9:53:35
compilar todo el código aquí dentro de esta carpeta src
going to compile all of the code right here inside this src folder
9:53:38
pero no queremos eso, solo voy a eliminar estos archivos aquí
but we don't want that i'm going to just delete these files right
9:53:41
quiero que todo el código compilado esté dentro
here i want all of the compiled code to be inside
9:53:44
de esta carpeta de prueba aquí, así que cómo demonios vamos a hacer
this test folder right here so how in the world we are going to be doing
9:53:47
eso, voy a abrir mi configuración de ts aquí y voy a
that i'm going to just open my ts config right here and i'm
9:53:50
voy a buscar el directorio externo aquí
going to just search for the outer right here the
9:53:54
el directorio externo, así que voy a descomentar eso y primero que nada voy a presionar ctrl y espacio y sabes qué, voy a proporcionar un disco aquí en este caso, así que si lo guardo
outer directory okay so i'm going to just uncomment that and first of all i'm going to just pro i'm going to hold ctrl and hit space and you know what i'm going to just provide a disk right here in this case so if i just save that
9:54:06
en este caso queremos compilar todo nuestro código en esta carpeta dist
in this case we want to compile all of our code into this dist folder
9:54:09
así que aquí puedes ver que proporcionamos la ruta de esta dist
so here you can see we provide the path of this dist
9:54:12
aquí, así que ahora déjame cerrar eso y cruzar los dedos
right here okay so now let me just close that and finger
9:54:15
y si simplemente ejecuto eso
crossed and if i just run that so
9:54:19
aquí puedes ver que va a compilar todo nuestro código en esto
here you can see it's going to compile all of our code into this
9:54:22
carpeta dist aquí, así que también podemos eliminar
dist folder right here so we can also just remove
9:54:25
en este aquí, voy a eliminar esta exclusión, voy a comentar esta línea y ahora déjame eliminar todos esos archivos una vez más
on this one right here i'm going to just remove this exclude i'm going to comment this line out and now let me just delete all of that files once again
9:54:35
y ahora déjame volver a ejecutar ese tsc una vez, así que si ejecuto
and now let me just rerun that tsc one time so if i run
9:54:38
eso, va a compilar todo el código en este ds
that so it's going to compile all of the code into this ds
9:54:41
carpeta o carpeta dist aquí, así que eso fue
folder or dist folder right here so that was
9:54:44
acerca de la configuración genuina de typescript, así que
it about the genuine setup of typescript so
9:54:47
vamos a escribir nuestro código typescript usando esta extensión que es la extensión ts, pero tenemos que compilar nuestro código en un código javascript para que podamos trabajar con el javascript del mundo real aquí
we're going to be writing our typescript code by using this extension which is the ts extension but we have to compile our code into a javascript code so that we can work with the real world javascript right here
9:54:59
Está bien, así que eso fue acerca de la configuración genuina de TypeScript o como quieras llamarlo. Así que eso fue acerca de la compilación y todo eso.
Okay, so that was it about the TypeScript genuine setup or whatever you want to call that. So that was it about compilation and all of that.
9:55:06
Ahora aprendamos sobre nuestros archivos de declaración. Voy a copiar eso y ponerlo aquí.
Now let's learn about our declaration files. I'm going to just copy that and put it right here.
9:55:12
Y voy a ir a este TypeScript.org aquí. Y voy a hacer clic en esta documentación aquí.
And I'm going to go ahead and go to this TypeScript.org right here. And I'm going to just click on this docs right here.
9:55:19
Luego voy a desplazarme hacia abajo hasta este archivo de declaración. Así que voy a hacer clic en eso y no te voy a leer toda la documentación.
Then I'm going to just scroll down to this declaration file. So I'm going to just click on that and I'm not going to read you through all of the documentation.
9:55:26
Pero confía en mí, los archivos de declaración son totalmente simples, increíbles y directos.
But trust me, declaration files are totally simple and amazing and straightforward.
9:55:32
Entonces, ¿qué son los archivos de declaración y por qué deberías preocuparte por ellos? Bueno, no tienes que preocuparte por ninguno de los archivos de declaración.
So what in the world are declaration files and why you should care about them? Well, you don't have to worry about any of the declaration file.
9:55:39
Pero estos son los archivos que pueden terminar con esta extensión aquí, .d.ts extensión.
But these are the files which can be end with this extension right here, .d.ts extension.
9:55:44
Así que sabes qué, en lugar de perder tu tiempo, voy a eliminar esta carpeta de prueba aquí.
So you know what, instead of wasting your time, I'm going to just go ahead and remove this test folder right here.
9:55:49
y también voy a eliminar toda esa carpeta, quiero decir, voy a
and i'm going to also remove all of that folder i mean like i'm going
9:55:52
también eliminar esta carpeta aquí también y voy a crear
to also remove this folder right here as well and i'm going to just create
9:55:56
como un archivo index.ts aquí y voy a registrar en
like index.ts file right here and i'm going to log to
9:55:59
la consola como consola o no consola o
the console like console or not console or
9:56:02
voy a registrar en la consola como no sé, el documento sería
i'm going to just log to the console like i don't know document would be
9:56:05
bien, así que ahora trabajemos un poco con el objeto documento
fine so now let's just work with a little bit of document object
9:56:08
modelo, no vamos a trabajar con el modelo de objeto documento
model we are not going to be working with the document object model
9:56:11
porque TypeScript sabe cada cosa sobre eso y no tenemos que preocuparnos por los tipos del modelo de objeto documento, así que si yo
because typescript know every single thing about that and we don't have to worry about the document object model uh types as well so if i
9:56:18
coloco el mouse sobre esto, así que el compilador de TypeScript ya
hover my mouse over to this so the typescript compiler already
9:56:21
sabe qué tipo de datos
know which type of data
9:56:24
este documento contendrá, así que aquí puedes ver que ahora está
this document will be holding so here you can see it is now
9:56:27
actualmente configurado en el documento justo aquí, así que si estás usando un vs
currently set to document right here so if you are using a vs
9:56:30
código, así que quiero que mantengas presionado ctrl y hagas clic en
code so i want you to just hold ctrl and click on
9:56:34
eso, así que nos llevará a estas declaraciones
that so it's gonna brings us to these declaration
9:56:37
archivos justo aquí, así que ahora déjame tomar una captura de pantalla de eso, así que aquí
files right here so now let me just take a screenshot of that so here
9:56:41
puedes ver que nos llevará a este lib.dom.d.ts
you can see it's gonna brings us to this lib.dom.d.ts
9:56:44
archivo justo aquí, así que no vamos a proporcionar ningún otro
file right here so we are not going to be providing any other
9:56:48
contenido dentro de estos archivos de declaración, pero dentro
stuff inside this declaration files but inside
9:56:51
de estos archivos de declaración solo vamos a especificar los tipos, ¿de acuerdo?
this declaration files we are going to be only like
9:56:54
así que solo los tipos, nada más, así que aquí puedes ver que
only specifying the types okay
9:56:58
tenemos un objeto de evento, así que va a ser un evento o indefinido y
so just the types nothing else so here you can see we
9:57:01
puedes aprender más sobre eso, así que si busco algo como
have an event object so it's going to be either an event or undefined and
9:57:04
no sé, documento, no un documento, sino obtener elemento por id o algo así, así que si hago clic en eso, aquí puedes
you can learn more about that so if i just search for like
9:57:08
ver que tenemos ese método obtener elemento por id justo aquí y
i don't know document not a document but get element by id or something like that so if i just click on that so here you can
9:57:15
el tipo de eso se establecerá en este elemento html
see we have that get element by id method right here and
9:57:18
justo aquí, así que si mantengo presionado ctrl y hago clic allí, así que aquí tú
the type of that will be set to this html element
9:57:22
puedes ver que solo incluirá los tipos, ¿verdad?
right here so if i hold ctrl and click on there so here you
9:57:25
puede ver que solo incluirá los tipos correctos
can see it's going to only include the types right
9:57:28
aquí, así que dentro de este archivo de declaración no vas a encontrar ningún código real, solo encontrarás, eh, ¿cómo lo llamamos? una declaración o los tipos aquí
here so inside this declaration file you are not going to find any real code but you will just find uh what do we call it a declaration or the types right here
9:57:38
está bien, eso fue todo sobre el archivo de declaración y así es como los tipos del compilador saben
okay so that was it about the declaration file and this is how the types of compiler knows
9:57:43
cada cosa sobre el DOM y todo ese tipo de cosas como bibliotecas de terceros
every single thing about the DOM and all of that kind of stuff like third-party libraries
9:57:47
pero ahora déjame mostrarte o antes de que te muestre
but now let me just show you or before i show you
9:57:50
primero que nada, déjame instalar una biblioteca aquí
that first of all let me just install one library right here
9:57:53
y si ya conoces axios totalmente
and if you already know axios totally
9:57:57
genial, si no conoces axios no tienes que preocuparte por
cool if you don't know axios you don't have to worry about
9:58:00
axios porque no vamos a escribir mucho código de axios, solo voy a escribir un poco de código de axios y ni siquiera tienes que preocuparte por eso, así que axios es
axios because we're not going to be writing a lot of axios code i'm going to just write a little bit of axios code and you don't even have to worry about that so axios is
9:58:09
la biblioteca que ya viene con la declaración
the library which already comes with the declaration
9:58:12
archivo, así que lo que quiero hacer es que ya
file so what i want to do is that i already
9:58:15
hacer una configuración para eso, voy a eliminar esas cosas
make a setup for that i am going to just remove that stuff
9:58:18
de aquí que especifiqué aquí, quiero compilar todos
from here which i specified right here i want to compile all
9:58:21
los archivos aquí, así que voy a eliminar eso y sí
of the files right here so i'm going to just remove that and yep
9:58:24
supongo que el resto de ellos será totalmente esto, voy a eliminar eso
i guess the rest of them will be totally this i'm going to just remove that
9:58:27
y ahora lo que quiero hacer es que voy a usar como
and now what i want to do is that i'm going to just use like
9:58:30
npm init -- o no -- sino -y aquí, voy a presionar
npm init dash dash or not dash dash but dash y right here i'm going to hit
9:58:36
enter aquí, así que solo va a usar este archivo package.json
enter right here so it's going to just use us this package.json file
9:58:40
no es nada, pero solo mantendrá un seguimiento de todas las dependencias que
it is nothing but it will just keep track of all of the dependencies which
9:58:43
vamos a instalar para este proyecto, así que actualmente solo
we are going to be installing for this project so currently we just
9:58:46
queremos instalar axios si ya conoces
only want to install the axios if you already know
9:58:49
axios, genial, si no conoces axios no tienes que preocuparte
axios cool if you don't know axios you don't have to worry
9:58:52
por eso, pero ahora déjame usar como npm i y
about that but now let me just use like npm i and
9:58:55
axios y si presiono enter, se va a instalar esta biblioteca axios dentro de mi máquina y sí, eso está totalmente instalado
axios and if i hit enter so it's going to install this axios library inside my machine and yep that's totally installed
9:59:03
la siguiente cosa que quiero hacer es que tengo que usar ese axios
the next thing which i want to do is that i have to use that axios
9:59:06
aquí en algún lugar, así que ya creé este index.ts
right here somewhere so i already created this index.ts
9:59:09
archivo aquí y lo siguiente que quiero hacer es que si
file right here and the next thing which i want to do is that if
9:59:12
simplemente escribo como importar axios de axios
i just write like import axios from axios
9:59:16
aquí y si guardo eso y si mantengo ctrl
right here and if i save that and if i hold ctrl
9:59:19
y hago clic en este axios aquí así que ya
and click on this axios right here so it already
9:59:22
viene con los tipos aquí como los archivos de declaración y aquí puedes ver que tenemos muchos tipos aquí como que no tenemos ningún código real pero tenemos muchos tipos aquí.
comes with the types right here like the declaration files and here you can see we have a lot of types right here like we don't have any actual code but we have a lot of types right here.
9:59:34
Sí, Axios ya viene con los tipos como ni siquiera Axios.
Yeah, Axios already comes with the types like not even Axios.
9:59:38
Hay muchas bibliotecas y marcos que ya vienen con los tipos de TypeScript aquí.
There are a lot of libraries and frameworks which already comes with the TypeScript types right here.
9:59:44
Así que ahora déjame mostrarte dónde puedes encontrar eso. Supongo que no estaba muy seguro de eso pero los tipos de TypeScript
So now let me just show you where you can find that. I guess that was not quite sure about that but TypeScript types
9:59:52
GitHub o algo así. Voy a buscar eso. Y ahí vamos. Este definitivamente tipo aquí. Así que si yo
GitHub or something like that. I'm going to just search for that. And there we go. This one definitely type right here. So if I
10:00:00
abro eso si sigo adelante y voy a este tipo definido voy a
open that if i go ahead and go to this definite type i'm going to
10:00:03
ir a eso y sí este repo es súper popular
go to that and yeah this repo is super popular
10:00:06
aquí y incluso puedes contribuir a eso por ti mismo
right here and you can even contribute to that by yourself
10:00:09
si tienes algún tipo de biblioteca o marco y eso necesita
if you have some sort of a library or framework and that needs
10:00:13
uh tipos así que también puedes proporcionar esto ahora déjame abrir
uh types so you can also provide this now let me just open
10:00:16
estos tipos aquí y aquí va a darnos un error esperemos un momento aquí puedes ver que va a darnos este error va a oh ni siquiera un error es supongo que un
these types right here and here it's going to give us an error let's just wait for that here you can see it's going to give us this error it's going to oh not even an error it's i guess a
10:00:25
advertencia lo siento tenemos que truncar este reintento porque
warning sorry we have to truncate this retry because it
10:00:29
incluye más de 1000 archivos yo
includes over 1000 files i
10:00:32
quiero decir que solo puede mostrarte los 1000 archivos pero sí
mean like it can only show you the 1000 files but yeah it
10:00:35
simplemente fallará al cargar todos sus archivos así que aquí puedes ver
will just fail to load all of their files so here you can see
10:00:38
tenemos muchos tipos para cada cosa
we have a lot of types for every single thing
10:00:42
aquí pero todavía hay muchos proyectos como por ejemplo puedes pensar en x no x use pero puedes pensar en express
right here but there are still a lot of projects like for instance you can think about x not x use but you can think about express
10:00:50
expressjs expressjs no viene con los tipos integrados así que
expressjs expressjs does not come with the built-in types so
10:00:53
sí ahora déjame escribir un loadash supongo que el loadash no incluye
yeah now let me just write a loadash i guess the loadash does not include
10:00:56
sus tipos así que ahora déjame escribir low dash venir
their types so now let me just write low dash come
10:00:59
en low dash y este repositorio es
on low dash and this repository is
10:01:02
supremamente horrible porque es totalmente grande
supremely awful because it is totally big
10:01:05
voy a hacer clic en este loadash y sí, está cargando mucho de todos modos, así que aquí puedes ver que no tenemos nada más
i'm gonna just click on this loadash and yeah it is loading a lot anyway so here you can see we don't have anything else
10:01:13
pero tenemos como todos sus archivos, ¿verdad?
but we have like all of their files right
10:01:16
aquí que termina con este .d y .ts
here which ends with this .d and .ts
10:01:20
justo aquí, así que tenemos todos sus archivos para todos
right here so we have all of their files for all
10:01:23
las cosas, así que si abro esta cabeza justo aquí y aquí puedes
of the things so if i just open this head right here and here you can
10:01:26
ver que tenemos solo un archivo simple justo aquí, uh tú
see we have just simple one file right here uh you
10:01:29
sabes que hay otra historia de la que no tienes que preocuparte, pero de todos modos
know what there's other story you don't have to worry about there but anyways
10:01:32
ya aprendiste sobre cuáles son nuestras declaraciones de tipo y cómo funciona, así que sabes qué, déjame usar este xus justo aquí, voy a crear un
you already learned about what our type declaration are and how it works so you know what let me just use this xus right here i'm going to just create a
10:01:40
función fetch data y va a ser igual a esta función asincrónica
function fetch data and it's going to be equals to this asynchronous function
10:01:43
y ya asumí que ustedes ya saben todas esas cosas
and i already assumed that you guys already know all of that stuff
10:01:46
así que voy a usar ese try y catch para un bloque try, ¿qué quieres, oh?
so i'm going to use that try and catch for a try block what do you want oh
10:01:49
sabes, primero que nada, no, déjame encargarme del else log
you know first of all no let me just take care of the else log
10:01:52
así que voy a usar como console, sabes qué, console punto
so i'm going to use like console you know what console dot
10:01:56
error y voy a escribir algún tipo de error justo aquí y para este vamos a escribir solo un error punto mensaje m-e-t-w-s-a-g-a
error and i'm going to just write some sort of error right here and for this one we are going to be just writing an error dot message m-e-t-w-s-a-g-a
10:02:05
ahí vamos y estamos obteniendo este increíble error
there we go and we are getting this awesome error
10:02:08
mensaje justo aquí del que nos vamos a encargar en
message right here which we are going to be taking care of in
10:02:11
unos segundos, así que sí, así que la siguiente cosa que quiero hacer
a few seconds so yeah so the next thing which i want to do
10:02:14
es que tengo que ajustar algún tipo de datos, así que voy a escribir como
is that i have to fit some sort of a data so i'm going to just write like
10:02:17
json, vamos, base de datos json placeholder peg justo aquí y tengo que ajustar algún tipo de datos de allí, voy a copiar este to do justo aquí
json come on json placeholder peg database right here and i have to fit some sort of a data from there i'm going to just copy this to do right here
10:02:27
y voy a escribir como const response y
and i'm going to just write like const response and
10:02:31
va a ser igual a um esta respuesta de axios
it's going to be equals to um this axios response
10:02:35
justo aquí, vamos, axio, oh, primero que nada importamos
right here come on axio oh we have first of all import
10:02:38
eso justo aquí, así que voy a proporcionar una coma
that right here okay so i'm going to just provide a comma
10:02:41
y voy a importar como respuesta de axios, ¿verdad?
and i'm going to just import like axios response right
10:02:44
aquí si puedo conseguir eso aquí y ahora tenemos que
here if i can get that right here and now we have to
10:02:47
usar eso así que voy a escribir como respuesta de axios qué demonios está pasando ahora déjame copiar eso y colocar eso aquí y aquí tenemos que anotar
use that so i'm going to just write like axios response what the hell is going on now let me just copy that and place that right here and here we have to annotate
10:02:56
ahí con la tarea como qué tipo de datos que estamos
there with the to do like which kind of data which we are
10:02:59
obteniendo de esta API específica aquí ahora déjame
going to be getting from this specific api right here now let me just
10:03:02
copiarlos colocar eso aquí así que ahora estamos obteniendo estos datos
copy them place that right here so we are now getting this data
10:03:05
como el id del usuario va a ser igual oh vamos como
like the user id is going to be equals oh come on like
10:03:09
el id del usuario va a ser igual a uno el id se establecerá en uno el
the user id is going to be equals to one the id will be set to one the
10:03:12
título se establecerá en alguna cadena y también el complicado se establecerá en algún tipo de valor booleano aquí así que también podemos crear una orden para hacer aquí ahora déjame
title will be set to some string and also the complicate will be set to some sort of a boolean value right here so we can also create order to do right here now let me just
10:03:21
interfaz cuadrada uh voy a dar un nombre como interfaz
squared interface uh i'm going to give a name of like interface
10:03:24
hacer y dentro de ahí podemos especificar un tipo para el
to do and inside there we can specify a type for the
10:03:27
id del usuario id título complicado aquí así que
user id id title complicated right here so
10:03:30
voy a escribir como id del usuario y va a ser igual a el
i'm going to just write like user id and it's going to be equals to the
10:03:33
número también voy a proporcionar el id también se establecerá en un
number i'm going to also provide the id will be also set to a
10:03:37
número y también tendríamos algún tipo de título que
number and also we would have some sort of a title which
10:03:40
se establecería en cadena y también tendríamos un completado no complicado dije complicado está completado ok así que sí ya
would be set to string and also we would have a completed not complicated did i say complicated it's completed okay so yeah we already
10:03:49
importamos eso y lo estamos usando aquí pero yo
import that and we are using that right here but i
10:03:52
olvidé usar el evento uh consciente y axios
forgot to use the event uh aware and axios
10:03:55
y luego tenemos que especificar el enlace donde quieres obtener eso
and then we have to specify the link where you want to get that
10:03:59
datos así que voy a escribir como punto obtener y vamos a estar
data so i'm going to just write like dot get and we are going to be
10:04:02
obteniendo nuestros datos de esta um uh url correcta
getting our data from this um uh url right
10:04:05
aquí voy a copiar eso y ahora déjame colocar eso aquí uh
here i'm going to copy that and now let me just place that right here uh
10:04:08
tengo que escribir dentro de las comillas volvamos y por qué en el mundo estamos obteniendo esta respuesta y si mantengo el mouse sobre eso así que
i have to write the inside of quotes let's just go back and why in the world we are getting this response and if i hold my mouse over to that so
10:04:16
no se puede extender la interfaz x oh vamos estoy usando
cannot extend the interface x oh come on i'm using
10:04:19
el signo igual aquí tengo que anotar eso
the equal to sign right here i have to annotate that
10:04:22
con esta tarea y también esta x usar respuesta aquí y
with this to do and also this x use response right here and
10:04:25
ahora déjame decir simplemente allí y r e s p
now let me just say over there and r e s p
10:04:28
o n s e no i s e está bien
o n s e not i s e okay
10:04:32
así que debajo de eso solo vamos a iniciar sesión en la consola como algunos
so underneath there we're going to be just logging into the console like some
10:04:35
una especie de tarea y voy a especificar esta respuesta
sort of a to do and i'm going to specify this response
10:04:38
qué demonios estoy haciendo ahora mismo así que response.data ahí vamos está bien así que sí para el error el error va a
what the hell am i doing right now so response.data there we go okay so yeah for the error the error is going to
10:04:45
ser cualquier error aquí como sí no sabemos qué tipo de error es
be any error right here like yeah we don't know which kind of error it's
10:04:49
nos va a lanzar así que podemos especificar cualquier error oh
going to throw us so we can specify any error oh
10:04:52
sabes qué déjame manejar eso correctamente así que voy a cortar eso de aquí
you know what let me just handle that properly so i'm going to cut that from here
10:04:55
y aquí lo que quiero hacer es que solo voy a buscar como
and here what i want to do is that i'm going to just search for like
10:04:59
si axios punto es axios
if axios dot is axios
10:05:02
error uh y aquí tenemos que especificar ese error
error uh and here we have to specify that error
10:05:05
justo aquí así que si ese es el caso así que solo voy a escribir como console punto
right here so if that's the case so i'm going to just write like console dot
10:05:08
error ahora déjame escribir console punto error y
error now let me just write console dot error and
10:05:11
voy a decir como axios error y también
i'm going to just say like axios error and also
10:05:15
déjame poner error punto mensaje justo aquí qué tipo de mensaje vamos a recibir de ese error y debajo de eso qué tienes que hacer tenemos
let me put error dot message right here which kind of message we are going to be getting from that error and underneath that what do you have to do we have
10:05:22
solo buscar esa respuesta de error uh si
to just search for that error response uh if
10:05:25
tienes la respuesta de error así que qué quieres hacer solo queremos registrar en la consola el
you have the error response so what do you want to do we just want to log to the console the
10:05:28
estado así que estado y solo voy a escribir
status so status and i'm going to just write
10:05:31
como respuesta de error iniciar estado justo aquí estoy
like error response start status right here i'm
10:05:34
voy a duplicar eso y cambiar este estado a datos correcto
going to duplicate that and change this status to data right
10:05:37
aquí y vamos a obtener los datos de esa respuesta y también déjame guardar eso para este s más qué tengo que hacer solo voy a escribir como um console punto error
here and we are going to be getting the data from that response and also let me just save that for this s plus what do i have to do i'm going to just write like um console dot error
10:05:48
y aquí solo tenemos que escribir ese error vamos error
and here we just have to write that error come on error
10:05:52
punto mensaje justo aquí ahora déjame guardar eso y ahora déjame
dot message right here now let me just save that and now let
10:05:55
ejecutar este método justo aquí voy a ejecutar eso
me just execute this method right here i'm going to just execute that
10:05:58
justo aquí voy a enviar mi archivo y voy a
right here i'm going to send my file and i'm going to
10:06:01
simplemente ejecutaré mi código aquí para que nos dé todo eso mejor
just run my code right here so it's going to give us all of that better
10:06:05
aquí va a tomar un poco de tiempo, así que aquí puedes ver que tenemos que hacer y hacer es igual a este objeto aquí, así que ahora estamos obteniendo el id de usuario también el
right here it's going to take a bit of time so here you can see we have to do and to do is equals to this object right here so we are now getting the user id also the
10:06:13
id y también el título y completo ahora está configurado
id and also the title and complete is now set
10:06:16
en falso aquí, lo que significa que todo está bien
to false right here so which means like everything is a okay
10:06:19
y así es como vamos a estar usando TypeScript con Axios
and this is how we are going to be using a typescript with axios
10:06:23
biblioteca, debes saber que no tienes que saber eso, pero
library do you have to know that you don't have to know that but
10:06:26
sí, eso fue TypeScript con Axios, así que ahora finalmente
yeah that was a typescript with axios so now finally
10:06:29
voy a mostrarte algún tipo de biblioteca que no viene automáticamente
i'm going to just show you some sort of a library which does not automatically
10:06:32
con los tipos de TypeScript, así que
comes with the typescript types so
10:06:36
para eso vamos a tener que instalar un tipo separado, así que lo que yo
for that we're going to have to install a separate type so what i
10:06:39
quiero hacer es que voy a instalar simplemente Express
want to do is that i'm going to just install the express
10:06:42
js aquí, así que voy a usar como uh npm venir
js right here so i'm going to just use like uh npm come
10:06:45
en npm i y express y
on npm i and express and
10:06:49
no vamos a estar escribiendo mucho código de Express, pero voy a hacer una configuración general
we are not going to be writing a lot of express code but i'm going to just make a general
10:06:52
de Express js, así que sí, va a tomar un poco de tiempo
setup of express js so yeah it's going to take a bit of time
10:06:55
para instalar este Express js en mi máquina y voy a
to install this express js into my machine and i'm
10:06:58
simplemente dejar que haga su cosa y ahí vamos, ahora está instalado con éxito, voy a ir a mi package.json aquí y ahora déjame escribir
going to just leave it to do its thing and there we go it is now successfully installed i'm going to go ahead and go to my package.json right here and now let me just write
10:07:06
algún tipo de script para mí, ni siquiera tienes que
some sort of a script for myself you don't even have
10:07:09
preocuparte por lo que es Express js si te importa esto
to worry about what express js is if you do care about this
10:07:12
así que tengo un curso completo allí si quieres verlo, pero si no
so i have a complete course on there if you want to check it out but if you
10:07:15
te importa eso, así que no tienes que, déjame escribir un inicio
don't care about that so you don't have to let me just write a start
10:07:18
vamos, inicio y voy a escribir como ts-node
come on start and i'm going to just write like ts-node
10:07:23
directorio src y voy a ejecutar mi índice
src directory and i'm going to just run my index
10:07:26
quiero decir, como uh index.ts aquí, ahora voy a crear la carpeta src aquí y voy a poner mi index.js
i mean like uh index.ts right here now i'm going to just create src folder right here and i'm going to just put my index.js
10:07:34
justo allí y ahí vamos, así que sí, voy a abrir mi archivo index.ts aquí, ahora déjame
right there and there we go so yeah i'm
10:07:37
voy a abrir mi archivo index.ts aquí ahora déjame
going to open my index.ts file right here now let
10:07:40
quitar eso de adentro, ¿qué tengo que hacer si solo
me just remove that inside there what do i have to do if i just
10:07:43
escribo como import express from
write like import express from
10:07:47
express aquí, así que si paso el mouse por ahí
express right here so if i hold my mouse over to there
10:07:50
así que express está declarado, su valor nunca se lee
so express is declared its value is never read
10:07:53
podemos encargarnos de eso en unos segundos, pero no se pudo encontrar un archivo de declaración o un módulo express js aquí
we can take care of that in a few seconds but could not find a declaration file or a module express js right here
10:08:00
así que instalamos expressjs con éxito, pero también tenemos que
so we successfully installed expressjs but we also have to
10:08:03
instalar los archivos de declaración para eso, así que si paso el mouse
install the declaration files for that so if i hover my mouse
10:08:06
por eso y aquí verás esa solución rápida
over to that and here you will see that quick fix
10:08:09
aquí, uh, solo voy a hacer clic en eso, así que aquí puedes
right here uh i'm gonna just click on that so here you can
10:08:12
ver si quieres instalar los tipos o simplemente eliminar eso
see either install the types or just remove that
10:08:15
ok, así que aquí puedes ver si quieres instalar eso manualmente usando una terminal, así que tendrás que escribir este comando que es, primero que todo, escribir npm i y luego tienes que usar como
okay so here you can see if you want to install that manually by using a terminal so you are going to have to write this command which is first of all write npm i and then you have to use like
10:08:25
agregar tipos y luego barra inclinada expressjs aquí
add types and then forward slash expressjs right here
10:08:29
pero si estás usando un vs code, solo tienes que pasar el mouse por
but if you are using a vs code so you just have to hold your mouse over
10:08:32
eso, hacer clic en una solución rápida y luego hacer clic en esta instalación
to that click on a quick fit and then click on this install
10:08:35
aquí, así que se va a instalar automáticamente en tu máquina, así que
right here so it's going to automatically install it into your machine so
10:08:38
sí, voy a tener que esperar a que instale todos sus tipos, así que aquí puedes ver que ha desaparecido con éxito y solo voy a escribir como const app y va a ser igual a como express jazz
yeah i'm going to have to wait for that to install all of their types so here you can see that it is successfully gone and i'm going to just write like const app and it's going to be equals to like express jazz
10:08:48
vamos express, uh exp
come on express uh exp
10:08:51
en aws, sí, y ahora tengo que
on aws yep and now i
10:08:55
simplemente escribir express e y también e
have to just write express e and also e
10:08:58
aquí también, ahora déjame crear algún tipo de puerto y va a ser
here as well now let me just create some sort of a port and it's going to be
10:09:01
igual a como oh Dios mío, tres mil aquí
equals to like oh my god three thousand right here
10:09:04
y ahora déjame usar como abdell listen y
and now let me just use like abdell listen and
10:09:07
quieres escuchar el puerto y también ahora déjame ejecutar
you want to listen to the port and also now let me just execute
10:09:10
console log y vamos servidor
console log and come on server
10:09:14
ejecutando en el puerto y ahora déjame renderizar
running on port and now let me me just render
10:09:17
mi puerto aquí, solo volvamos y
my port right here let's just go back and
10:09:21
voy a usar mis comillas invertidas aquí como
i'm going to use my backticks right here like
10:09:24
eso y eso es todo, también voy a crear una ruta
that and that's it i'm going to also create one route
10:09:27
aquí así que voy a usar como app punto get, va a ir a la página de inicio
right here so i'm going to use like app dot get it's going to go to the home
10:09:30
y solo proporcionemos o solicitemos y también la respuesta, y aquí lo que tienes que hacer es escribir res punto no, oh sí, respuesta, ahí vamos
and let's just provide or request and also the response as well and here what do you have to do you just have to write res dot not oh yeah response there we go
10:09:41
respuesta comienza a enviar, también puedes abreviarlo a rec y res, pero solicitud y respuesta serían
response start send you can also abbreviate that to the rec and res but request and response would
10:09:45
más grande, así que solo voy a escribir hola typescript express
bigger so i'm going to just write hello typescript express
10:09:49
js o algo así, y ahora si mantengo mi
js or something like that and now if i hold my
10:09:52
ratón sobre esta respuesta aquí, así que la respuesta es respuesta, cualquier respuesta y sí, esta es nuestra función genérica, ¿verdad?
mouse over to this response right here so response is response any response and yeah this is our generic function right
10:09:59
aquí, pero también podemos importar las respuestas manualmente, así que
here but we can also import the responses manually so
10:10:02
voy a tener que escribir una coma y solo voy a obtener la solicitud y
i'm going to just have to write a comma and i'm going to just get the request and
10:10:06
también la respuesta, así que si
also the response as well okay so if i
10:10:09
las obtengo, también podemos proporcionar tipos para eso, así que estoy
get them we can also provide a types for that so i'm
10:10:12
simplemente copiándolas y anotando eso como una solicitud
going to just copy them and annotate that as a request
10:10:15
y también puedo copiar esta respuesta y anotarla con esta respuesta aquí, así que ahora déjame guardar eso y voy a
and i can also copy this response and annotate that with this response right here okay so now let me just save that and i'm going
10:10:23
simplemente usar mi terminal y voy a decir como npm start
to just use my terminal and i'm gonna just say like npm start
10:10:26
para iniciar mi servidor y yo
to start my server and i
10:10:30
supongo que eso sería todo, así que aquí puedes ver que todo está comenzando
guess that would be it okay so here you can see everything is starting
10:10:33
todo bien, pero va a tomar un poco de tiempo, así que
a-okay but it's gonna take a bit of time so
10:10:36
el servidor está corriendo en el puerto 3000, así que estoy
server is running on port 3000 so i'm
10:10:39
simplemente escribiendo como un localhost de 3000 y si lo presiono
gonna just write like a local host of 3000 and if i hit that
10:10:42
así que aquí puedes ver que ahora estamos obteniendo como hola typescript con express js, está bien, así que en tu caso va a verse algo así, así que sí, ese fue el final de este curso
so here you can see we are now getting like hello typescript with express js okay so in your case it's gonna look something like this so yeah that was the end of this course
10:10:52
y todavía quedan como dos secciones si quieres que haga
and there are still like two sections left if you want me to make
10:10:55
un curso sobre eso, como typescript con react.js y también typescript
a course on that like typescript with react.js and also typescript
10:10:58
con next.js definitivamente puedo hacer un curso sobre ellos pero
with next.js i can totally make a course on them but
10:11:02
este curso era solo para aquellas personas que quieren aprender
this course was just for those people who wants to learn
10:11:05
typescript y quieren usarlo en sus proyectos así que eso era todo lo que sé sobre typescript y lo uso a diario así que esa fue la
typescript and want to use it in their projects so that was all of the things i know about typescript and i use that daily so that was the
10:11:14
final de este curso y solo tengo una solicitud
end of this course and i only have one request
10:11:17
de ustedes déjenme simplemente
from you guys let me just
10:11:20
decir que si ustedes quieren apoyarme así que voy a
say that if you guys want to support me so i'm going to
10:11:23
darles un enlace en la descripción de abajo y los llevará a mi
give you a link in the description below and it will bring you to my
10:11:26
repositorio de github y pueden simplemente comenzar ese repo y
github repository and you can just start that repo and
10:11:30
pueden proporcionar lo que puedan pagar por ese repo y
you can provide you can afford that repo and
10:11:33
pueden hacer lo que quieran hacer con su repo así que lo que les pido a ustedes es que por favor me sigan en github y si quieren apoyar este canal siéntanse libres de suscribirse
you can do whatever you want to do with their repo so what i'm asking you from you guys is then please follow me on github and if you want to support this channel so feel free to subscribe
10:11:44
así que si no quieren apoyar así que sí, gracias por ver de todos modos y tal vez los veré en el próximo curso pero adiós por ahora y los amo a todos
so if you don't want to support so yeah thanks for watching anyways and maybe i'm gonna see you in the next course but bye from now and love you all
10:12:04
muy bien chicos así que ahora vamos a estar usando typescript con react.js así que si ustedes no
all right guys so now we are going to be using a typescript with react.js so if you guys don't
10:12:09
saben qué es typescript tengo un curso completo
know what a typescript is i have a complete course
10:12:13
ahí mismo así que esto va a ser como más
on there right here so this is going to be like more
10:12:16
que un curso loco como si te importa aprender typescript
than a crazy course like if you care about learning typescript
10:12:19
este va a ser el último curso para que aprendas, está bien así que
this is going to be the last course for you to learn okay so
10:12:22
sí, aprende allí y luego vuelve a este video y
yeah learn there and then come back to this video and
10:12:26
ahora vamos a estar aprendiendo sobre typescript con reactjs así que
now we are going to be learning about typescript with reactjs so
10:12:29
para hacer eso primero tenemos que hacer una configuración así que voy a abrir mi terminal aquí y ahora voy a estar usando npm create read at
to do there first of all we have to make a setup so i'm going to open my terminal right here and now i'm going to be using npm create read at
10:12:36
latest ahora si presiono enter ahora tenemos que darle algún tipo
latest now if i hit enter now we have to give it some sort
10:12:39
de un nombre como ts demos o algo así en
of a name like ts demos or something like that in
10:12:43
este caso voy a elegir react js y también
this case i'm going to be choosing react js and also
10:12:46
typescript no vamos a elegir javascript vamos a
typescript we are not going to be choosing javascript we're
10:12:49
elegir typescript así que si solo presiono enter ahora tenemos que
going to be choosing typescript so if i just hit enter now we have
10:12:52
ir a este ts demos y ahora si presiono enter y voy a estar usando un código punto para abrir eso aquí, luego déjame abrir mi terminal y voy a estar usando npm i para instalar todas las dependencias
to go into this ts demos and now if i hit enter and i'm going to be using a code dot to open that right here next let me open my terminal and i'm going to be using npm i to install all of the dependencies
10:13:04
y todas sus dependencias están ahora instaladas con éxito, así que aquí
and all of their dependencies are now successfully installed so here
10:13:07
puedes ver que tenemos nuestra carpeta src y ahora dentro de esta src
you can see we have our src folder and now inside this src
10:13:10
carpeta ahora estamos usando tsx
folder we are now using tsx
10:13:13
extensión aquí puedes usar ts o también puedes
extension right here you can either use ts or you can also
10:13:16
usar tsx en lugar de jsx ahora estamos
use tsx instead of jsx now we
10:13:19
trabajando con typescript así que para eso tenemos que usar el tsx así que
are working with typescript so for that we have to use the tsx so
10:13:23
puedo limpiar cada cosa que no necesitamos allí, así que solo voy a eliminar todo eso y vamos a guardar una barra para este y supongo que eso estará bien, pero tendré que eliminar este archivo index.css de allí.
i can just clean up every single thing we don't need there so i'll just remove all of that and let's just save a bar to this one and i guess that's going to be fine but I'm going to have to remove this index.css file from there.
10:13:34
Tenemos que ir a la aplicación y solo voy a eliminar cada cosa de aquí.
We have to go into the app and I'm going to just remove every single thing from here.
10:13:38
Vamos a usar nuestro rafce y eso estará bien.
Let's just use our rafce and that's going to be fine.
10:13:41
Voy a eliminar también esta carpeta pública porque tampoco la necesitamos y ahora si guardo mi archivo y lo abro en mi navegador usando npm run dev, aquí puedes ver que ahora estamos obteniendo nuestra aplicación.
I'm going to also remove this public folder because we also don't need that and now if I save my file and open that inside my browser by using npm run dev and here you can see we are now getting our app.
10:13:53
Así que la configuración ya está totalmente lista. A continuación, vamos a aprender sobre las propiedades de los componentes en acción.
So the setup is now totally done. Next we are going to be learning about component props in action.
10:13:57
Así que para hacer eso, primero vamos a crear un componente.
So to do that first of all we are going to be creating a component.
10:14:01
Así que solo voy a crear una carpeta de componentes y dentro de esta carpeta
So I'll just create a components folder and inside this folder
10:14:04
voy a crear algo como user.tsx, ahora estamos trabajando
i'm going to create like user.tsx we are now working
10:14:07
con typescript, así que tenemos que especificar tsx como extensión ahora
with type script so we have to specify tsx as extension now
10:14:11
dentro de eso vamos a usar nuestro rafcu para crear nuestro componente
inside that we are going to be using our rafcu to create our component
10:14:14
aquí guarda mi archivo, ahora voy a ir a mi aplicación
right here save my file now i'm going to go into my app
10:14:17
componente y ahora solo voy a eliminar esta aplicación y en lugar de eso
component and now i'll just remove this app and instead of that
10:14:20
la aplicación, voy a reemplazarla con este usuario, vamos a
app i'm going to just replace that with this user we're going to be
10:14:23
importar su inodoro directamente en el archivo knifey semi y ahora estamos obteniendo nuestro usuario aquí, lo cual es increíble, así que lo que voy a hacer es que voy
importing their toilet directly in knifey semi file and we are now getting our user right here which is amazing so what i'm going to do is that i'm
10:14:31
a pasar algunas propiedades, así que solo usaré algo como nombre y nombre
going to pass a few props right so i'll just use like name and name
10:14:34
puede ser cualquier cosa como alex o hosan o algo así, voy
can be anything like alex or hosan or something like that i'm
10:14:37
a especificar también la edad de 20 para él y también
going to also specify the age of 20 to him and also the
10:14:40
es estudiante, ¿es él un estudiante o no? así que solo voy a especificar
is student is he a student or not so i'll just specify
10:14:43
valor verdadero y tan pronto como haga eso, ahora estoy obteniendo este
true value and as soon as i do that i'm now getting this
10:14:47
error justo aquí así que si paso el mouse por ahí ahora me está diciendo
error right here so if i hover my mouse over to there it is now telling
10:14:50
que el tipo de esta propiedad que estás especificando aquí no es asignable al tipo de atributo intrínseco
me that the type this prop which you are specifying right here is not assignable to the type intrinsic attribute
10:14:57
está bien, tienes que hacer algo al respecto, como si estuvieras proporcionando estos
okay like you have to do something about that like you're providing these
10:15:01
props pero no los estás usando dentro de este componente
props but you are not using them inside this component
10:15:04
y para usarlos ya sabes cómo vamos a estar usando
and to use them you already know how we are going to be using
10:15:07
así que podemos usar como props justo aquí y ahora
them so we can just use like props right here and now
10:15:10
podemos usarlo totalmente aquí en el componente del servidor, así que solo usaré como no sé, tal vez h2 y vamos a estar usando como props.nombre, primero déjame duplicar algunas veces props.edad y también
we can totally use the right here in server component so i'll just use like i don't know maybe h2 and we are going to be using like props.name first of all let me just duplicate a few times props.age and also
10:15:22
es estudiante justo aquí, así que si guardo mi archivo y como
is student right here so if i sell my file and as
10:15:25
puedes ver que ahora estamos obteniendo a alex y también 20 y no podemos ver
you can see we are now getting alex and also 20 and we cannot see
10:15:28
que es estudiante porque este es un valor booleano y
that is student because this is a boolean value and
10:15:31
ahora aquí si paso el mouse por ahí me está dando un
now here if i hover my mouse over to there it is giving me an
10:15:34
error como los props de perímetro implícitamente tienen cualquier tipo
error like perimeter props implicitly has any type
10:15:38
lo que simplemente significa que no estás usando ningún
like which simply means you are not using any
10:15:41
typescript, así que si quieres usar typescript tienes que hacer algo al respecto, así que quiero usar typescript, así que para eso voy a tener que especificar un tipo
typescript so if you want to use typescript you got to do something about that so i want to use typescript so for that i'm going to have to specify a type
10:15:49
para el nombre, para la edad y también para el estudiante y
for the name for the age and also for the student and
10:15:52
¿por qué es eso? porque ahora estamos pasando estos datos y
why is that because we are now passing this data and
10:15:55
no estamos proporcionando ningún tipo para eso, así que para proporcionar un tipo
we are not providing any type for that so to provide a type
10:15:58
para eso vamos a estar anotando nuestra propiedad así, está bien
for that we are going to be annotating our prop like this okay
10:16:02
así que primero me encargaré del nombre y el nombre es un valor de cadena
so i'll just first of all take care of the name and name is a string value
10:16:05
que ya sé porque ahora estamos especificando un valor de cadena y ahora sabemos que también tenemos una edad y la edad es un número y también tenemos una propiedad de estudiante que es un booleano
which i already know because we are now specifying a string value and now we know that we also have a age and age is a number and also we have a student property which is a boolean
10:16:17
está bien, así que tan pronto como proporcione eso y guarde mi archivo aquí
okay so as soon as i provide that and save my file here
10:16:20
puedes ver que ya no estamos obteniendo ese error y por qué es
you can see we are no longer getting that error and why is
10:16:23
eso porque ahora le estamos diciendo explícitamente a nuestro compilador que
that because we are now explicitly telling our compiler that
10:16:26
el nombre debe ser una cadena, el h
the name should be a string the h
10:16:29
debería ser, vamos, déjame conseguir eso, debería ser un número
should be come on let me just get that it should be a number
10:16:33
y también el estudiante debería ser un valor booleano así que
and also the student should be a boolean value so
10:16:36
por eso nuestro compilador de typescript ahora sabe qué tipo usar, así que ahora si guardo mi archivo y solo los actualizo, seguimos obteniendo el mismo resultado y no estamos
that's why our typescript compiler now know which type to use so now if i save my file and just refresh them we are still getting their same result and we are not
10:16:45
obteniendo errores dentro de nuestro vs code, ahora esa es la primera
getting any errors inside our vs code now that's the first
10:16:48
manera, pero en algunas situaciones también querríamos desestructurar nuestros valores
way but in some situation we would also want to destructure our values
10:16:51
de estas props, así que ¿cómo vamos a hacer eso? Bueno,
from these props so how are we going to be doing there well
10:16:54
ya proporcionamos un tipo para eso, solo tenemos que desestructurar
we already provided a type for that we just have to destructure
10:16:57
todos esos valores, así que solo voy a eliminar estas props y solo voy a reemplazar
all of that values so i'll just remove these props and i'll just replace
10:17:01
las con estas llaves, quieres desestructurar el nombre, la edad
them with these curly braces you want to destructure the name the age
10:17:05
y también el es estudiante aquí, así que tan pronto como yo
and also the is student right here so as soon as i
10:17:08
hago eso, aquí puedes ver que ahora estoy obteniendo como no se puede encontrar el nombre de
do that here you can see i'm now getting like cannot find name of
10:17:11
la prop, como no estamos usando una prop, así que por eso estamos obteniendo este error
prop like we are not using a prop so that's why we are getting this error
10:17:14
así que voy a seleccionar esa primera, presionar ctrl d, ctrl d
so i'm going to select that first one hit ctrl d ctrl d
10:17:17
y eliminar ahí, así que tan pronto como solo elimine el punto y coma
and remove there so as soon as i just remove the semi
10:17:20
este es cómo se verá mi formato, sé que parece un poco loco, pero sí, así es como vamos a
file this is how my formatting will look like i
10:17:24
desestructurar nuestros datos y esto
know it seems a bit crazy but yeah this is how we are going to
10:17:27
es cómo vamos a proporcionar nuestros tipos para nuestros datos, así que
be destructuring our data and this
10:17:30
quiero que tengas eso en mente, así que esta es solo una forma básica de proporcionar nuestra prop, ahora déjame mostrarte cómo vamos a extraer todos sus tipos en
is how we are going to be providing our types for our data so
10:17:34
una forma separada o un tipo separado, está bien, así que solo voy a
i want you to keep that in mind so this is just a basic way of providing our prop now let me show you how we are going to be extracting all of their types into either a
10:17:42
cortar eso de aquí y también voy a eliminar eso de aquí y
separate shape or a separate type okay so i'll just
10:17:45
una vez más estamos obteniendo todos esos errores aquí, así que para hacer eso podemos crear un tipo, ya sabes cómo crear un tipo si vienes de mi
cut that from here and i'm going to also remove that from here and
10:17:48
curso de typescript, pero si no sabes cómo crear un tipo, deberías
once again we are getting all of that errors right here so to do that we can either create a type you already know how to create a type if you are coming from my
10:17:55
adelante y ver mi curso de typescript, ahora solo voy a crear mi tipo
typescript course but if you don't know how to create a type you
10:17:59
y le voy a dar el nombre de forma de usuario, básicamente puedes darle cualquier nombre que desees y ahora dentro de eso solo vamos a
should go ahead and watch my typescript course now i'll just create my type
10:18:02
espaciar tipos de palabras aquí, así que ahora estamos creando nuestro
and i'm going to give it the name of like user shape you can basically give it any name that you like and now inside there we are going to be just
10:18:08
forma de usuario, pero ahora tenemos que decirle a nuestro componente que lo hagamos.
spacing word types right here so we are now creating our
10:18:11
forma de usuario pero ahora tenemos que decirle a nuestro componente que
user shape but now we have to tell our component that we
10:18:14
queremos usar esta forma de usuario así que voy a copiar de aquí
want to use this user shape so i'm going to copy there from here and
10:18:18
voy a solo anotar las propiedades de mi componente a esta forma de usuario
i'm going to just annotate my component props to this user shape
10:18:21
así que tan pronto como haga eso voy a guardar mi archivo y refrescar
so as soon as i do that i'm going to save my file and refresh
10:18:24
ahí y aún estamos obteniendo ese mismo resultado y esos errores
there and still we are getting that same result and that errors
10:18:27
ya han desaparecido con éxito así que esa es la primera forma ahora
are now successfully gone so that's the first way now i
10:18:30
puedo comentar completamente esta línea y también podemos crear una interfaz para esto así que solo usaré como interfaz y le daré el nombre de usuario
can totally comment this line out and we can also create an interface for this so i'll just use like interface and i'm going to give it the name of like user
10:18:37
una vez más y no vamos a usar ningún signo igual
shape one more time and we're not going to be using any equals to sign
10:18:40
porque ahora estamos trabajando con la interfaz y ahora dentro de ahí podemos
because we are now working with the interface and now inside there we can
10:18:43
usar como nombre será una cadena y edad será un número y
use like name will be a string and age will be a number and
10:18:46
también tenemos la propiedad de este estudiante que es estudiante y eso va a ser el valor booleano
also we have the property of this student come
10:18:50
así que tan pronto como haga esto semi archivo y aquí puedes
on is student and that's going to be the boolean value
10:18:53
ver que estamos obteniendo el mismo resultado y ya no estamos obteniendo sus
so as soon as i do this semi file and here you
10:18:56
mensajes de error justo aquí así es como vamos a trabajar con los prompts con el componente pero ahora en algunas situaciones también querrás
can see we are getting the same result and we are no longer getting their
10:18:59
usar los hijos así que ahora déjame solo quitar eso de aquí estoy
error messages right here this is how we are going to be working with the prompts with the component but now in some situation you will also want to
10:19:06
a llamar a mi componente de esta manera así que queremos pasar
use the children so now let me just remove that from here i'm
10:19:09
algún tipo de jsx dentro de ahí no voy a hacer nada loco
gonna call my component as this way so we want to pass
10:19:12
pero solo pondré un párrafo que dirá como hola que
some sort of a jsx inside there i'm not gonna do anything crazy
10:19:15
significa que queremos usar nuestros hijos justo aquí así que
but i'll just put a paragraph which will just say like hello which
10:19:18
para usarlos para eso vamos a estar usando nuestros hijos así que
means like we want to use our children right here so
10:19:21
para usarlos para eso vamos a estar usando a nuestros hijos así que
to use them for that we are going to be using our children so
10:19:25
tenemos que reestructurar a nuestros hijos justo aquí vamos niños voy a copiar eso y tenemos que reemplazarlos con este h1 o tal vez y tenemos que renderizar a nuestros hijos justo aquí.
we have to restructure our children right here come on children i'm gonna copy that and we have to replace them with this h1 or maybe and we have to render our children right here.
10:19:36
Así que si guardo mi archivo, todavía estamos obteniendo este error aquí porque este children no tiene propiedad y no está disponible dentro de esta forma de usuario.
So if I save my file, still we are getting this error right here because this children has no property and it is not available inside this user shape.
10:19:45
Así que voy a quitar eso de aquí y solo puedo escribir como children. ¿Y ahora cuál será el tipo de este children?
So I'm going to remove that from here and I can just write like children. And now what will be the type of this children?
10:19:52
Como esto no es una prop. Esto no es ni una cadena ni un número o booleano o indefinido o algo así.
Like this is not a prop. This is neither a string nor a number or boolean or undefined or anything like this.
10:19:58
¿Qué demonios?
So what in the world?
10:20:00
vamos a especificar para estos niños, así que estamos
going to be specifying for this children so we are
10:20:03
vamos a usar algo llamado el nodo de react, está bien
going to be using something called the react node okay
10:20:06
así que si solo uso como el nodo de react y si presiono enter
so if i just use like react node and if i hit enter
10:20:09
así que se va a importar automáticamente aquí, como puedes ver, así que si
so it's going to auto import there right here as you can see so if
10:20:12
vendo mi archivo aquí, puedes ver que no estamos obteniendo ningún error y
i sell my file here you can see we are not getting any errors and
10:20:15
aquí puedes ver que estamos obteniendo lo que hello, pero ahora quiero ver qué hay dentro de este nodo de react, así que si mantengo mi control o comando y si hago clic en esto, nos llevará a
here you can see we are getting what hello but now i want to see like what is inside this react node so if i hold my control or command and if i click on this is going to brings us to
10:20:26
lo adivinaste, index.d.ts, que
you guessed it index.d.ts which
10:20:29
significa que esto nos lleva a un archivo de tipos, como este archivo solamente
means like this kind of brings us to types file like this file only
10:20:32
incluye los tipos, nada más que eso, así que
includes the types nothing else than there so
10:20:35
este nodo de react puede ser un elemento de react, ya sea un número de cadena
this react node can either be a react element either a string number
10:20:38
iterable, portal, booleano, nulo, indefinido
iterable portal boolean null undefined
10:20:41
y hay muchas cosas que puedes explorar en esto
and there are a lot of things that you can explore in this
10:20:44
archivo, pero nunca te recomendaré que explores este archivo, hay muchas cosas pasando aquí, está bien, así que solo lo quitaré de aquí y así es como
file but i will never recommend you to like explore this file there are a lot of things going on right here okay so i'll just remove that from here and this is how
10:20:54
vamos a especificar nuestro nodo de react para nuestros niños
we are going to be specifying our react node for our children
10:20:57
ahora esta es la forma moderna de proporcionar nuestra forma para
now this is the modern way of providing our shape for
10:21:00
nuestro prop, pero también hay otra forma que encontrarás como
our prop but that is also another way you will find like
10:21:03
en la documentación o alguien más lo llama, así que también quiero
in the documentation or somebody else call so i also want
10:21:06
mostrártelo allí, que se llama el fc o componente funcional
to show you there so which is called the fc or functional component
10:21:10
así que lo que voy a hacer es que voy a quitar eso de aquí y
so what i'm going to do is then i'm going to just remove that from here and
10:21:13
voy a volver a mi antiguo prop, como
i'm going to go back to my old prop like
10:21:16
tenemos el nombre edge y también el estudiante, voy a guardar ese archivo, también voy a quitar eso de aquí, también no necesitamos estos niños, así que simplemente
we have the name edge and also the student i'm going to save that file i'm going to also remove that from here we also don't need these children so let's just
10:21:23
quitar eso y también quitar esto, está bien, así que solo tenemos
remove that and also remove this okay so we only have
10:21:26
esta forma de usuario y voy a descomentar allí ahora
this user shape and i'm going to uncomment there right now
10:21:29
archivo semi, ahora también voy a desestructurar mi nombre y edad
semi file now i'm going to also destructure my name age
10:21:33
y también la propiedad del estudiante justo aquí y ahora déjame mostrar
and also the student property right here and now let me show
10:21:36
la forma anterior de proporcionar una propiedad para nuestro tipo de script, así que así es como lo vamos a hacer. Primero que nada, tenemos que proporcionar nuestro colon, luego tenemos que escribir fc que vendrá de react js como puedes ver aquí
you the older way of providing a prop for our type script so this is how we are going to be doing there first of all we have to provide our colon then we have to write fc which will be coming from the react js as you can see right here
10:21:47
fc como un componente funcional viene de react js y ahora tenemos que escribir como menor que
fc like a functional component is coming from the react js and now we have to write like less than
10:21:52
signo y aquí tenemos que especificar como una forma de usuario y
sign and here we have to specify like a user shape and
10:21:55
tenemos que cerrar allí y una vez que cierras allí y si paso mi
we have to close there and once you close there and if i hover my
10:21:58
ratón por encima de allí, dice que todos los elementos de desestructuración no se utilizan
mouse over to there it is saying like all destructure elements are unused
10:22:02
como si no estás utilizando el interior de tu código y ahora
like you are not using the inside your code and now
10:22:05
para solucionar este problema vamos a usar esto, así que solo usaré como h1
to fix this problem we are going to be using this so i'll just use like h1
10:22:09
escribiré mi nombre y luego la edad y luego finalmente es la propiedad del estudiante justo aquí, así que si guardo allí y aquí puedes ver que esta es otra forma de proporcionar una propiedad a nuestro componente.
i'll write my name and then age and then finally is student property right here so if i save there and here you can see this is yet another way of providing a prop to our component.
10:22:20
Bienvenido al primer desafío de react typescript. Así que en este quiero que crees el componente de botón que tomará tres propiedades como etiqueta, al hacer clic y deshabilitar.
Welcome to the react typescript first challenge. So in this one I want you to create the button component which will take three prop like label on click and disable.
10:22:28
Así que la etiqueta será solo la etiqueta del botón de avanzar y el
So label will be just the label forward button and the on
10:22:31
clic será una función que se ejecutará cada vez que alguien haga clic
click will be a function which will be executed whenever somebody clicks
10:22:34
en nuestro botón y también el deshabilitar será un estado como podemos indicar ya sea verdadero o falso y va a hacer que nuestro botón esté deshabilitado o
on our button and also the disable will be a state like we can indicate either the true or false and it's going to make our button either disable or
10:22:43
habilitado, así que finalmente tienes que importar ese componente
enable so then finally you have to import that component
10:22:46
dentro del archivo app.tsx y simplemente ejecutar eso
inside the app.tsx file and just run that
10:22:49
y asegúrate de que no obtuviste ningún error, así que dale tu mejor esfuerzo
and make sure that you didn't get any errors so give it your best shot
10:22:52
si puedes hacerlo, está completamente bien, luego vuelve y mira la
if you can do it that's completely okay then come back and watch the
10:22:55
solución y ahora te voy a dar mi solución, así que lo que
solution and now i'm going to give you my solution so what
10:22:58
voy a hacer es que voy a crear mi componente y dentro de este
i'm going to do is that i'm going to create my component and inside this
10:23:01
componente solo crearé mi bond.tsx, en este caso es
component i'll just create my bond.tsx in this case it's
10:23:04
porque ahora estamos trabajando con time script, así que vamos a tener que crear este tsx, ahora solo escribiré mi archivo rafc semi, iré a mi app y registraré eso
because we are now working with time script so we're going to have to create this tsx now i'll just write my rafc semi file go to my app and register that
10:23:12
componente justo aquí, así que solo escribiré mi botón y
component right here so i'll just write my button and
10:23:16
cerrar allí, como mencioné, tomará tres propiedades
close there like so as i mentioned it's going to take three props
10:23:19
así que solo escribiré una etiqueta y la etiqueta se establecerá en clic, así que
so i'll just write a label and the label will be set to click so
10:23:22
solo escribiré un clic aquí y también el evento de clic
i'll just write a click right here and also the on click event
10:23:26
manejador en este caso vamos a pasar nuestra función flecha y
handler in this case we're going to be passing our arrow function and
10:23:29
voy a decir como const.log y hacer clic así
i'll just say like const.log and click like so
10:23:32
y también voy a pasar el estado de desactivación así d-i-s-a-b-l-e-d y para el estado de desactivación voy a establecer eso en falso ahora que hemos proporcionado con éxito nuestra propiedad, tenemos que obtener esa propiedad dentro de nuestro componente.
and i'm going to also pass the disable state so d-i-s-a-b-l-e-d and for the disable state i'm going to set that to false now Now that we successfully provided our prop, we have to get that prop inside our component.
10:23:44
¿Entonces cómo puedes hacerlo? Y así es como vamos a consumir o acceder a esas propiedades. Usaré la propiedad.
So how can you go about doing that? And this is how we are going to be consuming or accessing that props. I'll use the prop.
10:23:51
Y aquí también tenemos que definir un tipo para eso. Así que solo usaré como etiqueta para la etiqueta. Eso va a ser una cadena.
And here we also have to define a type for that. So I'll just use like label for the label. That's going to be a string.
10:23:56
También vamos a pasar el manejador del evento on click. Eso va a ser una función.
We are going to be also passing the on click event handler. That's going to be a function.
10:24:00
Así que solo tenemos que proporcionar un void aquí porque no vamos a devolver nada de allí. Y también el estado deshabilitado.
So we have to just provide a void right here because we are not going to be returning anything from there. And also the disabled stat.
10:24:06
Y para el deshabilitado, va a haber un valor booleano. así que
And for the disabled, there's going to be a boolean value. so we
10:24:09
también tenemos que anotar eso ahora tenemos que usar el dentro de nuestro
also have to annotate that now we have to use the inside our
10:24:12
ui así que solo voy a quitar este botón y reemplazarlo con este
ui so i'll just remove this button and replace that with this
10:24:16
botón botón real aquí y aquí vamos a pasar
button actual button right here and here we're going to be passing
10:24:19
como prop punto nivel y también tenemos
like prop dot level and also we have
10:24:22
que proporcionar el manejador del evento on click y para el manejador del evento on click
to provide the on click event handler and for the on click event handler
10:24:25
vamos a usar como en on click así que vamos
we are going to be using like on on click like so we're
10:24:29
a pasar también el deshabilitar bien y eso va a ser igual
going to be also passing the disable okay and that's going to be equals
10:24:32
a esa prop punto deshabilitar así que voy a guardar mi archivo
to that prop dot disable so i'm going to to save my file
10:24:35
abrir mi terminal y usar npm run dev así que
open my terminal and use npm run dev so
10:24:38
se va a ejecutar eso dentro de mi navegador así que eso es genial y todo
it's going to run that inside my browser so that's cool and everything
10:24:42
como estamos obteniendo nuestro botón no estamos obteniendo ningún error aquí pero
like we are getting our button we're not getting any errors right here but
10:24:45
también podemos refactorizar este código para usar desestructuración así que solo voy a quitar
we can also refactor this code to user destructuring so i'll just remove
10:24:48
estas propiedades y voy a escribir como etiqueta y manejador del evento on click y también el estado deshabilitado ya no tenemos que proporcionar estas propiedades y puntos solo seleccionaré uno y presionaré ctrl d ctrl d
these props and i'm going to write like label and on click event handler and also the disable start we no longer have to provide these props and dots i'll just select one and hit ctrl d ctrl d
10:24:59
y eliminarlas. Ahora déjame guardar mi archivo y así es como se ve mi código y sí, podemos hacer clic en nuestro botón y nos va a dar como algo dentro de nuestra consola como puedes ver.
and remove them. Now let me just save my file and this is how my code looks like and yeah we can click on our button and it's going to give us like something inside our console as you can see.
10:25:10
Bienvenido al desafío de tipado de propiedades reutilizables con react.js y typescript.
Welcome to the reusable prop typing with react.js and typescript challenge.
10:25:14
Así que lo primero que quiero que hagas es que quiero que crees un archivo con el nombre de types.ts dentro del directorio src.
So the first thing that I want you to do is that I want you to create a file with the name of types.ts inside the src directory.
10:25:20
Luego define el tipo de info y extiende la lista de info de administrador dentro del archivo types.ts. Entonces, ¿qué es el tipo de info?
Then define the info type and extend the admin info list inside the types.ts file. So what is the info type?
10:25:27
Este tipo representa la mejor información compartida por todos los usuarios.
This type represents the best information shared by all users.
10:25:30
Incluye propiedades esenciales como ID, nombre y correo electrónico sobre un usuario específico.
It includes essential properties like ID, name, and email about a specific user.
10:25:35
Y sí, esa va a ser la primera parte de este desafío. Y en la siguiente parte, tendrás que crear un componente con el nombre de información del usuario.
And yeah, that's going to be the first portion of this challenge. And in the next portion, you're going to have to create a component with the name of user info.
10:25:42
Y ese componente mostrará la información del usuario basada en el tipo de información.
And that component will display the user information based on the info type.
10:25:47
Luego crea un componente de información de administrador, y ese mostrará la información del usuario y detalles adicionales de administrador basados en la información de administrador.
Then create an admin info component, and that will display the user information and additional admin detail based on the admin info
10:25:54
tipo de lista está bien y finalmente tienes que importar todo
list type okay and finally you have to import all of
10:25:57
dentro del archivo ab.tsx y solo ver si
them inside the ab.tsx file and just see like if
10:26:00
tienes algún tipo de error o no, así que hazlo lo mejor que puedas si puedes
you got some sort of error or not so give it your best shot if you can
10:26:03
hacerlo está completamente bien, luego regresa y mira la solución y
do it that's completely okay then come back and watch the solution and
10:26:07
ahora déjame darte mi solución, así que voy a quitar eso y crear
now let me just give you my solution so i'm going to remove that and create
10:26:10
primero que nada mi componente user info.tsx
first of all my component user info.tsx
10:26:13
y también admin info.tsx, así que solo crearé
and also admin info.tsx so i'll just create
10:26:16
como rafc dentro de este y también el rafc dentro del componente de información de administrador, ahora déjame ir
like rafc inside this one and also the rafc inside the admin info component now let me go
10:26:23
adelante e ir a mi aplicación y registrar ambos componentes
ahead and go to my app and register both of that component right
10:26:26
aquí, así que usaré como información del usuario y agarrar
here so i'll use like user info and grab
10:26:29
ahí, también voy a usar la información del administrador y también
there i'm going to also use the admin info and also
10:26:32
agarrar ahí, ahora déjame crear algún tipo de datos para
grab there right here now let me create some sort of a data so
10:26:36
lo que voy a hacer es que voy a crear mi usuario y ese usuario
what i'm going to do is that i'm going to create my user and that user
10:26:39
tendrá el id y eso se establecerá en uno y
will have the id and that's going to be set to like one and
10:26:42
también tendrá el nombre que será como no sé, john doe
also have the name which will be like i don't know john doe
10:26:45
y también el correo electrónico se establecerá en john
and also the email will be set to john
10:26:49
en gmail.com, así que eso será solo para un
at gmail.com so that's going be just for a
10:26:52
usuario normal, también vamos a crear uno para el administrador
normal user we're going to be also creating one for the admin
10:26:55
y el administrador tendrá el id de dos y también el
and the admin will have the id of two and also the
10:26:58
nombre se establecerá en jenny smith o algo así y
name will be set to jenny smith or something and
10:27:01
también vamos a proporcionar un correo electrónico y esto puede ser
also we're going to be providing an email and this can be
10:27:04
configurado como jenny en gmail.com está bien y
set to jenny at gmail.com okay and
10:27:08
ahora vamos a proporcionar un rol y el rol se establecerá como admin
now we are going to be providing a role and the role will be set to admin
10:27:11
vamos admin así y también vamos a proporcionar el último inicio de sesión así que solo usaré como nueva fecha y nos dará el último inicio de sesión
come on admin like so and we are going to be also providing the last login so i'll just use like new date and it's going to give us the last login
10:27:20
ahora aquí puedes ver que hemos definido nuestros datos y ahora vamos a
now here you can see we've defined our data and now we're going to be
10:27:23
pasar esos datos pero también tenemos que crear un tipo para
passing that data but we also have to create a type for
10:27:26
estos datos así que ¿cómo puedes hacerlo? Te voy a mostrar
this data so how can you go about doing that i'm going to show
10:27:29
cómo podemos hacer eso pero ahora déjame pegar estos datos como una propiedad así que
you how we can do that but now let me just paste this data as a prop so
10:27:33
solo escribiré como usuario y usuario y también voy a especificar
i'll just write like user and user and i'm going to also specify
10:27:36
el admin y que se establecerá en estos datos de admin está bien
the admin and which will be set to this admin data okay
10:27:39
así que ahora déjame proceder a crear mis tipos justo aquí dentro de esta carpeta src así que solo crearé como tipo o types.ts y aquí vamos a definir nuestros tipos como déjame mostrarte
so now let me go ahead and create my types right here inside this src folder so i'll just create like type or types.ts and here we're going to be defining our types like let me just show you
10:27:50
todo eso así que el id ahora se establece en uno así que
all of that like so the id is now set to one so
10:27:53
primero voy a definir como tipo de info y
first of all i'm going to just define like type of info and
10:27:57
este va a ser un tipo así que el id ahora se establece en número así que vamos a proporcionar
this is going to be a type so the id is now set to number so we are going to be providing
10:28:00
un número y además, vamos, olvidé incluir el
a number and also come on i forgot to include the
10:28:03
signo igual pensé que solo estaba creando algún tipo de objeto
equal to sign i thought i was just creating some sort of object
10:28:06
de todos modos, así que el nombre se establece en una cadena también el
anyway so the name is set to a string also the
10:28:09
correo electrónico se establece en cadena está bien, ahora debajo de eso también vamos a definir otro tipo que será la información del admin
email is set to string okay now underneath there we are going to be also defining another type which will be the admin info
10:28:16
tipo de lista y eso va a venir de la info como queremos cada cosa que la info
list type and that's going to be coming from the info like we want every single thing that the info
10:28:21
tenga y también queremos adjuntar esto
have and we also want to attach this
10:28:24
nuevo así que para el rol aquí puedes ver que ya obtenemos
new one so for the role here you can see we already get
10:28:27
todos sus datos o todos sus tipos de esto
all of their data or all of their types from this
10:28:30
info y ahora quieres adjuntar el rol y también el último inicio de sesión un
info and now you want to attach the role and also the last login a
10:28:34
rol se establecerá en cadena y el último inicio de sesión será
role will be set to string and the last login will be
10:28:37
establecido en fecha está bien y finalmente tenemos que exportar esto así que
set to date okay and finally we have to export this so
10:28:40
podemos usar el interior de nuestro archivo, así que solo lo exportaré allí, pero
we can use the inside of our file so i'll just export there but
10:28:43
tenemos que decirle explícitamente que este es un tipo, así que solo usaré
we have to explicitly tell it like this is a type so i'll just use
10:28:46
como información y tipo de lista de administradores
like info and type of admin list
10:28:49
información aquí, está bien, así que ahora que hemos creado con éxito allí
info right here okay so now that we successfully created there
10:28:52
también los exportamos, pero ahora tenemos que usar el interior de
we also exported them but now we have to use the inside of
10:28:55
nuestro archivo, está bien, así que para usarlos voy a agarrar primero de
our file okay so to use them i'm gonna grab first of
10:28:59
toda mi información y también la lista de administradores
all my info and also the admin list
10:29:03
o lista de información de administradores, para ser precisos, y también tenemos que anotar esta lista o este usuario con nuestro tipo, así que solo usaré como
or admin info list to be precise and we also have to annotate this list or this user with our type so i'll just use like info and i'm going to also provide my admin right here so i'll use like
10:29:15
lista de administradores o lista de información de administradores aquí, está bien
admin list or admin info list right here okay
10:29:19
así que ahora eso está totalmente hecho, ahora déjame ir a mi componente
so now that's totally done now let me just go ahead and go to my component
10:29:22
y agarrar todos sus datos, déjame acercar un poco y el
and grab all of their data let me just zoom in a bit and the
10:29:25
primera cosa que quiero hacer es que quiero agarrar mi información
first thing that i want to do is that i want to grab my info
10:29:28
de mi archivo de tipos y aquí vamos a definir nuestro
from my types file and here we're going to be defining our
10:29:31
propio tipo, así que solo usaré como tipo, um, la propiedad de información del usuario estará bien y eso va a ser
own type so i'll just use like type um user info prop will be fine and that's going to be
10:29:38
igual al usuario y para el usuario vamos a definir
equal to the user and for the user we are going to be defining
10:29:41
todo su tipo, así que solo usaré como la forma anterior de proporcionar
all of their type so i'll just use like the older way of providing
10:29:44
una propiedad, así que usaré como react, déjame conseguir eso y
a prop so i'll use like react let me just get that and
10:29:47
voy a usar como fc4 componente funcional y aquí vamos
i'm going to use like fc4 functional component and here we're
10:29:50
a proporcionar qué propiedad de información del usuario y voy a cerrar eso
going to be providing what user info prop and i'm going to close that
10:29:53
también voy a desestructurar al usuario, como todos los datos
i'm going to also destructure the user like all of the data
10:29:56
que ahora estamos proporcionando para este usuario y tenemos que
which we are now providing for this user and we have to
10:29:59
renderizar eso dentro de este componente, así que usaré como h2
render that inside this component so i'll use like h2
10:30:03
que dirá como información del usuario o la información sería
which will say like user info or information would be
10:30:07
bien y debajo de eso vamos a crear nuestro id que
fine and underneath that we're going to be creating our id which
10:30:10
simplemente nos dará como user.id y voy a duplicar
will just give us like user dot id and i'm going to duplicate
10:30:13
eso unas cuantas veces para que tengamos un nombre y también tengamos la dirección de correo electrónico, así que voy a cambiar este valor a nombre y también cambiar este id a correo electrónico
that a few times so we have a name and we also have the email address so i'm going to just change this value to like name and also change this id to email
10:30:22
y eso va a estar bien, haremos exactamente lo mismo para
and that's going to be fine we'll be doing exactly the same thing for
10:30:25
el componente de información del administrador, así que lo que voy a hacer es
the admin info component so what i'm going to do is
10:30:28
primero voy a obtener mi información del administrador
that first of all i'm going to grab my admin info
10:30:31
lista, así que una vez que las obtengamos, voy a crear mi
list okay so once we grab them i'm going to create my
10:30:34
tipo de propiedades de información del administrador y aquí
type of admin info props and here
10:30:38
vamos a estar usando como para el administrador, vamos a estar proporcionando como
we're going to be using like for the admin we're going to be providing like
10:30:41
lista de información del administrador como esta aquí, vamos a colocarla aquí, ahora también voy a usar mi react, así que solo usaré como react
admin info list like this one right here we're going to be placing there here okay now i'm going to also use my react so i'll just use like react
10:30:52
.fc para el componente funcional y voy a proporcionar mi
dot fc for the functional component and i'm going to provide my
10:30:55
lista de información del administrador aquí, también va a tomar el
admin info list right here it's going to also take the
10:30:58
perímetro o no un perímetro, sino la propiedad del administrador
perimeter or not a perimeter but the prop of admin
10:31:01
así que tenemos que tomar eso y tenemos que usarlo dentro de nuestro
so we have to take that and we have to use that inside our
10:31:04
componente, así que voy a eliminarlos y usaré como h2 de información del administrador así y proporcionar un párrafo con el id de admin.id
component so i'm going to remove them and i'll use like h2 of admin information like so and provide a paragraph with the id of admin.id
10:31:16
y solo duplicar eso unas cuantas veces al nombre
and just duplicate that a few times to the name
10:31:19
y también correo electrónico y también
and also email and also
10:31:22
el rol y finalmente tenemos que reemplazar eso
the role and finally we have to just replace that
10:31:26
con oh, sabes qué, sí, tenemos que escribir como admin.last
with oh you know what yeah we have to write like admin dot last
10:31:29
inicio de sesión y a partir de ahí vamos a obtener como dos locales
login and from there we are going to be getting like two locale
10:31:32
cadena, está bien y voy a ejecutar allí en lugar de proporcionar el id, solo voy a cambiar eso a un nombre y también voy a
string okay and i'm going to execute there instead of providing the id i'm going to just change that to a name and i'm going to also
10:31:39
proporcionar el correo electrónico aquí y también el rol
provide the email here and also the role
10:31:42
y finalmente vamos a obtener el último inicio de sesión
and finally we are going to be getting the last login
10:31:45
así que no sé por qué estamos obteniendo este error, no
like so i don't know why we are getting this error does
10:31:50
existe en qué tipo, déjame solo agarrar allí
not exist on what type let me just grab there
10:31:53
y poner este aquí, ahora han desaparecido con éxito
and put this one right here now they're successfully gone
10:31:56
y esto debería ser una cadena local ahora
and this should be locale string now
10:31:59
déjame guardar mi archivo y revisar esto, así que aquí puedes ver que ahora estamos
let me save my file and check this out so here you can see we are now
10:32:02
obteniendo la información del usuario y también estamos obteniendo la
getting the user information and we are also getting the
10:32:05
información del administrador y cada vez que envío mi archivo va
admin information and anytime i send my file it's going going
10:32:08
a darnos un segundo diferente aquí, lo cual es genial, pero ahora
to give us a different second right here which is cool but now
10:32:12
ya no estamos recibiendo errores y ahora estamos proporcionando
we are no longer getting any errors and we are now successfully
10:32:15
nuestros tipos para cada una de las propiedades del componente, está bien
providing our types for each of the component prop okay
10:32:19
así que ahora hablemos sobre el tipo reutilizable, así que para mostrarte allí
so now let's talk about the reusable type so to show you there
10:32:22
primero voy a crear mi carpeta de componentes y tendríamos
first of all i'm going to be creating my components folder and we would
10:32:25
algo como user info.tsx y
have like user info.tsx and
10:32:28
también voy a crear otro componente que será para el admin info.tsx y voy a entrar en mi componente de app, pero primero de
i'm going to also create yet another component which will be for the admin info.tsx and i'm going to go into my app component but first of
10:32:35
tenemos que escribir qué rfc dentro de este componente y
we have to write what rfc inside this component and
10:32:38
también dentro de este componente, también voy a
also inside this component as well i'm going to
10:32:41
entrar en mi componente de app y primero voy a importar mi usuario
go into my app component and first of all i'm going to be importing my user
10:32:44
componente de información y vender allí y también voy a
info component and sell there and i'm going to also
10:32:47
importar mi componente de información del administrador y vender allí como
import my admin info component and sell there as
10:32:51
bueno, solo pondré un poco de etiqueta aquí como h1 y
well i'll just put a bit of label right here like h1 and
10:32:54
información del usuario y luego voy a seleccionar esto hacia abajo
user info and then i'm going to select this down hand
10:32:58
y también voy a copiar eso y ahora déjame colocarlo aquí
and i'm going to also copy that and now let me just place it here
10:33:01
y cambiemos este a la información del administrador
and let's just change this one to the admin info
10:33:04
así que voy a guardar este archivo y como puedes ver aquí primero
so i'm going to save this file and as you can see right here first
10:33:07
tenemos nuestro componente de información del usuario y luego tenemos nuestro administrador
of all we have our user info component and then we have our admin
10:33:10
componente de información aquí, así que ahora voy a pasar un poco de prop
info component right here so now i'm going to pass a bit of prop
10:33:13
a él, así que solo usaré algo como nombre de usuario y el nombre de usuario será
to it so i'll just use like username and username will be
10:33:16
alex, solo escribimos alex aquí y vamos a
alex we just write alex right here and we are going to
10:33:20
también especificar el correo electrónico como alex@gmail.com y
be also specifying the email like alex at gmail.com and
10:33:24
también voy a poner el borde y h se establecerá en 20 y
i'm going to also put the edge and h will be set to 20 and
10:33:27
también voy a poner una ubicación y la ubicación será no sé, tierra
i'm going to also put a location and location will be i don't know earth
10:33:30
y también estados unidos, voy a
and also united state i'm going to
10:33:33
guardar este archivo y ahora voy a copiar cada cosa de
save this file and now i'm going to copy every single thing from
10:33:36
este componente, déjame colocarlo aquí en el componente de administración
this component let me just place it right here to the admin component
10:33:40
también, así que estamos proporcionando un nombre de alex, también estamos proporcionando un correo electrónico
as well so we are providing a name of alex we are also providing an email
10:33:43
edad y también la ubicación, sabes, déjame solo
age and also the location you know let me just
10:33:46
cambiar esta ubicación a algo más como marte o algo así y
change this location to something else like mars or something and
10:33:50
desconocido y también voy a proporcionar la propiedad de administrador y esto será totalmente único
unknown and i'm going to also provide the admin property and this will be a totally unique
10:33:55
propiedad como este componente no tiene la prop
property like this component does not have the prop
10:33:59
de administrador y este componente tiene la prop
of admin and this component has the prop
10:34:02
de administrador aquí, así que lo que voy a hacer es que
of admin right here okay so what i'm going to do is that
10:34:05
voy a entrar en mi componente de información de usuario aquí y primero de
i'm going to go into my user info component right here and first of
10:34:08
todo quiero crear mi información, así que solo escribiré como tipo de información que
all i want to create my info so i'll just write like type of info you
10:34:12
puedes crear una interfaz si quisieras, así que tomará como un nombre de usuario
can create interface if you wanted to so it's going to take like a username
10:34:15
y el nombre de usuario será una cadena, también vamos a proporcionar un
and username will be a string we're going to be also providing an
10:34:18
correo electrónico y el correo electrónico será una cadena también, esto proporciona un borde y el borde será un número y proporciona una ubicación y la ubicación será un
email and email will be a string as well this is provide an edge and edge will be a number and provide a location and location will be a
10:34:25
arreglo de cadenas, así que ahora tenemos que usarlo dentro de nuestro componente de usuario
string of array so now we have to use the inside our user component
10:34:28
primero voy a desestructurar mi nombre de usuario y luego el correo electrónico
i'll first of all destructure my username then email
10:34:32
y luego la edad y también la ubicación y anotaremos
and then age and also the location and we will annotate
10:34:35
ahí con este componente de información, no un componente, sino un tipo
there with this info component not a component but a type
10:34:38
ahora, si digo mi archivo, dirá que tenemos que usar
now if i say my file it's going to say that we have to use
10:34:41
todas estas props dentro de nuestros componentes, así que para hacer eso, voy
all of these props inside our components so to do that i'm
10:34:45
a cambiar este div a ul y ahora dentro de este ul vamos a definir algunos li's como li para el nombre de usuario y también vamos a
going to change this div to the ul and now inside this ul we're going to be defining a few li's like li for the username and also let's just
10:34:53
duplicar eso algunas veces para el correo electrónico y también para la edad.
duplicate there a few times for the email and also for the age.
10:34:58
Y voy a usar mi json.stringify
And I'm going to use my json.stringify
10:35:01
para que podamos ver el valor de esta ubicación, así que solo proporcionaré como
so we can see the value of this location so i'll just provide like
10:35:04
ubicación y ahora voy a guardar mi archivo y estoy recibiendo
location and now i'm going to save my file and i'm getting
10:35:07
algún tipo de error l-o-c-a-t-i-o-n-c-a-t-i-o
some sort of error l-o-c-a-t-i-o-n-c-a-t-i-o
10:35:11
y ahí vamos, así que ahora, si guardo mi archivo, estamos obteniendo todos esos datos que se ven increíbles. Básicamente voy a copiar cada cosa de este componente, ahora déjame colocar eso dentro de este componente aquí, guarda mi archivo
and there we go so now if i save my file we are getting all of that data which is looking amazing i'm going to basically copy every single thing from this component now let me just place that inside this component right here save my file
10:35:23
ahora también tenemos que reestructurar el nombre de usuario, el correo electrónico y también el borde
now we also have to restructure the username email and also the edge
10:35:26
copia allí y colócala aquí, así que
copy there and place there right here so
10:35:30
ahora voy a copiar esta información, vamos a entrar en nuestro componente de administración y
now i'm going to copy this info we're going to go into our admin component and
10:35:33
ahora déjame colocar eso aquí y en su lugar voy a cambiar eso a un
now let me just place that here and instead i'm going to change that to a
10:35:37
info como para la información del componente de administración, voy a copiar
info like for the admin component info i'm going to copy
10:35:40
ahí y ahora déjame colocarlo y como puedes ver aquí no estamos
there and now let me place it and as you can see right here we are not
10:35:43
obteniendo errores, pero si entro en mi componente app.tsx
getting any errors but if i go into my app.tsx component
10:35:46
aquí puedes ver que estamos obteniendo este error como este admin
here you can see we are getting this error like this admin
10:35:49
no está definido, así que si sigo adelante y voy a mi
is not defined so if i go ahead and go to my
10:35:52
componente de administración y si solo uso como escribir una coma
admin component and if i just use like write a comma
10:35:55
y poner mi admin aquí, guarda mi archivo, ahora se va a quejar
and put my admin right here save my file now it's going to complain
10:35:59
como huzain, tienes que registrarte allí dentro de tu a
like huzain you have to register there inside your a
10:36:02
tipo de información, así que para hacer eso voy a usar como admin y
info type so to do that i'm going to use like admin and
10:36:06
poner una cadena aquí, así que aquí puedes ver que ahora se ha
put a string right here so here you can see that it is now successfully
10:36:09
ido, pero ¿notaste una cosa? Ahora estamos repitiendo
gone but did you notice one thing we are now repeating
10:36:12
nosotros mismos, estamos copiando este tipo y
ourselves we are copying this type and
10:36:15
ahora lo estamos colocando aquí justo porque
we are now placing there right here just because
10:36:18
de este admin y ¿por qué lo estamos haciendo?
of this one admin and why are we doing
10:36:21
ahí, eso es porque este admin es único
there that's because this admin is unique
10:36:25
para este componente, podemos usarlo aquí, así que si solo
to this component we can totally use it right here so if i just
10:36:28
copia allí y ahora puedo usar totalmente mi derecho de administrador
copy there and now i can totally use my admin right
10:36:31
aquí guarda mi archivo que está totalmente terminado y debido a este administrador
here save my file that's totally done and because of this admin
10:36:34
prop estamos copiando toda la cosa
prop we are now copying the entire thing
10:36:37
y ahora estamos colocando allí justo aquí, así que si no quieres
and we are now placing there right here so if you don't want
10:36:40
usar eso, así que para eso vamos a usar el componente reutilizable
to use that so for that we are going to be using the reusable component
10:36:44
dentro de TypeScript, así que ¿cómo vamos a hacer allí para
inside the typescript so how are we going to be doing there to
10:36:47
hacer eso? Voy a ir a la información de mis usuarios y solo
do that i'm going to go into my users info and i will just
10:36:50
proporcionar la exportación justo aquí, así que si solo pongo esto
provide the export right here so if i just put this
10:36:53
exportaciones, lo que significa que puedo usar este tipo en cualquier lugar que
exports which means like i can totally use this type anywhere i
10:36:56
quiero en cualquier componente que quiero, así que ahora si voy
want in any component i want okay so now if i go
10:37:00
adelante y voy a mi componente de administrador, puedo eliminar eso totalmente
ahead and go to my admin component i can totally remove that
10:37:03
y ahora puedo importar mi información justo aquí, así que si
and now i can import my info right here so if
10:37:06
presiono enter aquí, así que se va a importar eso de la información del usuario
i hit enter right here so it's going to import that from the user info
10:37:09
voy a copiar allí y ahora déjame colocar esto justo aquí, guarda mi
i'm going to copy there and now let me just place it right here save my
10:37:12
archivo una vez más, estamos recibiendo un error por este administrador
file once again we are getting an error for this admin
10:37:15
así que para solucionar eso, tenemos que definir otro tipo
so to fix that we have to define another type
10:37:18
así que solo usaré como lista de información de administrador y
so i'll just use like admin info list and
10:37:22
vamos a usar primero toda la información como todos
we are going to be using first of all the info like all
10:37:25
los props que ya están disponibles dentro
of the props which are already available inside
10:37:28
esta información, también queremos usar todos ellos y
this info we also want to use all of them and
10:37:31
vamos a proporcionar un y ahora tenemos que definir
we are going to be providing an and and now we have to define
10:37:34
nuestro nuevo, así que también queremos usar el administrador y
our new one so we also want to use the admin and
10:37:37
el administrador será una cadena, está bien, así que si copio allí y ahora
admin will be a string okay so if i copy there and now
10:37:40
déjame colocar esto aquí, vamos, déjame colocar
let me just place say right here come on let me just place
10:37:43
esto aquí, guarda mi archivo y como puedes ver aquí, esos
it right here save my file and as you can see right here those
10:37:46
los errores ahora han desaparecido con éxito, así que así es como vamos a definir
errors are now successfully gone so this is how we are going to be defining
10:37:50
el tipo para nuestra propiedad en un componente, solo tenemos que
the type for our prop in one component we just have
10:37:53
exportar, así que así es como vamos a importar allí y
to export there this is how we are going to be importing there and
10:37:56
ahora más tarde, si decidimos agregar más propiedades, así que
now later if we decide to add some more prop so
10:37:59
así es como vamos a adjuntar allí usando este operador final, ahora la última cosa que quiero mostrarte es que puedes especificar explícitamente un tipo
this is how we are going to be attaching there by using this end operator k now the final thing i want to show you is that you can explicitly type
10:38:07
aquí, lo que significa que ahora le estamos diciendo a nuestro
a type right here which means like we are now telling our
10:38:10
compilador de typescript que esto va a ser algún tipo de tipo, esto
typescript compiler like this is going to be some sort of a type this
10:38:13
no es un componente, esto no es algún tipo de datos disponibles dentro de un
is not a component this is not some sort of a data available inside a
10:38:16
otro archivo, estos son tipos, así que ahora le estamos diciendo
other file these are types so now we are telling
10:38:20
a nuestro compilador que estos son tipos, así que lo va a tratar
our compiler like these are types so it's going to treat
10:38:23
como un tipo, así que sí, eso fue
it as a type okay so yeah that was
10:38:26
el componente reutilizable y a continuación vamos a aprender sobre los tipos de estado de uso, así que ahora hablemos sobre cómo vamos a
the reusable component and next we're going to be learning about the use state types okay so now let's talk about how we are going to
10:38:33
estar usando nuestros tipos o utilizados aquí, así que para hacer eso voy a
be using our types or or used here so to do that i'm
10:38:36
crear mi carpeta de componentes y voy a definir
going to create my components folder and i'm going to define
10:38:39
mi contador punto j, no jsx, sino tsx aquí
my counter dot j not jsx but tsx right here
10:38:42
simplemente usemos nuestro rafce, guarda mi archivo y
let's just use our rafce save my file and
10:38:45
registra ese contador dentro de mi aplicación, así que solo usaré como contador
register that counter inside my app so i'll just use like counter
10:38:49
y ahora simplemente registremos allí, así que si guardo mi
and now let's just register there right here so if i save my
10:38:52
archivo y como puedes ver, ahora estamos obteniendo nuestro contador que se ve increíble, así que lo primero que quiero hacer es definir mi conteo, así que
file and as you can see we are now getting our counter which is looking amazing so the first thing that i want to do is that i want to define my count so
10:38:59
simplemente usa como const count y luego set
just use like const count and then set
10:39:02
count será igual a use state y vamos
count will be equals to the use state and we
10:39:05
a proporcionar el valor inicial de cero allí, así que
are going to be providing the initial value of zero to there okay so
10:39:08
no se está quejando, pero si quieres proporcionar un
it is not complaining but if you want to provide a
10:39:11
tipo para use state, así es como lo vamos a hacer
type forward use state this is how we are going to be doing
10:39:14
ahí, así que si paso el ratón por ahí y como puedes ver, justo
there so if i hover my mouse over to there and as you can see right
10:39:17
aquí esta es una función genérica que significa que podemos proporcionar más tipos a la vez y si ustedes no saben qué es una función genérica o qué son los genéricos, deberían
here this is a generic function which means like we can provide more types at once and if you guys don't know what a generic function is or generics are so you should
10:39:26
definitivamente ir y ver mi curso de typescript y allí
definitely go ahead and watch my typescript course and there i
10:39:30
explicaré los genéricos con más detalle, así que solo especificaré
explain generics in a more great detail so i'll just specify
10:39:33
el tipo de número aquí y aquí pueden ver
the type of number right here and here you can see
10:39:36
podemos especificar el número, podemos especificar la cadena
we can specify the number we can specify the string
10:39:39
podemos proporcionar como indefinido, podemos proporcionar nulo si
we can provide like undefined we can provide null if you
10:39:42
quieren, podemos proporcionar cualquier tipo, así que solo voy a especificar como número
want we can provide any kind of type so i'm going to just specify like number
10:39:46
y así es como vamos a definir un uso dentro de nuestro componente de typescript, está bien, así que ahora podemos usar eso, podemos hacer básicamente cualquier cosa que queramos hacer con esto, así que solo usaré como aplicación de contador
and this is how we're going to be defining a use that inside our typescript component okay so now we can totally use that we can do like basically anything we want to do with this so i'll just use like counter app
10:39:56
y dentro de ahí vamos a crear nuestro contador como un párrafo
and inside there we are going to be creating our account as a paragraph
10:40:00
y voy a especificar el conteo como un video debajo de eso
and i'm going to specify count as a video underneath that
10:40:03
vamos a crear nuestro botón que solo dirá incrementar y
we are going to be creating our button which will just say increment and
10:40:06
también vamos a crear un componente y déjame duplicar
also we are going to be creating a component and let me just duplicate
10:40:09
eso y cambiarlo a decrementar y solo proporcionemos un poco del clic en eso cuando alguien haga clic en eso, así que ¿qué tenemos que hacer en esta situación?
that and change that to decrement and let's just provide a bit of the on click on there when somebody clicks on there so what do we have to do in this situation
10:40:18
vamos a usar nuestro set count en
we're going to be using our set count in
10:40:21
el primer caso vamos a incrementar nuestro contador en uno y en el segundo caso vamos a decrementar nuestro contador en uno, así que ahora si yo
the first case we are going to be incrementing our counter by one and in the second case we are going to be decrementing our counter by one so now if i
10:40:29
mismo por archivo y como pueden ver aquí puedo incrementar mi
same by file and as you can see right here i can increment my
10:40:32
contador y también puedo decrementar mi contador, así que sí, esto
counter and i can also decrement my counter so yeah this
10:40:36
es cómo vamos a proporcionar un tipo para nuestro uso
is how we are going to be providing a type or our use
10:40:39
datos, bienvenidos al desafío de uso de datos con react.js y typescripts
data welcome to the use data challenge with react.js and type scripts
10:40:42
así que lo primero que tienes que hacer es que tienes que definir un estado
so the first thing that you have to do is that you have to define a state
10:40:45
variable usando el uso de datos y tipificarlo explícitamente, así que te recomendaría crear un componente contador usando el uso de datos y anotarlo allí con un número, está bien, así que si ni siquiera puedes hacer esto.
variable by using the use data and type that explicitly so i would recommend you to create a counter component by using the use data and annotate there with a number okay so if you can't even do this one.
10:40:55
No tienes que hacer el primer paso, para ser honesto. Ahora, para el segundo paso, tienes que crear un componente de perfil de usuario y luego dentro de ese componente de perfil,
You don't even have to do the first step to be honest. Now for the second step, you have to create a user profile component and then inside that profile component,
10:41:03
vas a definir tu estado usando el uso de estado que contendrá el objeto con la información del usuario y tipificarlo en consecuencia.
you're going to be defining your stat by using the use stat which will hold the object with the user information and type it accordingly.
10:41:10
Está bien, básicamente vas a crear algún tipo de objeto que tendrá como el nombre de usuario, edad y algún tipo de ubicación o algo así.
Okay, like basically you're going to be creating some sort of object which will have like the user name, age and some sort of location or something like that.
10:41:17
Puedes poner cualquier tipo de información del usuario si lo deseas.
You can put like basically any kind of user information if you wanted to.
10:41:20
A continuación, debes crear una lista de tareas.
Next, you have to create a to-do list.tsx define a
10:41:24
una variable de estado para el elemento de la lista de tareas y tipificarla en consecuencia.
state variable for the to-do list item and type that accordingly so
10:41:27
dale tu mejor esfuerzo, si puedes hacerlo, está completamente bien, luego regresa
give it your best shot if you can do it that's completely okay then come
10:41:30
y mira la solución y ahora déjame darte mi solución.
back and watch the solution and now let me just give you my solution so
10:41:33
voy a crear un perfil de usuario, oh, sabes que no vamos a hacer
i'm going to create a user profile oh you know we're not going to do
10:41:36
eso, no ahora, primero déjame mostrarte
that not right now first of all let me just show you uh
10:41:39
el componente contador, así que solo crearé como const count
the counter component so i'll just create like const count
10:41:43
y luego establece count, vamos, establece
and then set count come on set
10:41:47
count así y eso va a ser igual a useState y el
count like so and that's going be equals to the use state and the
10:41:50
valor inicial será cero y ahora, si quieres anotar eso con el
initial value will be zero and now if you want to annotate that with the
10:41:53
número, así es como lo vamos a hacer, así que también podemos escribir
number so this is how we are going to be doing that so we can also just write
10:41:56
nuestro h1 y aquí vamos a definir nuestro contador o
our h1 and here we are going to be defining our counter or
10:41:59
contar con precisión y a continuación, tenemos que crear nuestro botón que
count to be precise and next we have to create our button which
10:42:02
nos permite incrementar nuestro contador, así que escribiré como on
allows us to increment our counter so i'll write like on
10:42:06
click y cuando alguien haga clic allí, vamos a activar esta función.
click and when somebody clicks on there we are going to be firing this function
10:42:09
así que solo usaré como const increment function y dentro de esta función vamos a usar setCount y proporcionemos nuestro
so i'll just use like const increment function and inside this function we are going to be using the set count and let's just provide our
10:42:16
anterior, sí, el conteo anterior estaría bien y
previous uh yeah previous count would be fine and
10:42:19
luego el conteo anterior más uno, así que ahora, si guardo mi archivo y
then previous count plus one so now if i save my file and
10:42:23
voy a usar mi npm run allí para ejecutarlo y aquí puedes
i'm going to use my npm run there to run there and here you can
10:42:26
ver que ahora estamos obteniendo nuestro contador, si hago clic en esto, simplemente va a
see we are now getting our counter if i click on this it's going to just
10:42:29
incrementar allí en uno, así que esa fue la parte fácil, ahora
increment there by one so that was the easy part now
10:42:32
también vamos a crear nuestro componente de usuario y vamos a estar tipeando allí, así que usaré como userProfile.tsx en este caso, déjame usar mi rafc dentro de allí.
we are going to be also creating our user component and we're going to be typing there so i'll use like user profile dot not jsx but tsx in this case let me just use my rafc inside there
10:42:43
ve al fondo y aquí vamos a estar renderizando o
go to the bottom and here we're going to be rendering or
10:42:47
un componente de perfil de usuario así y así es como se
a user profile component like so and this is how it
10:42:50
verá aquí, así que lo que voy a hacer es que primero voy a definir mi estado, así que usaré como useState y aquí.
will look like right here so what i'm going to do is that first of
10:42:53
todo, voy a definir mi estado, así que solo usaré useState y aquí
all i'm going to define my state so i'll just use like use state and here
10:42:56
vamos a pasar un objeto y, primero que nada, voy a pasar
we're going to be passing an object and first of all i'm going to pass
10:42:59
como un nombre, también vamos a proporcionar un borde de cero y
like a name we're going to be also providing a edge of zero and
10:43:02
el correo electrónico se establecerá en una cadena vacía, está bien, así que solo lo anotaré
the email will be set to empty string okay so i'll just annotate
10:43:05
ahí con la interfaz o también puedes crear el tipo si lo deseas
there with the interface or you can also create the type if you wanted to
10:43:08
así que solo crearé una interfaz y el nombre de la interfaz será
so i'll just create an interface and the interface name will be
10:43:12
perfil de usuario o sí, perfil de usuario
user profile or yeah user profile
10:43:15
estado o algo así, así que escribiré un nombre que será una cadena, yo
state or something so i'll write a name which will be a string i'll
10:43:18
también escribiré el borde que será un número y también el correo electrónico
also write the edge which will be a number and also the email
10:43:21
que será una cadena, está bien, así que voy a copiar este perfil de usuario
which will be a string okay so i'm going to copy this user profile
10:43:25
sabes, qué perfil de usuario, eh, estado
you know what user profile uh state
10:43:28
estará bien, así que voy a copiarlos y ahora déjame ponerlos allí correctamente
will be fine so i'm going to copy them and now let me put there right
10:43:31
aquí o anotar allí, aquí así
here or annotate there here like so
10:43:34
y lo que quiero hacer es que quiero crear mi perfil
and what i want to do is that i want to create my profile
10:43:38
y también establecer el perfil y va a ser igual
and also set profile and it's going to be equals
10:43:41
a esto usado aquí, a continuación, tenemos que usar allí, así que
to this used here next we have to use there so
10:43:44
voy a eliminar este perfil de usuario y solo escribiré como usuario
i'm going to remove this user profile and i will just write like user
10:43:47
perfil dentro del h2 y también voy a
profile inside the h2 and i'm going to also
10:43:50
escribir el campo de entrada y dentro de este campo de entrada, eh, el
write the input field and inside this input field uh the
10:43:53
tipo se establecerá en texto y también proporcionaré el marcador de posición de nombre
type will be set to text and i'm going to also provide the placeholder of name
10:43:56
hoy y el valor se establecerá en perfil
today and the value will be set to profile
10:43:59
punto nombre y también proporcionaré el controlador de eventos onChange
dot name and i'm going to also provide the on change
10:44:02
controlador de eventos cuando alguien cambie algo o escriba algo
event handler when somebody change something or type something
10:44:05
dentro de estos campos de entrada vamos a activar esta función
inside this input fields we are going to be firing this function
10:44:09
que dirá como actualizar nombre, esta es la función que
which will say like update name this is the function which
10:44:12
vamos a crear en unos segundos y va a tomar el evento punto
we are going to be creating in a few seconds and it's going to take the event dot
10:44:15
objetivo punto valor punto valor y va a pasar
target dot value dot value and it's going to pass
10:44:18
la para esta función y saben qué, solo voy a crear esto
the for this function and you know what i'm going to just create this
10:44:21
función de inmediato, así que sí, lo haré ahora mismo
function right away so yeah i'll just do that right now
10:44:24
usaré como const actualizar nombre, va a tomar el nombre y vamos a anotar allí con la cadena y dentro de allí vamos a usar un perfil establecido, va a tomar el perfil anterior
i'll use like const update name it's going to take the name and we will annotate there with the string and inside there we are going to be using a set profile it's going to take the previous profile
10:44:35
Y aquí solo tenemos que usar como, primero que nada, tenemos que copiar nuestro perfil anterior.
And here we just have to use like, first of all, we have to copy our previous profile.
10:44:41
Vamos, anterior, P-R-E-V-I-O-U-S o perfil de vista previa para ser precisos.
Come on, previous, P-R-E-V-I-O-U-S or preview profile to be precise.
10:44:46
Y también vamos a proporcionar un nuevo valor allí. Está bien. Así es como vamos a definir nuestro nombre de actualización.
And we're going to be also providing a new value to there. Okay. So this is how we're going to be defining our update name.
10:44:53
Y déjame ver. Así que si solo escribo algo, pero no puedo enviar esto, por eso no podemos ver allí.
And let me just see. So if I just type something, but I cannot submit this, that's why we cannot see there.
10:44:59
De todos modos, llegarás allí en unos segundos, también voy a
Anyways, you will get there in a few seconds i'm going to also
10:45:02
definir otro campo de entrada, así que usaré como entrada
define yet another input field so i'll use like input
10:45:06
con el tipo de número en este caso y aquí vamos a
with the type of number in this case and here we're
10:45:09
poner el marcador de posición de edad, también voy a poner el valor y de esta manera vamos a usar como perfil.edad es mayor que cero, si ese es el caso, vamos a obtener como perfil.edad
going to be putting the placeholder of edge to them i'm going to also put the value and for this way we are going to be using like profile.edge is greater than zero if that's the case we're going to be getting like profile.edge
10:45:21
pero si ese no es el caso, vamos a establecer allí como cadena vacía y también cuando alguien cambie o escriba algo dentro, vamos a activar esta función de actualización de edad
but if that's not the case we are going to be setting there to empty string and also when somebody change or type something inside there we are going to be firing this update age function
10:45:32
función de actualización de edad que vamos a crear en unos segundos y
update age function which we are going to be creating in a few seconds and
10:45:35
voy a pegar como evento punto objetivo punto valor dentro de allí y
i'm going to paste like event dot target dot value inside there and
10:45:38
ahora debajo de este campo de entrada vamos a definir otro
now underneath this input field we're going to be defining yet another
10:45:42
campo de entrada, así que usaré como entrada y el tipo será
input field so i'll use like input and the type will be
10:45:45
establecido en correo electrónico, también vamos a pasar el valor y
set to email we are going to be also passing the value and
10:45:48
el valor vendrá de perfil punto correo electrónico y
value will be coming from the profile dot email and
10:45:51
cuando alguien escriba algo dentro de allí, vamos a activar el evento
when somebody types something inside there we're going to be firing the event
10:45:54
objeto y crear esta función de actualización de correo electrónico en
object and creating this update email function in
10:45:57
unos segundos y usaré como evento objetivo punto valor
a few seconds and i'll use like event target dot value
10:46:01
finalmente tenemos que renderizar nuestro contenido, así que usaré como h3 y aquí vamos a escribir como resumen del perfil y debajo de ellos vamos a crear nuestro párrafo y primero que nada déjame renderizar mi
finally we have to render our content so i'll use like h3 and here we're going to be writing like profile summary and underneath them we're going to be creating our paragraph and first of all let me just render my
10:46:12
perfil.nombre y voy a duplicar eso como tres veces
profile.name and i'm going to duplicate the like three times
10:46:15
así que tenemos un perfil.edge y también perfil.email
so we have a profile.edge and also profile.email
10:46:19
bien, así que solo cambiemos eso a edge y cambiemos este a
okay so let's just change there to edge and change this one
10:46:22
email y sí, supongo que eso va a ser
to email and yeah i guess that's going to be
10:46:26
bien, pero también tenemos que crear este update edge y
fine but we also have to create this update edge and
10:46:29
también el update email, así que voy a crear eso aquí mismo
also the update email so i'm going to just create there right here
10:46:32
una vez que el update edge tome edge como
once update edge is going to take edge as
10:46:35
un perímetro y solo lo anotaremos como una cadena, está bien
a perimeter and we we will just annotate that as a string okay
10:46:38
así que ahora dentro de eso, uh, vamos a
so now inside there uh we are going
10:46:41
estar usando como set profile y aquí tenemos que proporcionar nuestro anterior
to be using like set profile and here we have to provide our previous
10:46:44
perfil y dentro de eso vamos a estar primero
profile and inside there we are going to be first
10:46:48
clonando nuestro anterior, vamos, perfil anterior
of all cloning our previous come on previous profile
10:46:51
y luego solo tenemos que proporcionar un nuevo valor para eso, está bien
and then we have to just provide a new value to that okay
10:46:54
así que vamos a pasar un edge y ahora queremos
so we are going to be passing an edge and now we want
10:46:57
que ese edge sea un número para que podamos convertir este edge a un número así usando este constructor de número o podemos
that edge to be a number so we can convert this edge to a number like so by using this number constructor or we can
10:47:05
simplemente escribir un más, así que también se convertirá en un número y
just write a plus so it's going to also convert there to a number and
10:47:08
ahora debajo de ellos también vamos a definir nuestro update email, así que
now underneath them we're going to be also defining our update email so
10:47:11
usaré como update email y va a tomar el email como
i'll use like update email and it's going to take the email as
10:47:14
un perímetro y va a haber una cadena, así que también
a perimeter and there's going to be a string so we also
10:47:17
tenemos que anotarlos y voy a usar como set profile y
have to annotate them and i'm going to use like set profile and
10:47:21
aquí una vez más tenemos que proporcionar nuestro perfil anterior y luego vamos a hacer un clon de eso usando punto punto punto perfil anterior, vamos, p-r-o-f-i-l-e
here we once again we have to provide our previous profile and then we're going to be making a clone of there by using dot dot dot previous profile come on p-r-o-f-i-l-e
10:47:30
y también voy a proporcionar el nuevo email para eso, está bien
and i'm going to also provide the new email to there okay
10:47:34
así que eso fue mucho
so that was a lot of
10:47:37
hablando, así que déjame ver aquí, puedes ver que tenemos nuestro usuario
talking so let me just see here you can see we have our user
10:47:40
perfil, no tenemos nada para el nombre para el
profile we don't have nothing for the name for the
10:47:43
edge, solo tenemos cero y para el email no tenemos nada
edge we have like only zero and for the email we don't have anything
10:47:47
así que si solo escribo mi propio nombre, se va a agregar allí
so if i just write like my own name and it's going to add there
10:47:50
aquí para este nombre también puedo cambiar el borde a
right here for this name i can also change the edge to
10:47:53
como 22 y también puedo proporcionar el correo electrónico como prueba
like 22 and i can also provide the email like test
10:47:56
en gmail.com se va a agregar allí justo aquí
at gmail.com it's going to add there right here
10:47:59
así que este va a ser mi resumen de perfil, así que eso está hecho
so this is going to be my profile summary so that's done
10:48:02
ahora es el momento de crear o hacer esta aplicación, así que
now it's time to create or to do this application so
10:48:05
voy a continuar y crear mi quehacer uh punto
i'm going to go ahead and create my to do uh dot
10:48:09
tsx o quehacer sí, la lista de quehaceres punto tsx estará bien, no sé qué demonios estoy pensando ahora mismo, así que vamos, oh Dios mío
tsx or to do come yeah to do list dot tsx will be fine i don't know what the hell am i thinking right now so let's oh my god
10:48:20
sabes que hacer estaría bien, así que quehacer punto tsx está bien y voy a escribir mi rafc dentro
you know what to do would be fine so to do dot tsx is fine and i'm going to write my rafc inside
10:48:26
ahí y voy a continuar e ir a mi aplicación y registrarme allí
there and i'm going to go ahead and go to my app and register there
10:48:29
justo aquí, así que solo escribamos sobre quehacer y registremos
right here so let's just write over to do and register
10:48:32
ahí y la primera cosa que quiero hacer es que quiero escribir como que
there and the first thing that i want to do is that i want to write like to
10:48:36
los quehaceres o sí, los quehaceres estarían bien y luego establecer
do's or yeah to do's would be fine and then set to
10:48:39
los quehaceres y eso va a ser igual a el estado de uso y el inicial
do's and that's going to be equals to the use state and the initial
10:48:42
el valor será solo un arreglo vacío, también voy a crear
value will be just empty array i'm going to also create
10:48:45
una interfaz para eso porque vamos a estar creando trabajos quehaceres
an interface for that because we're going to be creating work to do's
10:48:48
que tendrá una interfaz de quehacer, voy a proporcionar
which will have an interface off to do i'm going to provide
10:48:51
el id y el id será un número, también voy a proporcionar la tarea y
the id and id will be a number i'm going to also provide the task and
10:48:54
la tarea será una cadena y el completado será
the task will be a string and the completed will
10:48:57
establecido en booleano y ahora déjame obtener esta interfaz de quehacer y
be set to boolean and now let me get this to do interface and
10:49:01
tenemos que anotar qué estado hay allí, así que solo escribamos nuestro quehacer
we have to annotate what state to there so let's just write our to
10:49:04
y aquí tenemos que anotar allí así y
do and here we have to annotate there like so and
10:49:07
ahora déjame ir a la interfaz de usuario y cambiar esta interfaz de usuario, así que usaré como
now let me go to the ui and change this ui so i'll use like
10:49:10
h2 lista de quehaceres y debajo de allí
h2 to do list and underneath there
10:49:13
vamos a crear un botón que dirá como agregar a
we're going to be creating a button which will say like add to
10:49:16
haremos así y para este botón cuando alguien haga clic
do like so and for this button when somebody clicks
10:49:20
ahí vamos a estar ejecutando esta función así que simplemente usemos como
on there we are going to be firing this function so let's just use like
10:49:23
um agregar a hacer y
um add to do and
10:49:26
vamos a estar proporcionando maldita sea para hacer
we're going to be providing god damn it to do
10:49:29
y vamos a estar proporcionando un nuevo hacer dentro de ahí dej
and we're going to be providing a new to do inside there let
10:49:32
me crearé esta función de inmediato así que simplemente crearé eso ahora
me just create this function right away so i'll just create that right
10:49:35
aquí y sí, supongo que eso estará bien así que
here and yeah i guess that's going to be fine so
10:49:38
simplemente crearemos eso agregar a hacer y tomará una tarea
let's just create that add to do and it's going to take a task
10:49:42
como un perímetro y lo anotaremos como una cadena está bien así que dentro de ahí primero vamos a estar creando nuestro nuevo hacer y también voy a anotar la pestaña con este hacer y aquí eso va a ser igual a este objeto.
as a perimeter and we will annotate that as a string okay so inside there first of all we're going to be creating our new to do and i'm going to also to annotate tab with this to do and here that's going to be equals to this object.
10:49:53
Así que tomará el ID y el ID vendrá de la longitud de inicio de hacer más uno.
So it's going to take the ID and ID will be coming from to do start length plus one.
10:49:58
Así que eso va a ser básicamente mi id y también vamos a estar proporcionando
So that's going to be just basically my id and we're going to be also providing
10:50:02
una tarea que estamos tomando como un perímetro y vamos a estar proporcionando
a task which we are taking as a perimeter and we are going to be providing
10:50:05
ahí para esta función y también proporcionaré el completado y
there for this function and i'll also provide the completed and
10:50:08
eso se establecerá en falso, así como yo
that's going to be set to false just like i'm
10:50:12
tendré que proporcionar comas en lugar de proporcionar eso, lo que sea que fuera esto se proporciona establecido en hacer y finalmente hemos proporcionado un hacer anterior o sí, hacer
going to have to provide a commas instead of providing that whatever that was this is provided set to do's and finally we have provided a previous to do or to yeah to do's
10:50:21
refinar y aquí tenemos que simplemente hacer un clon de anterior
refine and here we have to just make a clone of previous
10:50:24
hacer así que simplemente escribamos nuestros pre-hacer y yo
to-dos so let's just write our pre-to-dos and i'm
10:50:27
voy a agregar mi nuevo hacer allí está bien así que
going to add my new to-do to there okay so
10:50:30
simplemente ocultemos este voy a ponerlo allí en
let's just hide this one i'm going to put there at
10:50:34
la parte superior vamos a estar renderizando nuestro hacer así que usaré como
the top we are going to be rendering our to-do so i'll use like
10:50:37
ul y voy a iterar sobre todos los hacer usando
ul and i'm going to iterate over through all of the to-dos by using
10:50:40
el mapa va a tomar nuestro hacer como un perímetro y dentro de ahí
the map it's going to take our to-do as a perimeter and inside there
10:50:43
vamos a estar usando nuestro li para renderizar cada hacer así que
we are going to be using our li to render over each to-do so
10:50:46
para cada uno de los hacer voy a escribir como hacer punto tarea y
for each of the to-do i'm going gonna write like to do dot task and
10:50:49
entonces voy a escribir como si está completado o no así que
then i'm gonna write like is it completed or not so
10:50:53
voy a usar eso para hacer que esté completado
i'm gonna use that to do dot completed completed
10:50:56
maldita sea, así que solo para hacer que esté completado si
god damn it so just to do dot completed if
10:50:59
ese es el caso, completado, si ese es el caso, vamos
that's the case completed if that's the case we're
10:51:03
a estar escribiendo como, eh, completado, pero si ese no es el caso, así que vamos a dejarlo como una cadena vacía, está bien, y también proporcionaré una clave
going to be just writing like uh completed but if that's not the case so we are going to be setting there to empty string okay and i will also provide a key
10:51:13
así que solo escribiré como hacer que el id sea una clave, estoy
so i'll just write like to do dot id as a key i'm
10:51:16
a guardar este archivo y finalmente déjame ir a mi app.tsx
going to save this file and finally let me go into my app.tsx
10:51:19
ya proporcionamos todo eso, así que probemos esto
we already provided all of that so let's just test this
10:51:22
así que aquí puedes ver que tenemos lo que agregar a hacer, voy a hacer clic en esto
out so here you can see we have what add to do i'm going to click on this
10:51:25
simplemente va a agregar una nueva tarea cada vez que haga clic en eso, así que
it's going to just add a new to do anytime i click on that so
10:51:29
sí, eso fue un ejemplo sobre
yeah that was uh what example about
10:51:32
el uso de hilos y aprendimos mucho sobre cómo podemos anotar lo que comienzas, así que eso fue todo sobre el ejemplo de cuenta y el ejemplo de perfil de usuario
the use thread and we learned a lot about how we can annotate what you start so that was it about for the account example for the user profile example
10:51:40
y también el ejemplo de lista de tareas, ahora vamos a cubrir tres temas a la vez, como usar referencias, formularios y eventos, como cómo vamos a proporcionar tipos para la referencia de usuario
and also the to-do list example as well now we are going to be covering three topics at once like use ref forms and events like how we are going to be providing up types for the user ref
10:51:52
formularios y también para los eventos, así que lo que voy a hacer es que voy a
forms and also for the events so what i'm going to do is that i'm going
10:51:55
crear mi carpeta de componentes dentro
to create my components folder inside
10:51:58
de esta carpeta de componentes, vamos a proporcionar nuestro form.tsx
this component folder we're going to be providing our form.tsx
10:52:03
y dentro de ahí voy a usar mi rfc, guardar mi archivo y también tenemos que registrar
and inside there i'm going to just use my rfc save my file and we also have to register
10:52:08
ahí dentro de nuestro componente de aplicación, así que solo usaré mi formulario
there inside our app component so i'll just use my form
10:52:11
y si presiono enter, va a tomar de ahí mis componentes
and if i hit enter so it's going to grab there from my components
10:52:14
carpeta, así que lo que voy a hacer es que primero voy a definir
folder so what i'm going to do is that first of all i'm going to define
10:52:17
mi estado, que será como enviado y
my state which will be like submitted and
10:52:21
también establecer datos enviados
also set submitted data
10:52:24
y vamos a almacenar eso dentro del use state y
and we're going to be storing there inside the use state and
10:52:27
para el valor inicial voy a especificar el nombre y el nombre se establecerá como una cadena vacía, también vamos a proporcionar un correo electrónico y el correo electrónico se establecerá como una cadena y también
for the initial value i'm going to specify the name and name will be set to empty string we're going to be also providing an email and email will be set to string and we also
10:52:35
tenemos una contraseña y la contraseña también será una cadena vacía
have a password and password will be also empty string
10:52:38
así que ahora podemos crear un tipo separado para todos ellos para
so now we can create a separate type for all of them to
10:52:42
para eso voy a estar usando un tipo y le voy a dar el nombre de como formulario
do that i'm going to be using a type and i'm going to give it the name of like form
10:52:45
y dentro de ahí vamos a estar definiendo un nombre que será una cadena, también voy a proporcionar el correo electrónico que será una cadena y también la contraseña que también será una cadena
data and inside there we are going to be defining a name which will be a string i'm going to also provide the email which will be a string and also the password which will be also a string
10:52:55
ok, así que voy a copiar estos datos justo aquí y ahora tenemos
okay so i'm going to copy this data right here and now we have
10:52:58
anotar o usar eso con estos datos, voy a estar usando mis datos de formulario y ahora simplemente anotemos o usemos eso con esos datos, así que
to annotate or use that with this data i'm going to be using my form data and now let's just annotate or use that with that data so
10:53:05
ahora eso está totalmente hecho, a continuación también vamos a estar usando el uso
now that's totally done next we are going to be also using the use
10:53:08
ref, así que solo usaré como const nombre y estamos
ref so i'll just use like const name and we are
10:53:11
a estar usando un uso ref para eso y si presiono enter
going to be using a use ref for that and if i hit enter
10:53:14
así que se va a importar automáticamente eso desde el react.js, no necesitamos el
so it's going to auto import that from the react.js we don't need the
10:53:17
reductor, así que digamos adiós a eso y el valor inicial será
reducer so let's say bye bye to that and the initial value will
10:53:21
establecido en nulo, ok y solo voy a duplicar eso un poco
be set to null okay and i'm going to just duplicate that a few
10:53:24
así que solo voy a cambiar el nombre de la variable a como correo electrónico y también a la contraseña, así que ahora tenemos que
times so i'm going to just change the variable name to like email and also to the password as well so now we have to
10:53:31
especificar un tipo específico para este uso ref, así que estamos
specify a specific type for this use ref so we are
10:53:34
a estar usando este uso ref dentro de nuestro formulario y
going to be using this use ref inside our form and
10:53:37
dentro de nuestro elemento de entrada html específico, así que
inside our specific html input element so
10:53:40
tenemos que decirle a nuestro uso ref que vamos a estar usando este nombre
we have to tell our use ref that we are going to be using this name
10:53:43
correo electrónico y contraseña dentro del elemento de entrada html
email and password inside the html input
10:53:47
ok, así que solo usaré como entrada html y si presiono enter y aquí puedes ver que vamos a estar usando nuestro tipo en la entrada html
element okay so i'll just use like html input and if i hit enter and here you can see we are going to be using our type on the html input
10:53:55
así que voy a copiar eso de aquí, déjame usar eso aquí
element so i'm going to copy that from here let me just use that here
10:53:58
y también aquí, ok, así que así es como vamos a
and also here okay so this is how we're going to
10:54:01
proporcionar un tipo para el uso ref y ahora simplemente usemos
be providing a type for the use ref and now let's just use
10:54:05
el componente de trabajo interno, así que lo que voy a hacer es que voy a simplemente
the inside work component so what i'm going to do is that i'm going to just uh
10:54:08
eliminar este trato y voy a cambiar eso con este formulario
remove this deal and i'm going to change that with this form
10:54:11
solo eliminaré este formulario de aquí y ahora voy a proporcionar mi
i'll just remove this form from here and now i'm going to provide my
10:54:14
campo de entrada y ese campo de entrada tomará el tipo de texto que vamos
input field and that input field will take the type of text we're
10:54:18
a estar proporcionando también un marcador de posición que dirá como ingresa tu nombre y también voy a estar definiendo mi ref, vamos
going to be also providing a placeholder which will say like enter your name and also i'm going to be defining my ref come on
10:54:25
mi ref y va a hacer referencia a este nombre
my ref and it's going to be referencing to this name
10:54:28
está bien, así que puedo duplicar eso unas cuantas veces
okay so i can totally duplicate that a few times i'm
10:54:31
voy a cambiar eso a correo electrónico y también a la contraseña
going to just change that to email and also to the password
10:54:34
también, así que también cambiaré estos a
as well okay so i'll also change these to
10:54:37
correo electrónico y también este a contraseña como
email and also this one to password as
10:54:41
bueno, así que si guardo mi archivo, eso es todo lo que tenemos que hacer para
well so if i save my file that's everything that we have to do for
10:54:44
ahora, pero también voy a crear un botón que dirá
now but i'm going to also create a button which will say
10:54:47
uh, enviar, está bien, y también vamos a proporcionar un tipo para eso y el tipo se establecerá en enviar ahora debajo
uh submit okay and we're going to be also providing a type for that and the type will be set to submit now underneath
10:54:54
ahí queremos mostrar nuestros datos, así que voy a escribir
there we want to show our data so i'm going to just write
10:54:57
una sección y ahora dentro de esta sección voy a escribir mi h1
a section and now inside this section i'm going to write my h1
10:55:00
que se establecerá en nombre y primero tenemos que obtener nuestro
which will be set to name and first of all we have to grab our
10:55:03
datos enviados y vamos a usar el
submitted data and we're going to be using the
10:55:06
propiedad punto nombre en el caso como puedes ver aquí
dot name property on the case as you can see right here
10:55:09
así que tenemos nuestros datos enviados y tenemos el nombre que
so we have our submitted data and we have the name we
10:55:12
también tenemos el correo electrónico y también la contraseña si quieres ver todos
also have the email and also the password if you want to see all
10:55:15
los datos, así que solo voy a duplicar eso como unas cuantas veces
of the data so i'm going to just duplicate there like a few time
10:55:18
tenemos que cambiar eso al correo electrónico y también cambiar esto
we have to change that to the email and also change this
10:55:21
uno a la contraseña también, así que solo así, solo voy a
one to the password as well just like this i'll just
10:55:25
cambiar este a el correo electrónico y también voy a cambiar este a
change this one to the email and i'm going to also change this one to
10:55:28
la contraseña, así que si guardo mi archivo y esto es todo lo que
the password so if i save my file and this is everything that we
10:55:31
tenemos que hacer para la interfaz de usuario, pero ahora vamos a adjuntar nuestro evento
have to do for the ui but now we are going to be attaching our event
10:55:34
en el formulario, así que cuando alguien envíe su formulario como
on the form so when somebody submit their form like
10:55:37
cuando alguien llene ese formulario y lo envíe, y si quieres
when somebody fill that form and submit there and if you want
10:55:40
proporcionar nuestra función de flecha justo aquí así
to provide our arrow function right here like this
10:55:43
no tenemos que especificar un tipo para eso, pero si tú
we don't have to specify a type for that but if you
10:55:47
quiero extraer toda esa lógica en una función separada así que
want to extract all of that logic into a separate function so
10:55:50
para eso tenemos que especificar algún tipo para eso así que
for that we have to specify some sort of a type for that so
10:55:53
simplemente usaré como manejar el envío y voy a copiar allí y
i'll just use like handle submit and i'm going to copy there and
10:55:56
simplemente creemos nuestro manejar el envío justo aquí, está bien, así que voy a estar usando como
let's just create our handle submit right here okay so i'm going to be using like
10:55:59
const manejar el envío, va a tomar el evento y
cons handle submit it's going to take the event and
10:56:03
como pueden ver aquí, ahora estamos obteniendo este error, así que para solucionar este error tenemos que decirle a nuestro typescript que estamos usando un evento de formulario como
as you can see right here we are now getting this error so to fix this error we have to tell our typescript that we are using a form event like we
10:56:12
estamos usando un evento en el formulario justo aquí
are using a event on the form right here
10:56:15
y también tenemos que decirle que vamos a estar ejecutando esto
and we also have to tell it that we are going to be firing this
10:56:18
función en el elemento de formulario HTML así
function on the HTML form element like this
10:56:21
uno, está bien, así que también tenemos que decirle allí que voy a estar usando
one okay so we also have to tell it there I'm going to be using
10:56:24
como elemento de formulario HTML y ahora si presiono enter
like HTML form element and now if I hit enter
10:56:27
así es como le vamos a estar diciendo a nuestro compilador que estamos
so this is how we are going to be telling our compiler that we are
10:56:30
vamos a estar ejecutando este evento en el evento del formulario y luego vamos a estar usando en el elemento de formulario HTML, está bien, así que solo puedo usar como evento punto
going to be firing this event on the form event and then we are going to be using the on the HTML form element okay so I can just use like event dot
10:56:39
prevenir el comportamiento predeterminado, así que solo va a prevenir nuestro comportamiento predeterminado y ahora solo puedo agarrar como
prevent default so it's going to just prevent our default behavior and now i can just grab like
10:56:44
constante valor del nombre, como lo que el usuario escribe
const name value like whatever user type
10:56:47
dentro de este campo de entrada justo aquí, como el campo de entrada del nombre
inside this input field right here like the name input field
10:56:50
así que lo que voy a hacer es que solo voy a usar como nombre y
so what i'm going to do is that i'm going to just use like name and
10:56:53
voy a estar obteniendo una propiedad actual esto debido a este nombre
i'm going to be getting a current property this because of this name
10:56:56
justo aquí que ahora está configurado a esta referencia y ahora si
right here which is now set to this reference and now if
10:57:00
simplemente uso el punto valor y qué estamos obteniendo, ahora estamos
i just use the dot value and what are we getting we are now
10:57:03
obteniendo un error si paso el mouse sobre allí, ahora está dando
getting an error if i hover my mouse over to there it is now giving
10:57:06
nos como nombre punto actual es posiblemente nulo, es
us like name dot current is possibly null it
10:57:09
nulo, no posiblemente porque ya
is null not possibly because we already
10:57:12
lo configuramos en nulo, así que ¿cómo puedo solucionar este error para solucionar
set that to null so how can i fix this error to fix
10:57:15
este error podemos usar el operador de inserción nula justo aquí
this error we can use the null insertion operator right here
10:57:19
lo cual ya cubrimos en mi curso de typescript si ustedes
which we already covered in my typescript course if you guys
10:57:22
no saben sobre esto, así que definitivamente pueden ver mi typescript
don't know about this so you can definitely watch my typescript
10:57:25
curso, pero si ustedes ya saben, está bien, así que básicamente ahora le estamos diciendo a nuestro compilador que no tiene que preocuparse
course but if you guys already know there that's cool so basically we are now telling our compiler like you don't have to worry
10:57:32
por este código, como que nunca puede ser nulo y nunca puede estar indefinido
about this code like it can never be null and it can never be undefined
10:57:35
le estamos diciendo esto a nuestro compilador como que no tienes que
we are now telling this to our compiler like you don't have
10:57:38
preocuparte por nuestro código, está bien, así que ahora voy a duplicar allí
to worry about our code okay so now i'm going to just duplicate there
10:57:42
como unas cuantas veces, tal vez dos veces más y voy
like a few time maybe two times more and i'm going
10:57:45
a cambiar el nombre de esta variable a un valor de email y
to change this variable name to like an email value and
10:57:48
también voy a cambiar este a un valor de contraseña también, está bien, así que podemos registrar eso en la consola o simplemente podemos enviarlo a nuestro DOM, así que usaré como establecer datos enviados
i'm going to also change this one to the password value as well okay so we can totally log that to the console or we can just submit it to our dom so i'll just use like set submitted data
10:58:00
y vamos a proporcionar nuestro objeto, simplemente proporcionemos un nombre y
and we are going to be providing our object let's just provide a name and
10:58:04
para el nombre vamos a proporcionar como un valor de nombre que es
for the name we are going to be providing like a name value which is
10:58:07
esta variable aquí, también voy a proporcionar una coma y
this variable right here i'm going to also provide a comma and
10:58:10
simplemente proporcionemos un email y eso va a ser el valor del email y
let's just provide an email and that's going to be the email value and
10:58:13
también para la contraseña vamos a usar la contraseña
also for the password we are going to be using the password
10:58:16
o el valor de contraseña, más bien
value or password value rather
10:58:20
así que si guardo mi archivo ahora, ya no tenemos errores aquí porque hemos tipado correctamente o hemos proporcionado tipos para todo y ahora aquí
so if i save my file now we no longer have any errors right here because we successfully type types or we successfully
10:58:27
puedes ver que ahora estamos obteniendo esta interfaz de usuario, así que cualquier cosa que escriba dentro
provided at types for everything and now here
10:58:30
de allí, como por ejemplo, si especifico mi nombre como zan y
you can see we are now getting this ui so anything i type inside
10:58:33
mi email será test y g, vamos test
there like for instance if i specify my name of zan and
10:58:37
y gmail.com y, eh, qué
my email will be test and g come on test
10:58:40
es esa contraseña, ingresa tu email, ingresa tu email y
and gmail.com and uh what
10:58:43
ingresa tu contraseña, ahí vamos, así que si guardo allí
is that password enter your email enter your email and
10:58:50
ahora puedo escribir como, eh, mi
enter your password there we go so if i save there
10:58:53
contraseña real y ahora si envío
now i can write like uh my
10:58:57
eso aquí, puedes ver, oh, estamos obteniendo hosin hosin hosin
real password and now if i submit
10:59:00
que aquí puedes ver oh estamos obteniendo hosin hosin hosin
that here you can see oh we are getting hosin hosin hosin
10:59:03
una vez más y estoy proporcionando una prueba y mi real
once again and i'm providing a test and my real
10:59:07
contraseña por qué es eso oh eso es porque estamos usando un nombre una y otra vez tenemos que cambiar eso al correo electrónico y también tenemos que cambiar eso a la
password why is that oh that's because we are using a name again and again we have to change that to the email and also we have to change that to the
10:59:15
contraseña aquí así que si guardo mi archivo ahora y si
password right here so if i save my file now and if i
10:59:18
envío allí ahora estamos obteniendo un nombre como hosain correo electrónico
submit there now we are getting a name as hosain email
10:59:22
como una prueba en gmail.com y contraseña mi real
as a test at gmail.com and password my real
10:59:25
contraseña aquí así que si solo actualizo allí y déjame
password right here so if i just refresh there and let me
10:59:28
escribir algo algo en gmail.com
type something something at gmail.com
10:59:31
y algo genial y ahora déjame hacer clic en
and something cool and now let me click on
10:59:35
este enviar y así es como vamos a obtener todos sus datos aquí mismo está bien así que así es como vamos a proporcionar un tipo o un aviso para el formulario y también para el evento y y también para el useRef.
this submit and this is how we are going to be getting all of their data right here okay so this is how we are going to be providing a types or a prompt for the form and also for the event and and also for the useRef.
10:59:47
Crea un archivo con el nombre de focusInput.tsx dentro de este directorio RCA y define un componente que use un useRef para enfocarse en el campo de entrada cuando se hace clic en el botón.
Create a file with the name of focusInput.tsx inside this RCA directory and define a component that use a useRef to focus on the input field when the button is clicked.
10:59:55
Escribe la referencia apropiadamente. Así que esa va a ser la primera parte. En la segunda parte,
Type the ref appropriately. So that's gonna be the first part. In the second part,
11:00:00
el nombre de contact form.tsx dentro del directorio src y
the name of contact form.tsx inside the src directory and
11:00:03
luego define un componente de formulario con el tipo de estado y formulario
then define a form component with the type of state and form
11:00:06
manejador después de eso crea un archivo con el nombre de evento
handler after that create a file with the name of event
11:00:09
manejando.tsx dentro del directorio src y define
handling.tsx inside the src directory and define
11:00:12
un componente que demuestra la escritura de diferentes manejadores de eventos así que dale
a component that demonstrates typing different event handlers so give
11:00:15
tu mejor intento si puedes hacerlo eso está completamente bien luego vuelve y mira la solución y ahora déjame darte mi solución así que lo que voy a hacer es que voy a definir mi
it your best shot if you can do it that's completely okay then come back and watch the solution and now let me give you my solution so what i'm going to do is that i'm going to define my
11:00:25
focus input.tsx voy a usar
focus input.tsx i'm going to use
11:00:28
mi rdfc dentro de allí ve a mi aplicación primero que todo vamos
my rdfc inside there go to my app first of all let's
11:00:31
a guardar allí y registrar mi enfoque
just save there and register my focus
11:00:34
oh maldita sea enfoque oh
oh god damn it focus oh
11:00:39
Dios mío enfoque si puedo escribirlo hoy así que
my god focus if i can type it today so
11:00:42
enfoque input aquí y si reviso esto así que aquí puedes ver que ahora estamos obteniendo más enfoque input que se ve genial y lo que voy a hacer es que voy a estar usando el use ref
focus input right here and if i check this out so here you can see we are now getting more focus input which is looking cool and what i'm going to do is that i'm going to be using the use ref
11:00:52
sin reducer use ref que
with not reducer use ref which
11:00:55
vendrá de react js y aquí vamos a
will be coming from the react js and here we are going to
11:00:58
proporcionar el valor inicial de nulo a ellos, comenzaré en
be providing the initial value of null to them i'll start in
11:01:01
la variable con el nombre de como input ref y eso va a ser igual
the variable with the name of like input ref and that's going to be equals
11:01:04
a este use ref y también los anotaremos con
to this use ref and we will also annotate them with
11:01:08
el elemento de entrada html que vendrá
the html input element which will be coming
11:01:11
del archivo de definición, así que si mantengo ctrl y hago clic allí y
from the definition file so if i hold ctrl and click on there and
11:01:14
aquí puedes ver que ahora podemos obtener todo eso, um qué
here you can see we can now get like all of that um what
11:01:17
llamamos a sus tipos desde typescript, así que sí, eso es
do we call it their types from the typescript so yeah that's
11:01:21
lo primero, ahora siguiente tenemos que usar esto, así que solo escribiré
the first thing now next we have to use this so i'll just write
11:01:24
como campo de entrada con el tipo de texto y también voy a escribir
like input field with the type of text and i'm going to also write
11:01:27
la referencia y solo la referenciamos a la entrada ref, déjame definir mi marcador de posición que dirá como, uh, haz clic en el botón para enfocar
the ref and we will just reference that to the input ref let me define my placeholder which will say like uh click the button to focus
11:01:37
así y finalmente también vamos a proporcionar
me like so and finally we are going to be also providing
11:01:40
un botón y cuando alguien haga clic en su botón, estarán
a button and when somebody clicks on their button they're
11:01:43
disparando una función que será un manejar enfoque, uh, sí
going to be firing a function which will be a handle focus uh yeah
11:01:47
manejar enfoque estará bien y enfocar entrada será el nivel
handle focus will be fine and focus input will be the level
11:01:50
ahora déjame crear este manejar enfoque justo aquí debajo
now let me create this handle focus right here underneath
11:01:53
esta entrada ref, así que solo usaré como const const
this input ref so i'll just use like const const
11:01:56
manejar enfoque y eso va a ser una flecha
handle focus and that's going to be an arrow
11:02:00
función, vamos a obtener nuestra entrada ref punto actual
function we're going to be getting our input ref dot current
11:02:03
video y solo vamos a usar el enfoque dentro
video and we are going to be only using the focus inside
11:02:06
de ahí, así que ahora déjame guardar mi archivo y revisar esto, así que cada vez que
there so now let me save my file and check this out so anytime
11:02:10
haga clic en este campo de entrada, se va a enfocar mi
i click on this input field so it's going to focus my
11:02:13
campo de entrada y así es como vamos a anotar
input field and this is how we are going to be annotating
11:02:16
ahí, así que ese fue el primer paso, ahora para el siguiente paso vamos a
there so that was the first step now for the next step we're going
11:02:19
crear nuestro formulario de contacto, así que formulario de contacto
to be creating our contact form so contact form
11:02:22
punto tsx y aquí simplemente usemos nuestro
dot tsx and here let's just use our
11:02:25
rafce y registramos allí mismo
rafce and register there right here so
11:02:29
tenemos nuestro formulario de contacto y registramos allí y guardamos allí
we have our contact form and register there and save there
11:02:32
lo que voy a hacer es que primero voy a usar mi estado y aquí vamos a proporcionar nuestro objeto y
so what i'm going to do is there first of all i'm going to use my use state and here we're going to be providing our object and
11:02:40
dentro de este objeto tendremos nuestro nombre y también tendríamos nuestro
inside this object we will have our name and also we would have our
11:02:43
correo electrónico así y
email email like so and
11:02:46
vamos a desestructurar los datos del formulario y también
we are going to be destructuring the form data and also
11:02:49
establecer datos del formulario y va a ser igual a este uso
set form data and it's going to be equals to this use
11:02:53
ahora para estos datos del formulario vamos a estar anotando allí
there now for this form data we are going to be annotating there
11:02:56
con la interfaz así que ahora déjame crear una interfaz para eso así que no vamos
with the interface so now let me just create an interface for that so we're
11:02:59
a hacer nada loco, puedes crear un tipo si quieres, pero en mi caso voy a crear una interfaz con el nombre de como estado del formulario de contacto y básicamente puedes darle cualquier nombre que prefieras.
not going to be doing anything crazy you can either create a type if you wanted to but in my case i'm going to create an interface with the name of like contact form stat and basically you can give it like any name that you prefer.
11:03:10
Voy a escribir un nombre y anotar con la cadena y el correo electrónico y anotar allí.
I'm going to write a name and annotate with the string and email and annotate there.
11:03:16
Vamos, correo electrónico con el correo electrónico y anotar allí con la cadena también.
Come on, email with the email and annotate there with the string as well.
11:03:22
Así que voy a copiar allí y voy a anotar mi uso de estado con este estado del formulario de contacto aquí mismo.
So I'm going to copy there and I'm going to annotate my use stat with this contact form stat right here.
11:03:27
Así que lo que voy a hacer es que voy a eliminar este div y lo voy a reemplazar con el formulario y también voy a reemplazar este otro con el formulario también.
So what I'm going to do is that I'm going to just remove this div and I'm going to replace that with the form and I'm going to also replace this other one to the form as well.
11:03:36
Así que vamos a crear nuestro div. Dentro de este div vamos a crear nuestra etiqueta.
So let's just create our div. Inside this div we're going to be creating our label.
11:03:40
Elimina este HTML4 de allí y también voy a proporcionar mi nombre dentro de allí.
Remove this HTML4 from there and I'm going to also provide my name inside there.
11:03:44
Primero vamos a registrar el campo de entrada y este campo de entrada tendrá el tipo de texto.
First of all we are going to be registering the input field and this input field will have the type of text.
11:03:49
El nombre se establecerá en nombre y también vamos a proporcionar un valor y ese valor vendrá de los datos del formulario punto nombre.
Name will be set to name and we're going to be also providing a value and that value will be coming from the form data dot name.
11:03:56
Está bien, así que también vamos a proporcionar nuestro propio manejador de eventos de cambio y cuando alguien escriba algo allí, vamos a estar manejando este evento de cambio, ahora déjame duplicar este div aquí para el correo electrónico
Okay so we are going to be also providing the own change event handler and when somebody types something inside there so we're going to be fighting this handle change event now let me duplicate this uh dev right here for the email
11:04:07
así que simplemente lo duplicé y cambié allí a correo electrónico y
so i just duplicated that and change there to email and
11:04:11
también cambia este texto a correo electrónico
also change this text to email
11:04:14
y también vamos a cambiar el nombre al correo electrónico como
and we're going to be also changing the name to the email as
11:04:18
bueno, así que cambia el nombre al correo electrónico y en
well okay so change the name to the email and in
11:04:21
este caso vamos a seguir proporcionando este manejador de cambio y debajo de este div vamos a crear nuestro botón que seleccionará enviar y para este botón vamos a estar
this case we're going to be still providing this handle change and underneath this dev we're going to be creating our button which will select submit and for this button we're going to be
11:04:30
proporcionando un tipo de envío a eso, está bien, así que ahora
providing a type of submit to that okay like so and now
11:04:33
finalmente tenemos que crear nuestra función de manejo de cambios dentro
finally we have to just create our handle change function inside
11:04:36
este componente, así que usaré como const manejar cambios, es
this component so i'll use like const handle change it's
11:04:40
va a tomar el objeto de evento y vamos a estar anotando ahí
going to take the event object and we're going to be annotating there
11:04:43
usando el evento de cambio, así que escribamos nuestro
by using the change event so let's just write our
11:04:46
evento de cambio y aquí para este evento de cambio vamos a estar
change event and here for this change event we're going to be
11:04:49
usándolo en el campo de entrada HTML, así que también tenemos que especificar explícitamente ese campo de entrada HTML también, está bien, así que desde el
using there on the html input field so we also have to explicitly specify that html input field as well okay so from the
11:04:57
evento.target, vamos a estar desestructurando el nombre y también el valor.
event.target, we're going to be destructuring the name and also the value.
11:05:01
Así que ahora déjame desestructurar el nombre y también el valor de este evento.target.
So now let me just destructure the name and also the value out of this event.target.
11:05:06
Está bien, así que aquí vamos a estar usando como establecer datos del formulario y simplemente proporcionemos nuestro estado anterior hoy.
Okay, so here we're going to be using like set form data and let's just provide our previous state today.
11:05:11
Y una vez más, vamos a estar haciendo un payaso de nuestro estado anterior.
And once again, we're going to be making a clown of our previous state.
11:05:16
Y aquí vamos a estar definiendo un nombre y luego tenemos que proporcionar un valor más nuevo que ahora estamos obteniendo de este evento.target para ello aquí.
And here we're going to be defining a name and then we have to provide a newer value which we are now getting from this event.target for it here.
11:05:24
Así que ahora voy a guardar eso y eso va a ser todo para nuestro manejo de cambios. A continuación, también tenemos que definir nuestra función de envío.
So now I'm going to save that and that's going to be it for our handle change. Next, we also have to define our on submit function.
11:05:30
Así que cada vez que nuestro formulario se envía, vamos a estar disparando nuestra función de manejar envío.
So whenever our form is submitted, so we're going to be firing our handle submit function.
11:05:35
Voy a copiar ahí y crear mi manejar envío justo aquí.
I'm going to copy there and create my handle submit right here.
11:05:39
Proporcionar nuestro evento y lo anotaremos allí con el evento del formulario.
Provide our event and we will annotate there with the form event.
11:05:43
Y aquí también tenemos que decirle que vamos a estar usando en el elemento del formulario HTML.
And here we also have to tell it that we are going to be using the on the HTML form element.
11:05:49
formulario HTML y luego elemento así.
HTML form and then element like so.
11:05:52
está bien, así que aquí tenemos que usar nuestra función de flecha, vamos a estar previniendo
okay so here we have to use our arrow function we're going to be preventing
11:05:55
el comportamiento predeterminado y también debajo de eso tenemos
the default behavior and also underneath there we have
11:05:58
simplemente registrar en la consola los datos del formulario y
to just log to the console for form data and
11:06:02
aquí, uh, vamos a estar usando algún tipo de etiqueta
here uh we are going to be using some sort of a label
11:06:05
como formulario enviado, así que está bien, eso fue mucha charla y sí, sabes, déjame probar esto, así que aquí puedes ver que tenemos nuestro nombre y correo electrónico
like form submitted like so okay that was a lot of talking and yeah you know let me just test this out so here you can see we have our name and email
11:06:16
para el nombre voy a especificar mi propio nombre, para el correo electrónico simplemente escribiré como prueba@gmail.com
for the name i'm going to specify my own name for the email i'll just write like test at gmail.com
11:06:21
y ahora si hago clic en este enviar y abro mi consola, así que
and now if I click on this submit and open my console so
11:06:24
nos dará todos sus datos aquí, pero estamos recibiendo algún tipo de error
it's going to give us all of their data right here but we are getting some sort of error
11:06:27
por tipo presente y prueba en gmail.com
by type present and test at gmail.com
11:06:31
y haga clic allí, ahora estamos enviando nuestro formulario y también
and click on there now we are getting our form submitted and also
11:06:34
nuestro correo electrónico y nuestros datos de nombre, lo que significa que
our email and our name data so which means like
11:06:37
todo está funcionando como esperamos que funcione y esto es
everything is working the way we expect them to work and this is
11:06:41
cómo vamos a proporcionar una anotación o un tipo de script para nuestro objeto de evento y así es como vamos a
how we are going to be providing an annotation or type script for our event object and this is how we are going
11:06:46
proporcionar allí o así es como vamos a crear un
to be providing there or this is how we're going to be creating an
11:06:49
estado de interfaz hacia adelante, ahora déjame crear el componente final
interface forward state now let me create the final component
11:06:52
que será para el manejo de eventos, así que vamos a usar como evento
which will be for the event handling so we're going to be using like event
11:06:56
manejando .tx, voy a usar mi rafc
handling dot tx i'm going to use my rafc
11:06:59
dentro de allí, ve a mi aplicación y registra ese componente
inside there go to my app and register that component
11:07:02
justo aquí, así que manejo de eventos y voy a
right here so event handling and i'm going to
11:07:05
simplemente llamar a este componente, mira esto y tenemos nuestro manejo de eventos que se ve increíble, lo primero que quiero hacer es que
just call this component check this out and we have our event handling which is looking amazing the first thing that i want to do is that
11:07:12
quiero crear mi h2 que dirá algo como manejo de eventos
want to create my h2 which will say like event handling
11:07:15
ejemplo y ahora debajo de eso simplemente
example and now underneath that i'll just
11:07:18
crear un botón y ese botón dirá algo como clic meh
create a button and that button will say like click meh
11:07:22
y aquí también tenemos que proporcionar el on click
and here we also have to provide the on click
11:07:25
manejador de eventos y cuando alguien haga clic en
event handler and when somebody clicks on
11:07:28
su manejador de clic, así que en esa situación estamos
their handle click so in that situation we are
11:07:31
simplemente disparando esta función como manejar clic y estamos
going to be just firing this function like handle click and we
11:07:34
también creando un evento para este, así que cuando alguien pase el mouse, en esta situación vamos a
are going to be also creating an event for this one so like when somebody mouse enter so in this situation we are going to be
11:07:41
disparar esta función como manejar mouse enter, está bien
firing this function like handle mouse enter okay
11:07:44
así que lo que voy a hacer es que voy a definir ambas funciones, así que
so what i'm going to do is that i'm going to define both of these functions so
11:07:48
primero, definamos esta función manejar clic, luego vamos a definir esta manejar mouse enter, está bien, así que voy a copiar eso y crear mi manejar clic
first of all let's just define this handle click one then we're going to be defining this handle mouse enter okay so i'm going to copy that and create my handle click
11:07:57
va a tomar el objeto de evento y vamos a anotar allí con el
it's going to take the event object and we're going to be annotating there with the
11:08:00
evento del mouse y también tenemos que decirle explícitamente que vamos a activar ese evento en el botón html
mouse event and we also have to explicitly tell it that we're going to be firing that event on the html button
11:08:07
elemento así y aquí dentro
element like so and here inside there
11:08:10
vamos a registrar en la consola como evento punto actual
we're going to be logging to the console like event dot current
11:08:13
vamos c u doble r c u doble r e
come on c u double r c u double r e
11:08:16
n t objetivo actual y también tenemos
n t current target and also we
11:08:19
que proporcionar algún tipo de nivel como clic en botón hacia algo
have to just provide some sort of a level like button click towards something
11:08:22
como ahí voy a guardar mi archivo y estamos
like there i'm going to save my file and we
11:08:25
obteniendo algún tipo de error oh eso es porque tenemos que escribir un react
are getting some sort of error oh that's because we have to write a react
11:08:28
así que voy a usar react y presionar enter así
dot so i'm going to use react and hit enter so
11:08:31
va a agarrar este react react del react js que es
it's going to grab this react react from the react js that's
11:08:35
lo primero ahora también tenemos que definir esto
the first thing now we also have to define this
11:08:38
función así que lo que voy a hacer es que voy a definir ahí
function so what i'm going to do is that i'm going to define there
11:08:41
justo aquí así const manejar mouse enter es
right here so const handle mouse enter it's
11:08:44
también va a tomar el objeto de evento y vamos a estar anotando allí usando
going to also take the event object and we're going to be annotating there by using
11:08:47
react.mouse y evento de mouse
react.mouse and mouse event
11:08:50
y luego le vamos a decir que vamos a activar allí en el elemento dev html está bien así que también voy a proporcionar
and then we're going to be telling it that we're going to be firing there on the html dev element okay so i'm going to also provide
11:08:59
uh lo que llamamos un const.log y aquí estamos
uh what we call a const.log and here we're
11:09:02
vamos a estar usando como e.current target justo aquí
going to be using like e.current target right here
11:09:05
y también voy a proporcionar algún tipo de etiqueta que dirá como
and i'm going to also provide some sort of a label which will say like
11:09:08
mouse entró o algo así
mouse entered or something
11:09:11
ahora déjame guardar allí y probar esto y aquí
now let me save there and test this out and here
11:09:14
puedes ver que tenemos nuestra uh etiqueta y también
you can see we have our uh label and we also
11:09:18
tenemos nuestro botón déjame solo refrescar allí y cada vez que paso el mouse
have our button let me just refresh there and whenever i hover my
11:09:21
sobre esto va a darnos ese mouse enter y
mouse over to this it's going to give us that mouse enter and
11:09:24
también nos va a dar, sabes, déjame solo mostrarte que también nos va a dar ese div específico así que ahora dentro de este div tenemos nuestro manejo de eventos
it's going to also gives us you know let me just show you that it's going to also gives us that specific div so now inside this div we have our event handling
11:09:31
ejemplo y también nuestro botón y ahora si paso el mouse
example and also our button and now if i hover my mouse
11:09:34
sobre este clic me va a dar
over to this click me it's going to also gives
11:09:38
como mouse enter, nos va a dar esos datos así que
us like mouse enter it's going to give us that data so
11:09:41
sí, ese fue un ejemplo o ese fue un desafío para el
yeah that was example or that was a challenge for the
11:09:44
déjame mostrarte el contacto del input de enfoque
let me just show you the focus input contact
11:09:48
formulario y también el manejo de eventos, ahora hablemos de cómo vamos
form and also the event handling now let's talk about how we
11:09:51
a usar TypeScript con la API de contexto, así que para hacer eso voy a crear una carpeta con el nombre de contexto y ahora dentro de esta carpeta solo crearé mi context.tsx
are going to be using a typescript with context api so to do that i'm going to create a folder with the name of context and now inside this folder i'll just create like my context.tsx
11:10:01
y ahora dentro de ahí, primero que nada, vamos a tener que importar o crear contexto desde react.js y ahora lo siguiente que tenemos que hacer es que tenemos que crear una instancia de eso.
and now inside there first of all we are going to have to import or create context from react.js and now the next thing that we have to do is that we have to create an instance of that.
11:10:09
Así que usaré mi exportación y luego const my context y eso va a ser igual a crear contexto.
So I'll use my export and then const my context and that's going to be equals to the create context.
11:10:15
Así que vamos a crear una instancia de eso y ahora para el valor inicial voy a proporcionar un conteo y el conteo será igual a cero y también vamos a crear una función de incremento
So we are going to be creating an instance of that and now for the initial value I'm going to provide a count and count will be equal to zero and we're going to be also creating an increment function
11:10:24
que simplemente no devolverá nada por ahora y luego también vamos a crear una función más para el decremento, así que voy a guardar este archivo y ahora si quieres agregar un tipo de script
which will just return nothing for now and then we are going to be also creating one more function for the decrement okay so i'm going to save this file and now if you want to add a type script
11:10:33
contexto hacia adelante, así que así es como vamos a hacer eso, puedes crear un tipo o también puedes crear una interfaz si lo deseas
forward context so this is how we are going to be doing that you can either
11:10:36
así que solo crearé mi interfaz aquí y le daré el nombre de
create a type or you can also create an interface if you wanted to
11:10:39
mis propiedades de contexto y ahora dentro de ahí
so i'll just create my interface right here and i'm going to give it the name of
11:10:42
como mis propiedades de contexto y ahora dentro de ahí
like my context props and now inside there
11:10:46
tenemos un contador que será un número y también tenemos una función de incremento y desde esta función de incremento vamos a
we have a count which will be a number and we also have an increment function and from this increment function we are going to be
11:10:52
solo devolver el blanco como nada por ahora entonces nosotros
only returning the white like nothing for now then we
11:10:55
también vamos a crear uno para el decremento así que ahora déjame duplicar ahí
are going to be also creating one for the decrement so now let me just duplicate there
11:10:58
y crear nuestra función de decremento y ahora si quieres agregar ahí
and create our decrement function and now if you want to add there
11:11:02
así que solo escribiré mi lista y asignaré y luego escribiré como mi
so i'll just write my list and sign and then i'll write like my
11:11:05
propiedad de contexto y voy a cerrar ahí de esta manera está bien
context prop and i'm going to close there at this way okay
11:11:08
así que así es como vamos a definir nuestro contexto y ahora hablemos de
so this is how we are going to be defining our context and now let's talk about
11:11:11
cómo vamos a crear nuestro proveedor así que para crear nuestro proveedor solo voy a escribir como const mi proveedor vamos mi proveedor ahí vamos es
how we are going to be creating our provider so to create our provider i'm going to just write like const my provider come on my provider there we go it's
11:11:19
va a tomar un children como una propiedad y luego dentro
going to take a children as a prop and then inside
11:11:22
de ahí vamos a estar usando como const y luego contador y
there we are going to be using like const and then count and
11:11:26
entonces establece el conteo, este va a ser el estado que quieres pasar a
then set count this is going to be the state which you want to pass into
11:11:29
nuestro componente, así que vamos a estar usando como use state y el inicial
our component so we are going to be using like use state and the initial
11:11:32
el radio se establecerá en cero, así que ahora está tomando un hijo, así que
radio will be set to zero so it is now taking a children so
11:11:35
tenemos que proporcionar un tipo para eso también, así que solo usaré como mi
we have to provide a type for that as well so i'll just use like my
11:11:39
fc como mi componente funcional que vendrá de react.js y luego tenemos que proporcionar nuestra prop aquí, así que así es como vamos a crear, usaré mi interfaz
fc like my functional component which will be coming from the react.js and then we have to provide our prop right here so this is how we are going to be creating there i'll use my interface
11:11:49
y luego mi proveedor, sí, eso va a estar bien, vamos a
and then my provider yeah that's that's going to be fine we're
11:11:52
proporcionar nuestros hijos que vendrán del nodo react
going to be providing our children that's going to be coming from the react node
11:11:56
y si presiono enter, se va a importar automáticamente aquí, así que ahora voy a etiquetar eso y lo voy a poner aquí
and if i hit enter so it's going to auto import there right here okay so now i'm going to tag that and i'm going to put there right here
11:12:02
envía mi archivo y ahora nos va a dar un error porque tenemos que
send my file and now it's going to give us an error because we have to
11:12:05
usar eso, ahora primero déjame exportar esto para que podamos usar
use that now first of all let me just export this so that we can use
11:12:08
en otros archivos, así que usaré como export default y luego mi proveedor, vamos mi proveedor así que envía mi archivo y ahora dentro de este mi proveedor
in other files so i'll use like export default and then my provider come on my provider like so send my file and now inside this my provider
11:12:18
voy a simplemente devolver primero mi contexto
I'm going to just return first of all my my context
11:12:21
y vamos, ¿qué demonios estoy haciendo? y
and come on what the hell am I doing and
11:12:24
entonces voy a usar el método del proveedor allí, así que solo voy a
then I'm going to use the provider method on there okay so I'll just
11:12:27
cerrar allí dentro de este proveedor, voy a tener que pasar algunos
close there inside this provider I'm going to have to pass some
11:12:30
tipo de datos, así que usaré como valor y para el valor estamos
sort of data so I'll use like value and for the value we are
11:12:34
pasando un conteo que ya hemos definido aquí y
going to be passing a count which we've already defined right here and
11:12:37
ahora déjame usar mi función de incrementar y decrementar, así que usaré como incrementar
now let me just use my increment and decrement function so I'll use like increment
11:12:40
y ahora dentro de este incremento no vamos a hacer nada loco, pero solo usaré como establecer conteo y luego conteo más
and now inside this increment we're not going to be doing anything crazy but I'll just use like set count and then count plus
11:12:47
uno y también voy a crear una función más para el decremento como
one and I'm going to also create one more function for the decrement as
11:12:51
bueno, así que usaré como decrementar aquí y
well so I'll use like decrement right here and
11:12:54
voy a decrementar mi valor aquí, solo escribiré un menos
I'm going to decrement my value right here I'll just write a minus
11:12:57
y también voy a copiar ambos y colocar
and I'm going to also copy both of them and place
11:13:01
ahí mismo junto con el conteo, así que solo colocaré su incremento
there right here along with the count so I'll just place their increment
11:13:04
y también voy a copiar el decremento y lo voy a colocar allí, así que si guardo mi archivo y aquí puedes ver que todos los errores han desaparecido y obviamente tenemos que usar
and I'm going to also copy the decrement and I'm going to place there okay so if I save my file and here you can see all of the errors are now gone and obviously we have to use
11:13:12
estos niños dentro de nuestro jsx así que solo lo pondré
these children inside our jsx so i'll just put it
11:13:15
ahí justo aquí así que si guardo mi archivo y
there right here like so so if i save my file and
11:13:18
así es como vamos a proporcionar un tipo para nuestro contexto ahora
this is how we are going to be providing a type for our context now
11:13:22
voy a ir a mi componente principal y tenemos que usar eso bien
i'm going to go into my main component and we have to use that right
11:13:25
aquí así que lo primero que quiero hacer es que quiero agarrar mi
here so the first thing that i want to do is that i want to grab my
11:13:28
proveedor justo aquí voy a copiar de allí y
provider right here i'm going to copy there from there and
11:13:31
solo usemos eso en toda la aplicación está bien
let's just use there on all of the entire app okay
11:13:34
así que voy a poner eso aquí guardo mi archivo y así es como vamos a agregarlo exitosamente pero ahora solo crearé un componente contador escribiré como
so i'm going to put there here save my file and this is how we are going to be successfully adding there but now i'll just create a counter component i'll write like
11:13:42
componente y luego counter.tsx será
component and then counter.tsx will
11:13:45
bien voy a usar mi archivo rafce semi
be fine i'm going to use my rafce semi file
11:13:48
ir a mi componente de aplicación y solo registremos ese contador justo aquí para que podamos ver qué está pasando
go into my app component and let's just register that counter right here so that we can see what's going on
11:13:54
así que voy a registrar mi componente contador justo aquí
okay so i'm going to just register my counter component right here
11:13:57
ahora tenemos que usar nuestro contexto dentro de este componente contador así que para hacer eso primero vamos a importar
now we have to use our context inside this counter component so to do that first of all we are going to be importing
11:14:03
el uso del contexto de react.js y luego también vamos a importar nuestro propio contexto como mi
the use context from the react.js and then we are going to be also importing our own context like my
11:14:09
contexto bien desde la carpeta de contexto y
context okay from the context folder and
11:14:12
ahora para usar eso lo primero que quiero hacer es que quiero escribir
now to use that the first thing that i want to do is that i want to write
11:14:15
mi fc así que solo usaré como fc para el funcional
my fc so i'll just use like fc for the functional
11:14:19
componente y supongo que eso estará bien y dentro
component and i guess that's going to be fine and inside
11:14:22
ahí usaré mi uso del contexto voy a proporcionar
there i will use my use context i'm going to provide
11:14:25
mi propio contexto a ahí como mi contexto y vamos a desestructurar muchas cosas de él así que necesito el conteo y también la función de incremento y también la función de decremento de mi contexto
my own context to there like my context and we are going to be destructuring a lot of things from it so like i need the count and also the increment function and also the decrement function from my context
11:14:37
o mi uso del contexto. Así que ahora dentro de ahí, solo usemos el componente de trabajo interno.
or my use context. So now inside there, let's just use the inside work component.
11:14:41
voy a eliminar este div de aquí y proporcionar mi párrafo y proporcionar el conteo y el valor inicial para este conteo se establecerá en ese conteo que proviene del contexto de trabajo.
I'm going to remove this div from here and provide my paragraph and provide the count and the initial value for this count will be set to that count which is coming from work context.
11:14:50
También vamos a crear un botón que dirá como incrementar.
We're going to be also creating a button which will say like increment.
11:14:54
Vamos, incrementar y también esto es crear uno
Come on, increment and also this is create one
11:14:57
para el decremento y adjuntar el controlador de eventos en
for the decrement and attach event handler on
11:15:00
ambos de estos botones el primero tomará el incremento y
both of these buttons the first one will take the increment and
11:15:03
el segundo tomará el decremento así que ahora si guardo mi archivo y
the second will take the decrement so now if i save my file and
11:15:07
aquí puedes ver que ahora estamos obteniendo nuestro conteo si hago clic en esto va a
here you can see you are now getting our count if i click on this it's going to
11:15:10
incrementar mi contador y si hago clic en este va a decrementar
increment my counter and if i click on this one so it's going to decrement
11:15:13
mi contador aquí por uno así que sí esto es
my counter right here by one so yeah this is
11:15:16
cómo vamos a proporcionar un contexto de typescript hacia adelante ahora hablemos de cómo vamos a proporcionar un reductor de usuario hacia adelante así que yo
how we are going to be providing a typescript forward context now let's talk about how we are going to be providing a type forward user reducer so i'll
11:15:24
solo crearé una carpeta de componentes y dentro de ella vamos a crear work counter.tsx y voy a usar mi rafc para que pueda ver algo en la pantalla y aquí vamos a registrar los componentes de work counter.
just create a components folder and inside there we're going to be creating work counter.tsx and I'm going to use my rafc so that I can see something on the screen and here we're going to be registering work counter components.
11:15:37
Así que si guardo mi archivo y reviso esto aquí puedes ver que ahora estamos obteniendo work counter que se ve increíble.
So if I save my file and check this out so here you can see we are now getting work counter which is looking amazing.
11:15:42
Ahora dentro de este componente contador lo primero que quiero hacer es importar el reductor de usuario de react.js y luego tenemos que usarlo dentro del componente work counter.
Now inside this counter component the first thing that I want to do is that I want to import the user reducer from the react.js and then we have to use the inside work counter component.
11:15:51
Así que usaré el reductor de usuario va a tomar la función reductor
So I'll use like user reducer it's going to take the reducer function
11:15:54
y también el estado inicial así que vamos a proporcionar como conteo
and also the initial stat so we're going to be providing like count
11:15:57
y el conteo se establecerá en cero está bien así que vamos a desestructurar
and count will be set to zero okay so we are going to be destructuring
11:16:00
nuestro estado y funciones de despachar así que solo usaré como estado
our stat and dispatch functions so i'll just use like stat
11:16:03
y también el despachar y ahora que tenemos que crear nuestro reductor y
and also the dispatch and now that we have to create our reducer and
11:16:07
también tenemos que proporcionar un tipo para este estado está bien así que
also we have to provide a type for this stat okay so
11:16:10
lo que voy a hacer es que voy a crear mi función reductor justo aquí yo
what i'm going to do is that i'm going to just create my reducer function right here i'll
11:16:13
solo le daré un nombre como reductor va a tomar el estado y también la acción y ahora en esta función vamos a usar nuestro switch y
just give it a name of like reducer it's going to take the stat and also the action and now in this function we're going to be using our switch and
11:16:20
casos una vez más y primero de todo vamos a proporcionar si
cases one more time and first of all we are going to be providing if
11:16:23
el tipo de acción punto tipo vamos a escribir un tipo
the action dot type come on let me just write a type
11:16:26
está establecido en incrementar i n c r e
is set to increment i n c r e
11:16:29
m e n t ahí vamos así que en esta situación solo vamos a devolver
m e n t there we go so in this situation we are going to be only returning
11:16:33
el conteo y el conteo vendrá de el estado punto conteo
the count and count is going to be coming from the state dot count
11:16:36
más uno y si ese no es el caso y el caso
plus one and if that's not the case and the case
11:16:39
es decrementar así que en esta situación qué tenemos que hacer tenemos que una vez más devolver nuestro conteo y el conteo vendrá de el estado punto conteo menos
is decrement so in this situation what do we have to do we have to once again return our count and count will be coming from the state dot count minus
11:16:47
uno está bien y también si ese no es el caso así que
one okay and also if that's not the case so
11:16:51
para el valor predeterminado vamos a proporcionar qué estadística justo aquí estoy
for the default value we are going to be providing what stat right here i'm
11:16:54
voy a eliminar eso y aquí puedes ver que ahora estamos obteniendo un error como qué es
going to remove that and here you can see we are now getting an error like what is
11:16:57
una estadística y cuál es la acción así que para hacer eso vamos a tener que
a stat and what is the action so to do that we are going to have to
11:17:00
proporcionar un tipo para eso así que ahora voy a crear un tipo justo aquí
provide a type for that so now i'm going to just create a type right here
11:17:03
con el nombre de acción o acciones
with the name of action or actions
11:17:06
supongo que acción estaría bien porque solo vamos a hacer
i guess action would be fine because we are going to be doing only
11:17:09
una acción y voy a proporcionar la propiedad de tipo hoy y
one action and i'm going to provide the property of type today and
11:17:12
ese tipo puede ser ya sea incremento o eso
that type can be either increment or that
11:17:16
el tipo puede ser vamos a escribir el tipo puede
type can be come on let just write type can
11:17:19
ser establecido en decrementar como ya hemos especificado allí
be set to decrement as we've already specified there
11:17:22
justo aquí como ya sea incremento o decrementar así que ahora que tenemos
right here like either increment or decrement so now that we have
11:17:25
usar allí justo aquí para esta acción así que voy a anotar allí
to use there right here for this action so i'm going to just annotate there
11:17:28
con esta acción lo siguiente que tenemos que hacer es que tenemos que cuidar
with this action the next thing that we have to do is that we have to take care
11:17:31
de esta estadística así que también vamos a crear un tipo para
of this stat so we are going to be also creating a type for
11:17:35
la estadística también así que usaré como tipo y luego simplemente usemos una estadística y ahora dentro de allí vamos a especificar un conteo y el conteo ahora está establecido en número y tenemos que tomar esta estadística tenemos que proporcionar allí justo aquí
the stat as well so i'll use like type and then let's just use a stat and now inside there we are going to be specifying a count and count is now set to number and we have to take this stat we have to provide there right here
11:17:47
y también vamos a estar devolviendo una propiedad de conteo desde allí así que
and we are going to be also returning a count property from there so
11:17:50
también podemos anotar toda esta función como un
we can also annotate this entire function as a
11:17:53
estado está bien así que esto es lo que tenemos que hacer primero que todo tenemos que
stat okay so this is what we have to do first of all we have to
11:17:56
crear un tipo de acción y tenemos que especificar por lo tanto el
create an action type and we have to specify therefore the
11:17:59
acciones luego tenemos que crear un tipo de estadística y tenemos que especificar por lo tanto la estadística está bien así que esto es lo que tenemos que hacer para esta función reductora
actions then we have to create a stat type and we have to specify therefore the stat okay so this is what we have to do for this reducer function
11:18:07
y ahora simplemente usemos esta estadística y también esta función de despacho dentro de esta interfaz de usuario así que para usarlas
and now let's just use this stat and also this dispatch function inside this ui so to use them
11:18:12
voy a estar usando un párrafo y solo proporcionaré un conteo y
I'm going to be using a paragraph and I'll just provide a count and
11:18:15
ese conteo vendrá de la estadística.contar y ahora debajo vamos a estar creando un botón que solo seleccionará incrementar y también vamos a estar creando uno para el decrementar.
that count will be coming from the stat.count and now underneath we are going to be creating a button which will just select increment and also we are going to be creating one for the decrement.
11:18:26
e-e-c-r-e-m-e-n-t ahí vamos voy a proporcionar un controlador de eventos on click en ambos
e-e-c-r-e-m-e-n-t there we go i'm going to provide an on click event handler on both of them
11:18:31
que solo activará esta función de despacho vamos a activar esta
which will just fire this dispatch function let's just fire this
11:18:34
función de despacho y vamos a proporcionar un tipo de incremento
dispatch function and we are going to be providing a type of increment
11:18:38
para el primero y un decremento para el segundo
for the first one and decrement for the second one
11:18:41
así que vamos a usar nuestro decremento, ahí vamos y
so let's just use our decrement there we go and
11:18:45
si guardo mi archivo y todo debería funcionar como esperamos, así que si hago clic en este botón, ahora incrementará nuestro contador y si hago clic en este
if i save my file and everything should work the way we expect to work so if i click on this button it will now increment over counter and if i click on this
11:18:52
el botón va a decrementar nuestro contador, está bien, así que sí
button is going to decrement our counter okay so yeah
11:18:56
así es como vamos a proporcionar un tipo para nuestro use reducer
this is how we are going to be providing a type for our use reducer
11:18:59
esto es mucha instrucción, así que básicamente vas a crear
this is a lot of instruction so basically you're going to be creating
11:19:02
un contador usando el use reducer y también vas a
a counter by using the use reducer and you're going
11:19:05
proporcionar los tipos apropiados para ellos, así que dale tu
to be also providing the appropriate types to them so give it your
11:19:09
mejor intento, si puedes hacerlo, está completamente bien, luego vuelve
best shot if you can do it that's completely okay then come
11:19:12
y mira la solución y te voy a dar mi solución, así que aquí
back and watch the solution and i'm going to give you my solution so here
11:19:15
primero voy a crear una carpeta con el nombre de reducers
first of all i'm going to just create like a folder with the name of reducers
11:19:18
y dentro de ella vamos a definir nuestro reducer de contador
and inside there we're going to be defining our counter reducer
11:19:22
.ts y aquí solo vamos a definir nuestro reducer
dot ts and here we're going to be just defining our reducer
11:19:25
así que usaré el reducer de contador, va a
so i'll use the counter reducer it's going
11:19:28
tomar el estado y también va a tomar la acción y
to take the state and it's going to also take the action and
11:19:31
aquí dentro vamos a usar nuestro switch
here inside there we're going to be using our switch
11:19:35
el caso final no es así, pero el switch y el caso final son como
end case it's not like that but switch end case is like
11:19:38
así que para el switch vamos a definir nuestro action.type tie f con el e y para el primero vamos a poner un incremento allí.
so so for the switch we're going to be defining our action dot type tie f with the e and for the first we are going to be putting an increment to there.
11:19:48
Así que si eso está configurado para incrementar, vamos a devolver el conteo y el conteo vendrá de state.count más uno.
So if that is set to increment, we are going to be returning the count and count will be coming from the state.count plus one.
11:19:55
Solo vamos a incrementar allí. Pero si el caso está configurado para
We are going to be only incrementing there. But if the case is set to
11:20:00
Así que usaré como decremento, D-E-C-R-E-M-E-N-T. Decremento.
And so I'll use like decrement, D-E-C-R-E-M-E-N-T. Decrement.
11:20:05
Así que vamos a devolver el conteo. Y solo vamos a obtenerlo de state.count.
So we're going to be returning the count. And let's just get there from the state.count.
11:20:10
Y solo vamos a escribir un menos uno porque vamos a decrementar allí. Después de eso, solo vamos a eliminar allí.
And let's just write a minus one because we're going to be decrementing there. After that, let's just remove there.
11:20:16
Después de eso, también vamos a proporcionar un estado predeterminado para ello. Así que para el predeterminado, solo vamos a devolver nuestro estado. Ahora eso está completamente hecho.
After that, we're going to be also providing a default state to it. So for the default, we're going to be only returning our state. Now that's totally done.
11:20:23
Pero también tenemos que proporcionar un tipo para el estado y también para la acción. Y vamos a hacer eso totalmente por separado.
But we also have to provide a type for the state and also for the action. And we're going to be doing that totally separately.
11:20:30
Escribiré un tipo con el nombre de estado del contador y aquí estamos
I'll write a type with the name of counter state and here we're
11:20:33
solo vamos a escribir como conteo y el conteo se establecerá en un número que
going to be only writing like count and count will be set to a number we
11:20:37
también podemos hacer eso en una sola línea, no tenemos que dividir en múltiples
can also make that as a one liner we don't have to split in multiple
11:20:40
líneas, también podemos escribir un tipo para el incremento
lines we can also write a type for the increment
11:20:43
acción que también tomará el tipo y
action which will also take the type and
11:20:46
el tipo se establecerá en incrementos, déjame escribir un incremento o
the type will be set to increments let me just write an increment or
11:20:50
sabes qué, déjame copiar eso de aquí en mucho tiempo
you know what let me just copy that from here in a lot of time
11:20:53
cometo errores de ortografía, así que ahora déjame duplicar eso y
I misspell things so now let me just duplicate that and
11:20:56
voy a cambiar eso al decremento, así que voy a copiar y colocar eso
I'm going to change that to the decrement so I'm going to copy and place that
11:20:59
y también en lugar de escribir un contador de incremento, voy a
and also instead of writing an increment counter I'm going
11:21:02
cambiar eso a dec, vamos e-e-c-r-e-m-e-n-t
to change that to dec come on e-e-c-r-e-m-e-n-t
11:21:06
acción de decremento, ahora déjame hacer eso como un tipo único, así que
decrement action now let me make that as a one type so
11:21:09
usaré como tipo y haré eso como una acción de contador y eso es
I'll use like type and make that as a counter action and that's
11:21:13
igual al incremento o al
going to be equals to the increment action or the
11:21:16
decremento, así y finalmente también voy a exportar esto para que podamos usarlo en otro archivo también, voy a exportar esto
decrement action like so and finally I'm going to also export this so that we can use that in other file too I'm going to also export this
11:21:24
contador, así que solo usaré como exportar aquí y finalmente estamos
counter so i'll just use like export right here and finally we're
11:21:27
también exportando el primero, así que ahora déjame usar exportar para
going to be also exporting the first one so now let me just use export for
11:21:30
este también, ahora es hora de anotar qué estado con
this one as well now it's time to annotate what state with
11:21:34
qué estado de contador y también qué acción
what counter state and also what action
11:21:37
con qué acción de contador, así que
with what counter action like so so
11:21:40
ahora eso está totalmente hecho, ahora déjame continuar y crear mi counter.jsx
now that's totally done now let me go ahead and create my counter.jsx
11:21:44
o componente tsx, usaré como counter.tsx
or tsx component i'll use like counter.tsx
11:21:47
dentro de ahí voy a usar mi archivo rfce semi, ir a mi aplicación y registrar eso
inside there i'm going to use my rfce semi file go to my app and register that
11:21:53
componente aquí dentro de mi aplicación, lo primero que quiero
component right here inside my app the first thing that i want
11:21:56
lo que quiero hacer es que quiero obtener mi use reducer así que usaré como use
to do is that i want to grab my use reducer so i'll use like use
11:21:59
reducer de reactjs también necesitarías
reducer from the reactjs you would also need to
11:22:02
obtener nuestro reducer de contador y también el contador
grab our counter reducer and also the counter
11:22:06
estado de donde de nuestro reducer de contador así que
state from where from our counter reducer so
11:22:09
ahora debajo de eso tenemos que definir nuestro estado inicial para el inicial
now underneath that we have to define our initial state for the initial
11:22:13
estado inicial vamos a estar anotando allí con el estado del contador que el estado del contador proviene de
i n i t i l initial state we are going to be annotating there with the counter state that counter state is coming from
11:22:21
este use reducer que ya hemos definido como count
this use reducer which we have already defined like count
11:22:24
ahora está configurado en un número que va a ser igual al count
is now set to number that's going to be equals to the count
11:22:27
y el count será igual a cero eso está totalmente hecho ahora
and count will be equals to zero that's totally done now
11:22:31
tenemos que usar nuestro use reducer para obtener nuestra función dispatch
we have to use our use reducer to get our dispatch function
11:22:34
y también nuestro estado inicial así que usaré como use reducer y aquí vamos a pasar nuestro reducer de contador y luego el estado inicial dentro de allí
and also our initial state so i'll use like use reducer and here we're going to be passing our counter reducer and then the initial state inside there
11:22:42
déjame desestructurar mi estado y también el dispatch de ese use reducer y ahora estoy
let me destructure my state and also uh the dispatch out of that use reducer and now i'm
11:22:50
a punto de crear la interfaz de usuario para eso como no una interfaz mágica sino una interfaz muy simple como count y aquí solo vamos a usar nuestro estado punto count para ver nuestro contador.
going to create the UI for that like not a magical UI but a very simple UI like count and here we are going to be only using our state dot count to see our counter.
11:23:00
También vamos a crear un botón. El primero solo incrementará nuestro contador y el segundo disminuirá nuestro contador.
We are going to be also creating a button. The first one will just increment our counter and the second one will be decrementing our counter.
11:23:08
Así que voy a proporcionar el controlador de eventos on click en ambos. Así que el primero
So I'm going to provide the on click event handler on both of them. So the first one
11:23:12
incrementará nuestro contador no interfaz sino incrementar
will increment or count not interface but increment
11:23:16
i n c r e m e n t
i n c r e m e n t
11:23:19
y el segundo disminuirá
and the second one will be decrementing
11:23:22
nuestro contador está bien así que ahora déjame simplemente ir y crear los contadores de incremento y también de decremento incrementar y habrá una función de error y esta función de error solo despachará y aquí tenemos que especificar el
or counter okay so now let me just go ahead and create the increment and also the decrement counters increment and there's going to be an error function and this error function will just dispatch and here we have to specify the
11:24:04
Ahora la última cosa que vamos a aprender en esta sección es cómo vamos a proporcionar un tipo para el use effect.
Now the final thing that we are going to be learning in this section is that how we are going to be providing a type for the use effect.
11:24:10
está bien así que para hacer eso primero voy a crear mi carpeta de componentes
okay so to do that i'm going to first of all create my components folder
11:24:13
y solo le daré el nombre de como mi component.tsx
and i'll just give it the name of like my component.tsx
11:24:17
dentro de allí solo usemos nuestro rafce semi
inside there let's just use our rafce semi
11:24:20
archivo ve a mi app y usa ese mi
file go to my app and use that my
11:24:23
componente aquí voy a llamar a este archivo semi
component right here i'm going to call this semi file
11:24:27
y mira esto, así que aquí puedes ver que tenemos nuestro componente que
and check this out so here you can see we have our my component which
11:24:30
se ve increíble, así que lo primero que tenemos que hacer es que tenemos que obtener nuestro use thread porque necesitamos algún tipo de hilo para almacenar nuestros datos y también necesitaremos el use effect.
is looking amazing so the first thing that we have to do is that we have to grab our use thread because we would need some sort of a thread to store our data and we will also need the use effect as well.
11:24:41
Está bien, así que ahora vamos a usar el interior de nuestro componente. Así es como vamos a hacerlo.
Okay so now we are going to be using the inside of our component. So this is how we are going to be doing there.
11:24:45
Primero que nada, vamos a crear nuestros datos y luego set data, y eso va a ser igual a use state y le vamos a proporcionar el valor inicial de nulo.
First of all we are going to be creating our data and then set data and that's going to be equals to the use state and we are going to be providing the initial value of null to it.
11:24:53
También lo anotaré allí como un valor nulo. Ahora que tenemos que obtener nuestros datos.
I will also annotate there as a null value. Now that we have to fetch our data.
11:24:58
Así que para obtener nuestros datos, ya sabes cómo vamos a hacerlo. Así que vamos a usar el use effect aquí.
So to fetch our data you already know how we are going to be fetching our data. So we are going to be using the use effect right here.
11:25:04
Y ahora dentro de eso, vamos a pasar la función de callback y también nuestro array de dependencias vacío.
And now inside there, we are going to be passing the callback function and also our empty dependency array.
11:25:08
Ahora, lo primero que quiero hacer es usar mi función de obtener datos. Eso va a venir de esta función asíncrona así.
Now the first thing that I want to do is that I want to use my fetch data function. That's going to be coming from this asynchronous function like so.
11:25:16
Y dentro de eso, vamos a usar nuestro bloque de try y catch.
And inside there, we are going to be using our try and catch block.
11:25:19
Y si tenemos algún tipo de error, en esa situación vamos a usar
And if we have some sort of error, so in that situation we are going to be using
11:25:22
como console.error y simplemente usaremos algo como error al obtener datos
like console.error and let's just use like error fetching data
11:25:27
está bien y también especificaremos nuestro error aquí y
okay and we will also specify our error right here and
11:25:30
si no es el caso, así que para el bloque try vamos a obtener nuestros
if that's not the case so for the try block we are going to be getting our
11:25:33
datos usando el método fetch y vamos a
data by using the fetch method and we are going to be
11:25:36
obtener nuestros datos de esta API que es json
getting our data from this api which is json
11:25:39
plus holder.com y para slash product y solo vamos a obtener el primer producto, está bien, así que también tenemos que cambiar eso o convertir nuestra respuesta a json
plus holder.com and for slash product and we are going to be getting only the first product okay so we have to also change that or convert our response to json
11:25:49
y tenemos que almacenar en algún tipo de variable así y yo estoy
and we have to store in some sort of a variable like so and i'm
11:25:52
también voy a establecer los datos, quiero decir, establecer
going to also set the data to i mean like set
11:25:55
el resultado en nuestro set data, así es como vamos a obtener
the result to our set data so this is how we are going to be fetching
11:25:58
nuestros datos y ahora simplemente ejecutemos esta función para que
our data and now let's just execute this function so that
11:26:01
podamos obtener estos datos con éxito, así que si guardo mi archivo y
we can successfully fetch this data so if i save my file and
11:26:05
ahora, si hago clic en esto, nos mostrará todas sus cosas aquí
now if i click on this it's going to show us all of their stuff right here
11:26:08
como nos dará el id, el título y también la descripción y tenemos algunas cosas más como
like it's going to give us the id the title and also the description and we have a few more things like
11:26:15
porcentaje de descuento y así sucesivamente, así que para
discount percentage and so on and so forth so for
11:26:18
todos esos datos vamos a crear un tipo de producto, está bien.
all of that data we are going to be creating a product type okay
11:26:21
así que para hacer eso voy a usar como primero tenemos que ir
so to do that i'm going to be using like first of all we have to go
11:26:24
adelante y crear nuestro tipo justo aquí así que no voy a
ahead and create our type right here so i'm not
11:26:27
perder mucho de su tiempo pero solo crearemos este tipo
going to waste a lot of your time but we will just create this type
11:26:30
justo aquí así que primero tenemos un tipo de producto va a tener el id título descripción precio porcentaje de descuento calificación stock marca categoría miniatura e imágenes
right here so first of all we have a product type it's going to have the id title description price discount percentage rating stock brand category thumbnail and images
11:26:40
ok así que estos son todos los datos que vamos a estar usando
okay so these are all of the data that we are going to be using
11:26:43
dentro de nuestra aplicación así que por eso ahora hemos creado con éxito
inside our app so that's why we now successfully created
11:26:46
un tipo para eso así que ahora podemos anotar nuestro strad usando su
a type for that so we can now annotate our strad by using their
11:26:49
tipo así que solo pondré un tipo o nulo y
type so i'll just put a type or null and
11:26:52
ahora que eso está hecho lo siguiente que quiero hacer es que quiero renderizar todos
now that's done the next thing that i want to do is that i want to render all of
11:26:56
los datos justo aquí dentro de mi interfaz de usuario así que para renderizar eso primero
the data right here inside my ui so to render that first
11:26:59
de todo vamos a estar verificando si ya tienes los datos o no
of all we are going to be checking like if you already have the data or not
11:27:02
así que si tienes los datos en esta situación vamos a estar renderizando
so if you have the data in this situation we are going to be rendering
11:27:05
nuestros datos pero si no tienes los datos vamos a
our data but if you don't have the data we are going
11:27:08
estar usando un párrafo vamos vamos a usar nuestro párrafo
to be using a a paragraph come on let's just use our paragraph
11:27:11
y dentro de este párrafo seleccionarás cargando punto punto
and inside this paragraph you will select loading dot dot
11:27:14
punto ok y también voy a cerrar mi párrafo justo aquí
dot okay and i'm going to also close my paragraph right here
11:27:17
ok así que si tenemos los datos así que en esta situación qué debo
okay so if we have the data so in this situation what do i
11:27:20
hacer voy a crear aquí otro div y ahora dentro de este
have to do i'm going to create here another div and now inside this
11:27:24
div vamos a estar renderizando todo nuestro contenido así que solo usaré
div we're going to be rendering all of our content so i'll just use
11:27:27
como párrafo y este párrafo tendrá el id y usaremos como data.id básicamente también puedes renderizar tus datos o desestructurar tus datos justo aquí si quisieras, pero no lo haré.
like paragraph and this paragraph will have the id and we will use like data.id basically you can also render your data or destructure your data right here if you wanted to, but I'm not going to.
11:27:38
voy a avanzar el video porque esto es solo un asunto de interfaz de usuario y podemos hacerlo un poco más rápido. Así que solo usaré como data.title.
I'm going to fast forward the video because this is just a UI stuff and we can totally do that a bit quickly. So I'll just use like data.title.
11:28:12
ahora si guardo mi archivo y reviso esto así que aquí puedes ver que tenemos
now if i save my file and check this out so here you can see we
11:28:15
nuestro id tenemos el título precio el descuento
have our id we have the title price the discount
11:28:18
y así sucesivamente y también tenemos nuestra miniatura justo
and so on and so forth and we also have our thumbnail right
11:28:21
aquí así que la cual puedo copiar y colocar allí aquí está
here so which i can copy and place there here it's
11:28:24
nos va a dar la miniatura de nuestro producto, así que si quieres entrar en
going to give us the thumbnail of our product so if you want to go into like
11:28:28
otro producto, podemos simplemente elegir el segundo, guardar
another product so we can just choose like second one save
11:28:31
nuestro archivo y refrescar esto, así que ahora nos va a dar los datos actualizados
our file and refresh this so now is going to give us the updated data
11:28:34
puedo copiar eso, puedo renderizar allí si quisiera
i can totally copy that i can totally render there if i wanted to
11:28:37
pero sabes qué, supongo que eso se verá mejor, así que
but you know what i guess that's going to look better so
11:28:40
sí, así es como vamos a proporcionar un tipo o así es como vamos a
yeah this is how we're going to be providing a type or this is how we're
11:28:43
crear un tipo para o usar efecto, así que
going to be creating a type for or use effect so
11:28:47
ahora vamos a estar usando tailwind css dentro de tu proyecto de react.js, así que si no saben qué es tailwind css, tengo un curso completo allí que es de casi cuatro horas de contenido
now we are going to be using a tailwind css inside your react.js project so if you guys don't know what a tailwind css is i have a complete course on there which is about like almost four hour of content
11:28:59
además, también vas a construir tres increíbles proyectos responsivos
plus you are going to be also building three amazing responsive projects
11:29:02
así que si te importa aprender tailwind css, yo
so if you care about learning tailwind css i
11:29:06
prometo que este va a ser el mejor curso para ti, así que ahora vamos a ello
promise this is going to be the best course for you so now let's get into it
11:29:09
como vamos a estar usando tailwind css dentro de nuestro
like how we are going to be using tailwind css inside our
11:29:12
proyecto de react.js, así que para hacer eso, primero voy a hacer clic en
react.js project so to do that first of all i'm going to just click on
11:29:15
este botón de empezar, luego voy a ir a las guías del marco
this getting started button then i'm going to go into the framework guides
11:29:18
ahora vamos a elegir wheat y si quieres elegir algún otro
now we are going to be choosing wheat and if you want to choose some other
11:29:21
marco, eres más que bienvenido a usarlo, yo solo voy a elegir wheat
framework you are more than welcome to use there i'm going to just choose wheat
11:29:25
justo aquí, así que lo primero que tenemos que hacer es que tenemos que crear
right here so the first thing that we have to do is that we have to create
11:29:28
nuestro proyecto de lectura, así que voy a copiar eso de aquí y ahora voy a abrir
our read project so i'm going to copy there from here and now i'm going to open
11:29:31
mi terminal justo aquí, solo haré clic derecho en esto, va a pasar
my terminal right here i'll just right click on this it's going to pass
11:29:34
mi comando justo aquí, primero vamos a usar como npx
my command right here first of all we are going to be using like npx
11:29:37
crear proyecto de lectura y solo le voy a dar el nombre de como mi
create read project and i'm going to just give it the name of like my
11:29:40
proyecto y vamos a estar usando la plantilla de react.js, así que ahora tú
project and we're going to be using the react.js template so now you
11:29:44
quieres entrar en su proyecto usando un comando cd, ahora estoy dentro de su proyecto, voy a usar como npm i, solo usemos npm i, así que va a instalar todos sus paquetes de los que depende react.js justo aquí.
want to go into their project by using a cd command now i'm inside their project i'm going to use like npm i let's just use npm i so it's going to install all of their packages by which will react.js is depends on right here.
11:29:55
Mientras hace su trabajo, también voy a copiar eso.
While it's doing its thing, I'm going to also copy there.
11:29:58
Así que va a instalar algunas cosas como tailwind css post
So it's going to install a few things like tellman css post
11:30:01
css y también auto prefixer, también va a inicializar
css and also auto prefixer it's going to also initialize
11:30:05
nuestro css tellman dentro de nuestro proyecto, así que ahora eso está
our tellman css inside our project okay so now that's
11:30:08
hecho con éxito, voy a copiarlo una vez más
successfully done i'm going to just copy there once again
11:30:11
déjame colocarlo aquí y finalmente tenemos que inicializar
now let me place it right here and finally we have to initialize
11:30:14
nuestro css tellman dentro de su proyecto usando npx
our tellman css inside their project by just using npx
11:30:18
tellman css init -p, así que voy a presionar enter, así que
tellman css init dash p so i'm going to just hit enter so going
11:30:21
para inicializar mi tailwind css aquí y voy a abrir eso
to initialize my tailwind css right here and i'm going to open that
11:30:24
usando mi vs code, así que ahora dentro de ahí
by using my vs code so now inside there we
11:30:27
tenemos que ir a nuestro archivo tailwind config.js, así que
have to go into our tailwind config.js file so
11:30:30
voy a copiarlo y colocarlo aquí, así que ahora estamos dentro de este
i'll just copy there and place it right here so now we are inside this
11:30:33
archivo tailwind config.js, así que tenemos que reemplazar esto
tailwind config.js file so we have to replace this
11:30:36
contenido con este aquí, está bien
content with this one right here okay
11:30:39
así que solo queremos proporcionar nuestro archivo index.html que
so we only want to provide our index.html file which
11:30:42
está dentro de este archivo rc y queremos seleccionar todas estas extensiones
is inside this rc file and we want to select like all of these extensions
11:30:46
aquí, está bien, así que solo tenemos que reemplazar y también tenemos que
right here okay so we just have to replace and also we have to
11:30:49
ir a nuestro archivo index.css, voy a copiar eso de
go into our index.css file i'm going to copy that from
11:30:52
aquí y ahora déjame ir a mi archivo index.css
here and now let me just go into my index.css file
11:30:55
voy a seleccionar cada cosa y reemplazar eso con estos
i'm going to select every single thing and replace that with these
11:30:58
estas tres directivas aquí, ahora finalmente voy a copiar esto
these three directives right here now finally i'm going to copy this
11:31:01
h1 y voy a ir a mi app no
h1 and i'm going to go into my app not
11:31:05
app.css, sino app.jsx y voy a
app.css but app.jsx and i'm going to
11:31:08
eliminar todo de allí, solo usaré mi rafce
remove every single thing from there i'll just use my rafce
11:31:11
y reemplazar su div con este h1, así que voy a enviar
and replace their div with this h1 so i'm going to send
11:31:14
mi archivo, ahora déjame usar mi npm run dev para
my file now let me use my npm run dev so to
11:31:17
iniciar mi servidor, así que aquí puedes ver que ahora estamos obteniendo el estilo, así que
start my server so here you can see we're now getting the styling so
11:31:20
ahora lo que voy a hacer es que voy a entrar en los componentes que voy a
now what i'm going to do is that i'm going to go into the components that i'm going
11:31:23
ir al componente de navegación y ahora solo voy a
to go to the browse component and now i'm going to just
11:31:26
elegir este componente aquí, está bien, así que podemos copiar totalmente el
choose this component right here okay so we can totally copy the
11:31:29
código html, solo voy a seleccionar algunas cosas como tal vez estoy
html code i'm going to just select a few things like maybe i'm
11:31:33
solo voy a seleccionar este dev aquí y copiar allí porque
going to just select this dev right here and copy there because
11:31:36
solo quiero probar mi código, así que solo lo quitaré de aquí y
i just want to test my code so i'll just remove that from here and
11:31:39
colocaré este dev aquí, guardaré mi archivo, mira esto
place this dev right here save my file check this out
11:31:42
actualiza allí y no estamos obteniendo nada, oh
refresh there and we're not getting anything oh
11:31:46
eso es porque estamos usando una clase en lugar de un nombre de clase, así que tenemos
that's because we are using a class instead of class name so we have
11:31:49
que seleccionar todo eso y cambiarlo al nombre de la clase
to select all of there and change that to the class
11:31:52
en su lugar, así que si guardo mi archivo y ahora actualizo allí
name instead so if i save my file and now refresh there
11:31:55
y tiene la clase de aquí, así que solo voy a quitar allí, guardar
and it has the class of here and so i'm going to just remove there save
11:31:58
mi archivo y aquí puedes ver que ahora estamos obteniendo este tipo
my file and here you can see we are now getting these kind
11:32:02
de componente, no se ven tan bien, pero
of a component they are not looking that great but
11:32:05
sí, confía en mí, puedes hacer muchas cosas locas con tailwind css y
yeah trust me you can do a lot of crazy stuff with telman css and
11:32:08
tengo un curso completo sobre eso y si quieres verlo aquí
i have a complete course on there and if you want to check there out here
11:32:11
está bien, así que sí, así es como vamos a estar
it is okay so yeah this is how we are going to be
11:32:14
usando tailwind css dentro de nuestros proyectos, está bien, así que
using a tailwind css inside our projects okay so
11:32:18
es hora de otro desafío y supongo que ese va a ser el desafío final
time for another challenge and i guess that's going to be the final challenge
11:32:21
para nuestra serie de react json typescript, así que
for our react json typescript series so
11:32:24
lo que tienes que hacer es que tienes que obtener tus datos de este json placeholder
what you have to do is that you have to fetch your data from this json placeholder
11:32:27
escribe un código y este endpoint te dará un
dot type a code and this endpoint will give you a
11:32:30
montón de usuarios, así que te dará la estructura de datos del usuario
lot of users so it's going to give you the user
11:32:34
así como esta, vas a tener el id, un id será
data structure like this you're going to have the id an id will
11:32:37
un número, luego tendrás un nombre, el nombre será una cadena, el nombre de usuario será
be a number then you you will have a name name will be a string username will
11:32:40
ser una cadena el correo será una cadena y el teléfono también será una cadena así que
be a string email will be a string and phone will be also a string so
11:32:43
usa el efecto para obtener los datos usa el estado para
use the use effect to fetch the data use the use state to
11:32:46
almacenar esos datos y luego finalmente solo renderiza en
store that data and then finally just render in
11:32:49
una especie de tabla o algo así así que dale lo mejor de ti
some sort of a table or something like that so give it your best shot
11:32:52
si puedes hacerlo está completamente bien entonces vuelve y mira la solución
if you can do it that's completely okay then come back and watch the solution
11:32:56
y aquí está mi solución así que solo voy a crear mi maldita lista de usuarios.tsx y voy a usar mi
and here is my solution so i'm going to just create my what the hell user list.tsx and i'm going to use my
11:33:05
archivo semi rafce ve a mi aplicación y
rafce semi file go to my app and
11:33:08
renderizarlos aquí como lista de usuarios como
render them right here like user list like
11:33:11
así que está bien así que lo primero que quiero
so okay so the first thing that i want to
11:33:14
hacer es que quiero crear algunas estadísticas así que vamos a crear un
do is that i want to create a few stats so we are going to be creating a
11:33:17
estadística para los usuarios así y también el
stat for the users like so and also the
11:33:20
establecer usuarios y va a ser igual a la estadística utilizada y el valor inicial
set users and it's going to be equals to the used stat and the initial value
11:33:23
se establecerá en un arreglo vacío está bien así que solo vamos a
will be set to empty array okay so let's just
11:33:26
crear una interfaz para este arreglo voy a colocar esta interfaz aquí así que tenemos nuestro usuario y tenemos el id que
create an interface for this array i'm going to place this interface right here so we have our user and we have the id which
11:33:33
se establecerá en número y el resto de las cosas se establecerán en cadena así que
will be set to number and the rest of the stuff will be set to string so
11:33:36
vamos a anotar nuestra estadística usando este usuario y
we're going to be annotating our stat by using this user and
11:33:39
tenemos que proporcionar nuestro arreglo dentro de ahí así que
we have to provide our array inside there like so
11:33:42
y tenemos que cerrarlo ahora debajo de eso tenemos que usar
and we have to close there now underneath that we have to use
11:33:45
nuestro loading y luego establecer loading y va a ser igual a
our loading and then set loading and it's going to be equals to
11:33:48
la estadística utilizada y el valor inicial se establecerá en verdadero y
the use stat and the initial value will be set to true and
11:33:52
también tenemos que anotar eso como un booleano porque estamos ordenando el valor de booleano dentro de ahí ahora finalmente tenemos
we also have to annotate that as a boolean because we are sorting the value of boolean inside there now finally we
11:33:58
también tenemos que crear uno para el error y eso se va a establecer en el set error
also have to create one for the error and that's going to be set to the set error
11:34:02
y tenemos que usar nuestro estado una vez más y el
and we have to use our use state one more time and the
11:34:05
valor inicial se establecerá en no está bien así que lo anotaré como
initial value will be set to no okay so i'll annotate that like
11:34:08
va a ser ya sea una cadena o no está bien y
it's going to be either a string or no okay and
11:34:11
tenemos que cerrar esto, así que eso va a estar en estado avanzado ahora tenemos
we have to close this so that's going to be at forward state now we have
11:34:14
que obtener nuestros datos utilizando el efecto de uso, así que voy a estar usando como
to fetch our data by using the use effect so i'm going to be using like
11:34:17
efecto de uso y aquí tenemos que especificar nuestra función de callback y para esta función de callback vamos a proporcionar nuestro array de dependencias vacío y también vamos a crear un
use effect and here we have to specify our callback function and for this callback function we're going to be providing our empty dependency array and we are going to be also creating a
11:34:26
función que nos permite obtener los usuarios así
function which allows us to fetch the users like so
11:34:29
y esto puede ser una función asincrónica y dentro de esta función
and this can be an asynchronous function and inside this function
11:34:32
vamos a estar usando nuestros bloques de try y catch para el catch vamos a usar como
we're going to be using our try and catch blocks for the catch we'll be using like
11:34:36
establecer error y tenemos que proporcionar nuestra instancia de error
set error and we have to provide our error an instance
11:34:39
de venga, ese error será la instancia
of come on that error will be the instance
11:34:43
de error, si ese es el caso, vamos
of error if that's the case we're
11:34:46
a obtener como error punto mensaje de eso, pero si ese no es el caso, solo vamos a decir que ocurrió un error, así que vamos
going to be getting like error dot message out of that but if that's not the case we're going to be just saying like an error occurred like so we're going
11:34:54
también vamos a proporcionar el estado final, finalmente, y para el finalmente vamos a establecer la carga
we are going to be also providing the finally state finally and for the finally we are going to be setting the loading
11:35:00
en falso, está bien, y ahora déjame encargarme del bloque try
to false okay and now let me take care of the try block
11:35:03
así que para el bloque try, primero vamos a obtener nuestros datos mediante
so for the try block first of all we are going to be fetching our data by
11:35:07
el uso de la API fetch y voy a especificar
using the fetch api and i'm going to specify
11:35:10
esta URL dentro de ahí y déjame solo lanzar algún tipo
this url inside there and let me just throw in some sort
11:35:13
de variable como respuesta, respuesta así y
of variable like response response like so and
11:35:16
también voy a verificar si no tenemos la respuesta, si la respuesta no está bien, así que en esa situación vamos
i'm going to also check if we don't have the response if the response is not okay so in that situation we are
11:35:23
a lanzar un nuevo error que dirá como
going to be throwing a new error which will say like
11:35:26
la respuesta de la red no estaba bien
network response was not okay
11:35:30
y si ese no es el caso, vamos a obtener nuestros datos
and if that's not the case we're going to be getting our data
11:35:33
así que usaré como const data y vamos a estar anotando
so i'll use like const data and we're going to be annotating
11:35:36
ahí usando nuestro usuario así y
there by using our user like so and
11:35:40
va a venir de la espera y luego response.json y tenemos que convertir nuestros datos a la respuesta json, también tenemos que empujar nuestros datos
it's going to be coming from the await and then response.json and we have to convert our data to the json response we also have to push our data
11:35:48
a nuestros usuarios, así que vamos a estar usando como set users y
to our users so we're going to be using like set users and
11:35:51
simplemente empujemos nuestros datos dentro de ahí, así que ahora eso es todo lo que has
let's just push our data inside there so now that's all you're
11:35:54
hecho, así que voy a ocultar o sabes que también tenemos que llamar a esta función
done so i'm going to hide or you know what we also have to call this function
11:35:57
dentro de ahí así y ahora
inside there like so and now
11:36:01
tenemos que ocultar este efecto de uso, ahora voy a estar verificando así que
we have to hide this use effect now i'm going to be checking so
11:36:04
si está cargando, así que en esta situación vamos
if loading so in this situation we're
11:36:07
a estar devolviendo o más bajo, así que solo escribiré como div o también puedo escribir h1 que dirá como cargando punto punto punto y también podemos duplicar
going to be returning or lower so i'll just write like div or i can also write h1 which will say like loading dot dot dot and we can also duplicate
11:36:16
ahí y cambiar ahí al error así que
at there and change there to the error so
11:36:19
solo cambiaré ahí al error así que voy a renderizar también
i'll just change there to the error like so so i'm going to also render
11:36:22
mi error dentro de ahí y aquí tenemos que escribir un error
my error inside there and here we have to just write an error
11:36:25
así que si tienes algún tipo de error, lo vamos a mostrar ahí
so if you have some sort of an error we're going to be displaying there
11:36:28
ahora para la interfaz de usuario, voy a eliminar esta lista de usuarios de
now for the ui i'm going to remove this user list from
11:36:31
aquí y voy a tener que cambiar ahí a una tabla y también
here and i'm going to have to change there to a table and also
11:36:34
cambiar este div a la tabla y dentro de esta tabla vamos a definir nuestro t head, está bien, y dentro de este t head
change this div to the table and inside this table we are going to be defining our t head okay and inside this t head
11:36:41
tenemos que definir nuestro tr dentro de este tr vamos a definir
we have to define our tr inside this tr we're going to be defining
11:36:44
nuestro th con el nombre, déjame duplicar ahí un poco
our th with the name let me just duplicate there a few
11:36:47
también tenemos que escribir un nombre de usuario y también
time we also have to write a username and we also
11:36:51
tenemos que escribir el correo electrónico y finalmente tenemos que escribir el
have to write the email and finally we have to write the
11:36:54
teléfono, vamos, teléfono así y debajo
phone come on phone like so and underneath
11:36:57
de este t head tenemos que escribir nuestro t body
this t head we have to write our t body
11:37:00
y dentro de este t body vamos a estar iterando sobre todos los usuarios usando este mapa, va a tomar al usuario como un, sí, como un parámetro y aquí tenemos
and inside this t body we are going to be iterating over to all of the users by using this map it's going to take the user as a yeah as a perimeter and here we have
11:37:09
especifica tu tr y para este tr vamos a
specify your tr and for this tr we're going to
11:37:12
también proporcionar una clave que será un user.id y
be also providing a key which will be a user.id and
11:37:15
aquí también tenemos que usar nuestro td para renderizar nuestro elemento, así que
here we also have to use our td to render our element so
11:37:18
usa como user.name y también voy a solo
use like user.name and also i'm going to just
11:37:21
duplicar eso unas cuantas veces, cambiar ahí al nombre
duplicate that a few times change there to the name
11:37:25
sí, sabes que ese era el usuario
yeah you know what that was the user
11:37:28
id y este va a ser el nombre y también tenemos que cambiar allí al nombre de usuario y cambiar este a el correo electrónico y finalmente cambiar este a el teléfono
id and this is going to be the name and we also have to change there to the username and change this one to the email and finally change this one to the phone
11:37:37
ahora déjame guardar mi archivo y revisar esto, así que aquí puedes ver que ahora estamos obteniendo el
now let me save my file and check this out so here you can see we are now getting the
11:37:42
nombre, no debería ser el nombre, también tenemos que proporcionar el id, así que simplemente duplicamos eso, cambiamos eso a id, ahora estamos obteniendo
name it shouldn't be the name we also have to provide the id so let's just duplicate that change that to id now we are getting
11:38:02
así que ahora hablemos sobre daisy ui, ¿qué es un daisy ui y
so now let's talk about the daisy ui so what is a daisy ui and
11:38:05
cómo vamos a usarlos con react.js, como puedes
how are we going to be using them with react.js as you
11:38:08
ver aquí en su página de inicio, están diciendo que este ui es la biblioteca de componentes más popular para tailwind css, si ya saben qué es tailwind css
can see right here on their landing page they are saying like this ui is the most popular component library for telman css if you guys already know what a telman css is
11:38:17
les encantará este ui, así que pueden
you will love this ui so you can
11:38:20
elegir diferentes temas si quieren, como oscuro y tenemos un cupcake
choose different themes if you wanted to like dark and we have a cupcake
11:38:23
y así sucesivamente, tema, está bien, así que en mi caso voy a
and so on and so forth theme okay so in my case i'm
11:38:26
elegir solo este tema oscuro aquí y dentro de su página de inicio
going to only choose this dark theme right here and inside their landing
11:38:30
puedes aprender más sobre eso, como en lugar de escribir todas estas
page you can learn more about that like instead of writing all of these
11:38:33
clases de CSS de tailwind, ya no tienes que escribir todas las
10-man CSS classes you no longer have to write all of
11:38:36
clases de CSS de tailwind, ahora puedes usar daisy para
these 10-man CSS classes now you can use desu to
11:38:39
escribir solo unas pocas clases, te dará el mismo
only write a few classes it will give you the same
11:38:42
resultado aquí, está bien, así que puedes elegir diferentes tipos
result right here okay so you can choose different kind
11:38:45
de temas, puedes elegir muchas cosas dentro de daisy
of themes you can choose a lot of things inside the desu
11:38:49
y si quieren que haga un curso separado sobre daisy
and if you guys want me to make a separate course on desu
11:38:52
puedo hacerlo totalmente o tal vez un curso intensivo y quiero
i can totally do that or maybe a crash course and i
11:38:55
que noten esta animación, estos son los temas que pueden
want you to notice this animation these are the themes that you
11:38:58
elegir de daisy y si quieren aprender allí
can choose from the desu and if you want to learn there
11:39:01
como dije, pueden aprenderlo de su documentación
as i said you can either learn it from their documentation
11:39:04
o si quieren que haga un curso separado sobre eso, puedo
or if you want me to make a separate course on there i
11:39:07
hacer un curso sobre eso, pero ahora hablemos sobre cómo vamos a
can totally make a course on there but now let's talk about how we are going to be
11:39:10
usar eso, solo tenemos que ejecutar este
using there to use that we only have to run this
11:39:13
comando aquí y también justo allí, pero primero de
command right here and also just right there but first of
11:39:17
todo lo que tenemos que hacer es configurar tailwind css así que voy a entrar en
all we have to make a tailwind css setup so i'm going to go into
11:39:20
tailwind css aquí y voy a ir a mi marco
the tailwind css right here and i'm going to go to my framework
11:39:23
guías una vez más luego elegiré el ancho y voy a copiar allí y abriré mi terminal aquí voy a colocar este comando pero también voy a cambiar el nombre de eso a algo más, dui estaría bien
guides one more time then i'll choose the width and i'm going to copy there and i'll open my terminal right here i'm going to place this command but i'm going to also change the name of that like something else dui would be fine
11:39:35
y voy a presionar enter ahora mismo luego voy a entrar en mi dui
and i'm going to hit enter right now then i'm going to go into my dui
11:39:38
componente y ahora solo voy a usar npm i para instalar
component and now i'm going to just use npm i to install
11:39:42
todos los paquetes ahora voy a abrir eso en mi vs code y luego voy a instalar todos sus otros paquetes y cosas así que ahora es el momento de instalar
all of the packages now i'm going to open that in my vs code and then i'm going to install all of their other packages and stuff so now it's time to install
11:39:49
daisyui dentro de nuestro proyecto así que voy a copiar eso y ahora déjame abrir mi terminal aquí y déjame colocar este comando que es npm i y luego daisyui en la última versión así que va a Mr.
daisyui inside our project so i'm going to copy that and now let me just open my terminal right here and let me just place this command which is npm i and then daisyui at latest so it's going to Mr.
11:39:59
Desi.
Desi.
11:40:00
dentro de nuestros proyectos ahora están exitosamente terminados ahora voy a
inside our projects now they're successfully done now i'm
11:40:03
seleccionar el esm y voy a copiar este comando justo
going to select the esm and i'm going to copy this command right
11:40:06
aquí primero que nada sabes déjame copiar la importación y
here first of all you know let me just copy the import and
11:40:09
luego iremos al archivo tailwind config.js que es
then we will go into the tailwind config.js file which is
11:40:12
este tailwind vamos, ¿dónde está?
this tailwind come on where in the world is okay
11:40:16
así que solo usaré oh olvidé instalar mi
so i'll just use oh i forgot to install my
11:40:19
tailwind css instalé este pero olvidé instalar mi tailwind css así que voy a copiar allí y ahora déjame ejecutar este comando aquí así que es
tailwind css i installed this one but i forgot to install my tailwind css so i'm going to copy there and now let me run this command right here so it's
11:40:26
va a instalar y configurar mi tailwind css dentro de mi proyecto
going to install and configure my tailwind css inside my project
11:40:29
déjame presionar enter así que va a inicializar mi tailwind css justo
let me just hit enter so it's going to initialize my tailwind css right
11:40:32
aquí ahora luego exitosamente hecho y también tenemos
here now then successfully done and we also have
11:40:35
copiar allí tenemos que ir a nuestra configuración de tailwind
to copy there we have to go into our tailwind config
11:40:38
colocar allí justo aquí guardar mi archivo y
place there right here save my file and
11:40:41
también tenemos que copiar estos ir a nuestro index.css
we also have to copy these go to our index.css
11:40:45
archivo y reemplazarlo con este componente y sí, hemos terminado totalmente con el tailwind css pero también tenemos que copiar allí ahora tenemos que ir a nuestro
file and replace it with this component and yeah we are totally done with the tailwind css but we also have to copy there now we have to go into our
11:40:53
archivo tailwindconfig.js que es este archivo y voy a
tailwindconfig.js file which is this file and i'm going to
11:40:56
simplemente colocarlo aquí y también déjame
just place it right here and also let me just
11:40:59
copiar este desi ui tenemos que ir dentro de los plugins y
copy this desi ui we have to go inside the plugins and
11:41:03
simplemente colócalo aquí y ahora tenemos que usar algún tipo de componente
just place it right here and now we have to use some sort of a component
11:41:06
así que simplemente iré a los componentes y en este caso
so i'll just go ahead and go to the components and in this case
11:41:09
voy a ir a los botones y simplemente copiaré el
i'm going to go to the buttons and i'll just copy the
11:41:13
código para eso, así que tal vez voy
code for that so maybe i'm going
11:41:16
a ir a este y copiar el código jsx de allí, simplemente copiemos, ahora voy a entrar en mi src
to go to this one and copy the jsx code from there let's just copy there now i'm going to go into my src
11:41:23
carpeta, luego mi carpeta de componente de aplicación, así que simplemente reemplazaré
folder then my app component folder so i'll just replace
11:41:26
esto con mi rfce y eliminaré este div o
it with my rfce and remove this div or
11:41:29
sabes qué, simplemente vamos a eliminar la aplicación y voy a
you know what we're going to be just removing the app and i'm going
11:41:32
simplemente colocar todo mi código aquí, así que si guardo mi archivo ahora, dejemos
to just place all of my code right here so if i save my file now let
11:41:35
que ejecute mi npm run dev, así que se va a ejecutar allí, justo aquí y aquí
me run my npm run dev so it's going to run there right here and here
11:41:39
puedes ver que ahora estamos obteniendo todos estos botones como solo un botón simple
you can see we are now getting all of these buttons like just a simple button
11:41:42
y tenemos un botón neutral, primario, secundario y luego
and we have a neutral primary secondary s and then
11:41:45
fantasma y así sucesivamente, botón justo aquí, podemos continuar y
ghost and so on and so forth button right here we can go ahead and
11:41:48
hacer muchas cosas aquí, como obtener el modelo si quisieras
do lots of stuff right here like we can get the model if you wanted
11:41:51
podemos obtener las grabaciones si quisieras, podemos hacer
to we can get the recordings if you wanted to we can do
11:41:54
una gran variedad de cosas, como si hago clic allí, podemos obtener este modelo
a lot sort of stuff like if i click on there we can get this model
11:41:57
así que voy a copiar todo este código y ahora déjame
so i'm going to just copy all of this code and now let me just
11:42:00
reemplazar eso con este código justo aquí, así que
replace that with this code right here so
11:42:03
si guardo mi archivo ahora, si voy allí y hago clic
if i save my file now if i go there click
11:42:07
allí, ahora estamos obteniendo nuestro modelo, así que sí, así es como vamos a usar un daisy ui dentro de nuestros proyectos de react.js, ahora vamos a
on there we are now getting our model so yeah this is how we are going to be using a daisy ui inside or react.js projects now let's
11:42:14
usar otra biblioteca de componentes que se llama redix dentro
use another component library which is called redix inside
11:42:18
de tu proyecto de react js, así que aquí puedes ver que redix es un código abierto
your react js project so here you can see redix is an open source
11:42:21
biblioteca de componentes optimizada para un desarrollo rápido, fácil
component library optimized for fast development easy
11:42:24
mantenimiento y accesibilidad, simplemente importa y
maintenance and accessibility just import and
11:42:27
continúa, así que aquí están las demostraciones en vivo, así que estos son
go on so here are the live demos so these are
11:42:30
la cantidad de cosas que puedes hacer utilizando la biblioteca de componentes Redix, así que estos son solo los temas, también puedes ir a los primitivos, podemos revisar los íconos, también podemos ir a los colores
the amount of things that you can do by using the redix component library so these are just the themes you can also go to the primitives we can check out the icons we can also go to the colors
11:42:41
y hay muchas cosas sucediendo, así que voy a entrar en
and there are a lot of stuff going on so I'm going to go into
11:42:44
mi Redix una vez más y ahora para instalar, lo primero que
my Redix one more time and now to install there the first thing
11:42:47
tenemos que hacer es que tenemos que hacer una configuración de ReactJS y ahora dejame
that we have to do is that we have to make a ReactJS setup and now let
11:42:50
mostrarte cómo vamos a hacer esto, así que solo abriré mi terminal aquí
me show you how we are going to be doing this so I'll just open my terminal right here
11:42:53
y voy a escribir npm create read y
and I'm going to write npm create read and
11:42:56
último y si presiono enter, me va a preguntar por
latest and if I hit enter so it's going to ask me for
11:43:00
el nombre, le voy a dar el nombre de un proyecto Redix
the name I'm going to give it the name of like Redix project
11:43:03
o demo estaría bien, solo le daré el nombre de demo Redix, voy a elegir ReactJS como marco y JavaScript, voy a entrar en el red X y voy a abrir eso en mi VS code.
or demo would be fine I'll just give it the name of like Redix demo I'm going to choose ReactJS as a framework and JavaScript I'm going to go into the red X and I'm going to open that in my VS code.
11:43:13
Déjame abrir mi terminal integrada y voy a usar NPM I para instalar todos mis paquetes.
Let me open my integrated terminal and I'm going to use NPM I to install all of my packages.
11:43:18
Así que ahora, mientras hace eso, voy a hacer clic en este botón de empezar. Y aquí puedes ver cómo vamos a instalar eso.
So now while it's doing that, I'm going to click on this getting start button. And here you can see this is how we are going to be installing there.
11:43:25
Así que solo tenemos que copiar este comando. Voy a copiar este comando aquí. Y ahora han terminado exitosamente.
So we just have to copy this command. I'm going to copy this command right here. And now they're successfully done.
11:43:30
Así que voy a pegar este comando aquí y presionar enter. Está bien. Así que mientras hace eso, voy a entrar en mi componente principal global.
So I'm going to just paste this command here and hit enter. Okay. So while it's doing that, I'm going to go into my global main component.
11:43:37
Y voy a colocar este comando aquí. Así que voy a copiar allí. ahora
And I'm going to just place this command right here. So I'm going to copy there. now
11:43:40
está haciendo su trabajo y ahora han terminado exitosamente, así que
it is doing its thing and now they're successfully done so
11:43:43
voy a entrar en mi componente principal y dentro de este componente principal estoy
i'll go into my main component and inside this main component i'm
11:43:47
también voy a importar el experto rojo aquí, así que solo los guardaré
going to also import the red expert here so i'll just save them
11:43:50
a continuación, tenemos que ir a nuestro componente principal y tenemos que
next we have to go into our main component and we have to
11:43:53
usar nuestro contexto de tema, así que voy a copiarlo de aquí y ahora también lo voy a importar aquí, está bien, así que solo importemos eso, voy a envolver toda mi aplicación usando este contexto de tema así
use our theme context so i'm going to copy it from here and now i'm going to also import there right here okay so let's just import that i'm going to wrap my entire application by using this theme context like so
11:44:05
está bien, así que solo cerremos eso, presionemos enter y envolvamos toda mi aplicación
okay so let's just close there hit enter and wrap my entire application
11:44:08
usando este contexto, así que si solo elimino eso, siguiente
by using this context so if i just remove that next
11:44:12
tenemos que usar algún tipo de componente, así que solo copiaré este componente de
we have to use then some sort of a component so i'll just copy this component from
11:44:15
aquí y voy a entrar en mi componente de aplicación y
here and i'm going to go into my app component and
11:44:18
solo eliminaré cada cosa de allí y voy a usar mi rafce
i'll just remove every single thing from there and i'm going to use my rafce
11:44:21
o sabes qué, déjame colocar este componente aquí, cortarlo de aquí, usarlo aquí, voy a usar mi aplicación, copiar allí y solo cambiar
or you know what let me just place this component right here cut that from here use the right here i'm going to use my app copy there and just change
11:44:29
el nombre de mi función a app así que si guardo mi archivo y
the name of my function to app so if i save my file and
11:44:33
ahora voy a usar npm run dev para iniciar mi servidor y
now i'm going to use npm run dev to start my server and
11:44:36
aquí puedes ver que estamos obteniendo este resultado aquí que dice hola
here you can see we are getting this result right here which is saying like hello
11:44:39
del tema redx y supongo que no estamos obteniendo
from the redx theme and i guess we are not getting
11:44:42
un resultado tan genial, eso es porque ahora estamos obteniendo estas cosas
that much cool result that's because we are now getting these stuff
11:44:45
aquí así que voy a eliminar cada cosa del app.css y
right here so i'm going to remove every single thing from the app.css and
11:44:49
ahora déjame refrescarlos, también voy a eliminar cada cosa
now let me just refresh them i'm going to also remove every single thing
11:44:52
del index.css también y ahora si solo refresco esto
from the index.css as well and now if i just refresh this
11:44:55
hola de los temas redx y vamos, está bien
hello from the redx themes and let's go okay
11:44:58
así que así es como vamos a usar un redix dentro de nuestro
so this is how we are going to be using a redix inside our
11:45:01
proyecto de react.js ahora hablemos sobre el componente de copia y pega
react.js project now let's talk about the copy pasta component
11:45:05
la biblioteca que se llama shared send ui y
library which is called the shared send ui and
11:45:08
shared send ui es de lejos la más popular y
shared send ui is by far the most popular and
11:45:12
la biblioteca de interfaz de usuario más poderosa del front end, así que para
the most powerful front end ui library so to
11:45:15
instalarlos y estoy pensando en hacer un curso allí, pero de todos modos, esa es otra historia, así que para instalarlos voy a hacer clic en este botón de comenzar aquí
install them and i'm thinking about making a course on there but anyways there's other story so to install them i'm going to just click on this getting started button right
11:45:22
entonces voy a ir a esta instalación y solo voy a elegir
here then i'm going to go into this installation and i'm going to just choose
11:45:25
leer aquí y primero tenemos que hacer una configuración así que voy a copiar
read right here and first of all we have to make a setup so i'm going to copy
11:45:29
desde aquí abrir mi terminal una vez más, ahora dentro
there from here open my terminal one more time now inside
11:45:32
de esta terminal voy a colocar este comando y presionar enter, estoy
this terminal i'm going to place this command and hit enter i'm
11:45:36
a punto de darle el nombre de como uh shared cn demos
going to give it the name of like uh shared cn demos
11:45:39
y ahora solo voy a elegir react jns y typescript ahora
and now i'm going to just choose react jns and typescript now
11:45:43
voy a entrar en mis shared cn demos y venir
i'm going to go into my shared cn demos and come
11:45:46
en cd y luego shared cn demos
on cd and then shared cn demos
11:45:49
y ahora déjame abrir allí justo aquí y voy a
and now let me just open there right here and I'm going
11:45:52
abrir mi terminal una vez más y usar npm i para instalar
to open my terminal one more time and use npm i to install
11:45:55
cada paquete individual lo siguiente que tenemos que hacer es instalar tailwind CSS
every single package the next thing that we have to do is that we have to install tailwind CSS
11:45:59
dentro de nuestro proyecto así que voy a copiar allí y ahora
inside our project so I'm going to copy there and now
11:46:02
tenemos que usar eso aquí mismo, está bien, así que eso está hecho, ahora dej
we have to use that right here okay so that's done now let
11:46:05
me colocar este comando aquí, así que va a tardar un poco en instalar tailwind
me place this command right here so it's going to take a bit of time to install tailwind
11:46:09
CSS post CSS y auto prefixer y también va a inicializar mi tailwind CSS aquí, lo cual es increíble, así que lo siguiente que tenemos que hacer es ir al archivo de configuración ts
CSS post CSS and auto prefixer and also it's going to initialize my tailwind CSS right here which is amazing so the next thing that we have to do is that we have to go into the ts config file
11:46:19
y voy a copiar allí, simplemente vamos a ir al tsconfig
and I'm going to copy there let's just go ahead and go to the tsconfig
11:46:22
así que solo proporcionaré una coma aquí, ahora déjame colocar mis opciones de compilador
so I'll just provide a comma here now let me just place my compiler options
11:46:26
y ahora déjame guardar allí y cerrar allí, siguiente
and now let me just save there and close there next
11:46:29
tenemos que ir a nuestro archivo tsconfig.app.json
we have to go into our tsconfig.app.json file
11:46:32
así que solo escribiré allí, presionaré enter y ahora dentro
so I'll just write there hit enter and now inside
11:46:36
allí solo tenemos que proporcionar esta uri base y también este camino, así que voy a copiar allí desde allí y ahora necesito esta omisión de verificación de biblioteca, voy a colocar mi comando aquí
there we only have to provide this base uri and also this path so I'm going to copy there from there and now I need this skip lib check I'm going to just place my command right
11:46:45
y ahora finalmente tenemos que instalar el tipo de typescript
here and now finally we have to install the typescript
11:46:48
así que voy a copiar allí y también tenemos que instalar allí
type so i'm going to copy there and we also have to install there
11:46:51
aquí dentro de nuestro proyecto
right here inside our project the
11:46:54
la siguiente cosa que tenemos que hacer es colocar todos ellos en nuestro
next thing that we have to do is we have to place all of them into our
11:46:57
archivo v.config.ts, así que voy a ir a mi
v.config.ts file so i'm going to go into my
11:47:00
v.ts o cualquier archivo y ahora déjame
v.ts or whatever file and now let me just
11:47:03
coloca todos ellos justo aquí guarda mi archivo y ahora nosotros
place all of them right here save my file and now we
11:47:06
tenemos que inicializar nuestra interfaz shadson así que voy a copiar allí ahora déjame abrir mi terminal y colocar este comando que
have to initialize our shadson ui so i'm going to copy there now let me open my terminal and place this command which
11:47:13
es enviar ui y inicializar allí y estamos obteniendo
is shared send ui and initialize there and we are getting
11:47:16
algún tipo de error no se encontró configuración de tailwind css
some sort of error no tailwind css configuration found
11:47:19
en esta ubicación es probable que no tengas tailwind css instalado
at this location it is likely you don't have tailwind css installed
11:47:22
o tengas una configuración inválida así que cómo
or have an invalid configuration so how
11:47:25
es eso siquiera posible configuramos cada uno oh allí
is that even possible we set up every single oh there
11:47:28
vamos así que tenemos que entrar en el no
we go so we have to go into the not
11:47:32
hijo compartido pero tailwind css tailwindcss.com y aquí voy a tener que copiar
shared son but tailwind css tailwindcss.com and here i'm gonna have to copy
11:47:38
este contenido y colocarlo allí justo aquí semi
this content and place there right here semi
11:47:42
archivo y también tenemos que copiar estos componentes y
file and we also have to copy these components and we
11:47:45
tenemos que ir al archivo index.css y colocar
have to go into the index.css file and place
11:47:48
allí aquí semi archivo y ahora funcionará bien así que si
there here semi file and now it will work okay so if
11:47:51
simplemente lo vuelvo a ejecutar allí y ahora va a inicializar mi css 10-1
i just rerun there and now it's going to initialize my 10-1 css
11:47:54
archivo aquí voy a elegir este nuevo neutral de Nueva York
file here i'm going to just choose this new york neutral will
11:47:57
será adecuado para el color y no vamos a usar variables css
be fine for the color and we are not going to be using css variables
11:48:01
pero voy a establecer allí que sí, todo funcionará bien, así que ahora entonces
but i'm going to just set there to yes everything will work just fine okay so now then
11:48:06
hecho con éxito, finalmente tenemos que instalar algo de los
successfully done finally we have to install something from the
11:48:09
tonos y ui así que voy a proceder a instalar
shades and ui so i'm going to go ahead and install
11:48:13
algún tipo de componente, voy a entrar en
some sort of a component i'm going to go into
11:48:16
quizás botón, así es como funcionan los tonos y ui
maybe button so this is how the shades and ui works
11:48:19
te dará muchos componentes para elegir y
it will give you a lot of component to choose from and
11:48:22
supongamos que eliges como botón, primero tienes que instalar eso en tu proyecto y luego podrías usar esto, así que en este caso voy a instalar mi botón aquí mismo, así que voy a copiar allí
let's suppose you choose like button first of all you have to install that in your project and then you would be able to use this so in this case i'm going to install my button right here so i'm going to copy there
11:48:32
y primero tenemos que instalar allí y aquí verás una carpeta de componentes
and first of all we have to install there and here you will see a components
11:48:35
carpeta aquí y aquí puedes ver que tenemos una carpeta de componentes
folder right here and here you can see we have a components folder
11:48:38
dentro de esta carpeta de componentes tenemos una carpeta ui y
inside this component folder we have a ui folder and
11:48:41
dentro de allí tenemos nuestro botón aquí, no vamos a jugar con
inside there we have our button right here we're not going to be playing around
11:48:45
estos botones, pero solo los vamos a usar y
with these buttons but we are going to be just using them and
11:48:48
cómo vamos a usarlos, déjame mostrarte cómo podemos usarlos, voy
how are we going to be using them let me show you how we can use them i'm
11:48:51
a entrar en mi app.tsx y voy a eliminar cada cosa de allí y solo voy a usar mi rfce y ahora quiero usar ese botón, así que simplemente
going to go into my app.tsx and i'm going to remove every single thing from there and i'm going to just use my rfce and now i want to use that button okay so i'll just
11:49:00
usaré como botón aquí y aquí puedes ver que tenemos este componente de ubicación como ui y botón
use like button right here and here you can see we have this location like component ui and button
11:49:05
y si presiono enter aquí y ahora podemos escribir como lo que sea
and if i hit enter right here and now we can just write like whatever
11:49:09
quiero escribir como uh aprender más y si
i want to write like uh learn more and if
11:49:12
digo que mi archivo se ejecute o el servidor usando npm run dev
i say my file run or server by using npm run dev
11:49:15
copia allí, digamos justo aquí y aquí
copy there let's say right here and here
11:49:18
puedes ver que ahora estamos obteniendo nuestro botón justo aquí, lo cual es increíble, pero
you can see we are now getting our button right here which is amazing but
11:49:21
fue una gran configuración para hacer, está bien, así que podemos obtener como la tarjeta, podemos obtener como, vamos con el acordeón, podemos
that was a huge setup to make okay so we can get like the card we can get like uh come on with accordion we
11:49:29
obtener muchas cosas, así que lo que voy a hacer es que voy a simplemente
can get like a lot of stuff so what i'm going to do is that i'm going to just
11:49:32
crear mi tarjeta justo aquí, así que voy a copiarlas y
create my card right here so i'm going to copy them and
11:49:35
ejecutar allí, primero déjame simplemente terminar allí y
run there first of all let me just terminate there and
11:49:38
instalar mi tarjeta dentro de mi proyecto, así que se va a instalar
install my card inside my project so it's going to install
11:49:41
esa tarjeta justo aquí, luego se completó con éxito, ahora voy a ir
that card right here then successfully done now i'm going to go
11:49:44
allí y copiar todo ese contenido y voy a simplemente copiar todo ese código justo aquí, ahora dentro, solo tenemos que usar eso, está bien, así que si simplemente coloco este código, ahora estamos obteniendo muchas cosas.
in there and copy all of that content and i'm going to just copy all of that code right here now inside there we just have to use that okay so if i just place this coding right We are now getting a lot of stuff.
11:49:54
Pero en esta situación, solo quiero obtener el...
But in this situation, I only want to get the...
11:49:57
Así que voy a cortar eso de aquí y
So I will cut that from here and
11:50:00
eliminar todas esas cosas de aquí y necesitamos todas estas importaciones
remove all of that stuff from here and we need all of these imports
11:50:04
así que en lugar de proporcionar este botón, solo voy a proporcionar
so instead of providing this button i'm going to only provide
11:50:07
todas sus cosas, así que si guardo mi archivo, estamos obteniendo
all of their stuff so if i save my file we are getting
11:50:10
una entrada y también las etiquetas, también tenemos que instalar allí, está bien
an input and also the labels we also have to install there okay
11:50:13
así que estamos obteniendo un botón dos veces, no
so we are getting a button twice we
11:50:16
necesitamos react.js y ahora estamos obteniendo estos añadidos, como tenemos que instalar la etiqueta de entrada y también el select, así que voy
don't need react.js and we're now getting these added like we have to install the input label and also the select so i'm
11:50:23
a seguir adelante y agregar eso, así que para terminar allí
to go ahead and add that so to end there we
11:50:26
vamos a estar usando ese mismo comando, pero solo tenemos que cambiar el componente
are going to be using that same command but we only have to change the component
11:50:29
nombre, como en lugar de escribir una tarjeta, voy a escribir como
name like instead of writing a card i'm going to write like
11:50:32
entrada, también voy a poner la etiqueta y
input i'm going to also put the label and
11:50:35
también, finalmente tenemos que agregar el select, está bien
also finally we have to add the select okay
11:50:39
si presiono enter aquí, se va a instalar allí
if i hit enter right here so it's going to install there
11:50:42
dentro de mi proyecto y ahora que se instaló con éxito, y si corto este archivo y abro allí una vez más, aquí puedes ver que esos errores ahora han desaparecido con éxito.
inside my project and now that successfully install and if i cut this file and open there once again here you can see those errors are now successfully gone
11:50:51
está bien, así es como se verá, pero ahora voy a
okay so this is how it will look like but now i'm going
11:50:54
usar mi npm run dev y si solo actualizo allí y
to use my npm run dev and if i just refresh there and
11:50:57
aquí puedes ver que ahora estamos obteniendo nuestro formulario, así que tenemos nuestro campo de entrada
here you can see we are now getting our form so we have our input field
11:51:01
también tenemos una declaración select aquí, así que sí, esto
we have also a select statement right here so yeah this
11:51:04
es cómo vamos a estar usando un shadson ui dentro de nuestro react js
is how we are going to be using a shadson ui inside our react js
11:51:07
proyecto, así que ahora aprendamos sobre la biblioteca de formularios de react que
project so now let's learn about the react form library which will
11:51:10
nos permite proporcionar validación fácil de usar para nuestro formulario, está bien, así que voy a hacer clic en este botón de inicio y aquí puedes ver cómo vamos a estar instalando allí y así es como vamos a estar usando allí.
allows us to provide easy to use validation for our form okay so i'm going to click on this getting started button and here you can see this is how we are going to be installing there and this is how we we are going to be using there.
11:51:22
Así que lo que voy a hacer es que primero voy a hacer una configuración, así que voy a abrir mi terminal
So what I'm going to do is that first of all I'm going to make a setup so I'm going to open my terminal
11:51:25
aquí y voy a usar npm create read
right here and I'm going to be using npm create read
11:51:28
y la última y le voy a dar el nombre de como react hook form demo estaría bien y elegiré react.js y también typescript.
and latest and I'm going to give it the name of like react hook form demo would be fine and I'll choose react.js and also typescript.
11:51:40
Déjame entrar en mi react hook form y voy a usar npm i para instalar todos los paquetes.
Let me go into my react hook form and I'm going to use npm i to install all of the packages.
11:51:45
Así que luego, exitosamente hecho, voy a abrir allí en mi VS code usando
So then successfully done I'm going to open there in my VS code by
11:51:48
un código punto, así que se va a abrir allí, aquí voy a abrir
using a code dot so it's going to open there right here i'm going to open
11:51:52
mi terminal e instalar el paquete de react hook form de
my terminal and install the react hook form package from
11:51:55
aquí, así que solo tenemos que escribir npm install o i
here so we just have to write npm install or i
11:51:59
y luego tenemos que escribir react hook form y ahora voy a presionar enter
and then we have to write react hook form and now i'm going to hit enter
11:52:02
así que se va a instalar allí en mi proyecto, así que aquí puedes ver que eso está hecho
so it's going to install there in my project so here you can see that's done
11:52:05
ahora déjame cerrar allí y voy a usar npm run div
now let me just close there and i'm going to be using npm run div
11:52:08
para ejecutar qué servidor, también hice una limpieza, así que ahora es tiempo de enfocarse en el react hook form, así que voy a crear una carpeta con el nombre de componentes y dentro de allí voy a crear mi componente form.tx para ello aquí.
to run what server i also made a cleanup so now it's time to focus on the react hook form so i'm going to create a folder with the name of components and inside there i'm going to create my form dot tx component for it here.
11:52:19
Voy a usar mi RFCE y registrarlo en mi app.
I'm going to use my RFCE and register that in my app.
11:52:23
Está bien, así que primero tenemos que usar como formulario y tenemos que importarlo de la carpeta de componentes.
Okay so first of all we have to just use like form and we have to import that from the components folder.
11:52:29
Así que ahora voy a guardar eso y así es como se ve para ello aquí, que se ve increíble.
So now I'm going to save that and this is how it looks like for it here which is looking amazing.
11:52:33
Así que ahora la siguiente cosa que tenemos que hacer es que tenemos que agarrar o usar el formulario de donde vamos a estar agarrando allí del react hook form.
So now the next thing that we have to do is that we have to grab or use form from where we are going to be grabbing there from the react hook form.
11:52:41
Vamos a estar obteniendo toda nuestra magia como validación de formularios, manejo de formularios y también los errores de este hook.
We're going to be getting all of our magic like form validation, form handling and also the errors from this hook.
11:52:47
Esa es la razón por la que lo llamamos react hook form, está bien
That is why we call as a react hook form okay
11:52:50
por eso lo llamamos como un formulario de gancho de reacción, está bien
so we have to also execute there right here and now from
11:52:53
así que también tenemos que ejecutar allí justo aquí y ahora desde
this use form hook we are going to be destructuring a few things
11:52:57
este gancho de formulario que vamos a estar desestructurando algunas cosas
first of all we are going to be destructuring the register we
11:53:00
primero que nada vamos a estar desestructurando el registro que
would also need to destructure the handle submit and also the
11:53:03
también necesitaríamos desestructurar el manejo de envío y también el
form state and from this form state we are going
11:53:06
estado del formulario y a partir de este estado del formulario vamos
to be also nested destructuring the errors and also the is submitting uh is submitting there we go so i'm going to save my file and now let me explain all of that stuff right here.
11:53:17
también a desestructurar anidadamente los errores y también el estado de envío, uh, está enviando, ahí vamos, así que voy a guardar mi archivo y ahora déjame explicar todas esas cosas aquí.
So the first thing that we are destructuring is a register. And register is used to connect input field to the form. Then we have a handle submit.
11:53:24
Así que la primera cosa que estamos desestructurando es un registro. Y el registro se usa para conectar el campo de entrada al formulario. Luego tenemos un manejo de envío.
And this is a function which allows us to handle the form submission. Then we have errors which contains the validation error for the form.
11:53:30
Y esta es una función que nos permite manejar el envío del formulario. Luego tenemos errores que contienen el error de validación para el formulario.
And then we also have is submitting. So this is basically just a flag which I'm going to show you in a few seconds.
11:53:36
Y luego también tenemos el estado de envío. Así que esto es básicamente solo una bandera que te voy a mostrar en unos segundos.
So yeah that was just a bit of explanation about the register, handle, submit and errors. So I'm going to remove that from here.
11:53:42
Así que sí, eso fue solo un poco de explicación sobre el registro, manejo, envío y errores. Así que voy a quitar eso de aquí.
Now we are getting this error. So we have to also resolve this error so
11:53:46
Ahora estamos obteniendo este error. Así que también tenemos que resolver este error, así
which is our typescript error so i'm going to create my interface right here
11:53:49
que es nuestro error de typescript, así que voy a crear mi interfaz aquí
with the name of form data and inside
11:53:52
con el nombre de datos del formulario y dentro
there we are going to be first of all defining my name which will be
11:53:55
ahí vamos a estar primero definiendo mi nombre que será
a string and also the email which will be a string and
11:53:58
una cadena y también el correo electrónico que será una cadena y
also the password which will be a string
11:54:01
también la contraseña que será una cadena
as well okay so i'm going to take this form data right here and we have to put that or annotate or use hook with this form data so here you can see that's
11:54:10
también, está bien, así que voy a tomar estos datos del formulario aquí y tenemos que poner eso o anotar o usar el gancho con estos datos del formulario, así que aquí puedes ver que
now successfully done we are now getting these errors because we
11:54:13
ahora se ha hecho con éxito, ahora estamos obteniendo estos errores porque
have to use these okay so now to use that the first
11:54:16
tenemos que usar estos, está bien, así que ahora para usar eso, la primera
thing that i want to do is that i want to remove this form from here and instead of
11:54:19
cosa que quiero hacer es que quiero quitar este formulario de aquí y en lugar de
providing this div i'm going to change that to form and i'm going to also
11:54:22
proporcionar este div, voy a cambiar eso a formulario y también voy a
provide the on submit handler to that and for this
11:54:25
proporcionar el controlador de envío para eso y para este
on submit handler we are going to be calling this function which is a handle
11:54:29
controlador de envío vamos a estar llamando a esta función que es un manejo
submit which we are now importing from this hook okay so we have to provide that now inside there we are going to be providing our own custom function which will be the on submit function.
11:54:38
Y ahora déjame crear esta función de enviar justo aquí.
And now let me create this on submit function right here.
11:54:41
Básicamente no vamos a hacer nada loco, pero simplemente vamos a registrar datos en la consola.
So basically we're not gonna be doing anything crazy, but we're going to be just logging to the console or data.
11:54:46
Así que tenemos nuestro on submit, y va a tomar los datos, y ahora dentro de eso, simplemente vamos a registrar esos datos en la consola.
So we have our on submit, and it's gonna take the data, and now inside there, we're going to be just logging that data to the console.
11:54:53
Eso es todo lo que tenemos que hacer. Pero también voy a proporcionar mi magia de TypeScript aquí. Así que vamos a usar un manejador de envío.
That's everything that we have to do. But I'm gonna also provide my TypeScript magic right here. So we're going to be using like submit handler.
11:54:59
Manejador. Así que ahora déjame tomar eso del formulario de React y vamos a anotar eso con estos datos del formulario que ya hemos definido aquí.
Handler. So now let me just grab that from the React form and we are going to be annotating that with this form data which we have already defined right here.
11:55:08
Así que la presentación del formulario ya está completamente hecha. Lo siguiente que tenemos que hacer es crear nuestro campo de entrada para que podamos escribir algo dentro.
So the form submission is now totally done. The next thing that we have to do is that we have to create our input field so that we can type something inside there.
11:55:15
Así que solo crearé un div y dentro de este div proporcionaré una etiqueta y para este HTML4 solo proporcionaré un nombre y también voy a proporcionar un nombre como etiqueta.
So I'll just create a div and inside this div I will provide like a label and for this HTML4 I'll just provide like a name and I'm going to also provide a name as a label.
11:55:23
Ahora debajo de eso, vamos a definir nuestro campo de entrada aquí.
Now underneath there, we are going to be defining our input field right here.
11:55:27
Va a ser de tipo texto y también vamos a proporcionar el ID de nombre allí.
It's going to take the type of text and we are going to be also providing the ID of name to there.
11:55:32
Aquí, ahora vamos a usar nuestra función de registro. Así que voy a usar puntos suspensivos y aquí tenemos que llamar a esta función de registro, que ahora proviene de este gancho de uso de formulario aquí.
Here, now we are going to be using our register function. So I'm going to use dot dot dot and here we have to call this register function, which is now coming from this use form hook right here.
11:55:43
Así que ahora estamos llamando allí. Así que el primer argumento de texto es un nombre.
So we are now calling there right here. So the first argument text is a name.
11:55:48
Como puedes ver aquí, no se proporcionó el argumento de nombre.
As you can see right here, like argument name was not provided.
11:55:52
Puedes proporcionar el nombre de nombre o correo electrónico o contraseña
like you can provide the name of name or email or password
11:55:55
o cualquier cosa que prefieras, entonces también tienes que especificar
or anything that you prefer then you have to also specify
11:55:58
no tienes que hacerlo, pero si quisieras, puedes proporcionar
like you don't have to but if you wanted to you can provide
11:56:01
datos de validación allí, así que en lugar de hablar sobre la teoría
a validation data there so instead of talking about the theory
11:56:04
déjame poner un nombre aquí, está bien, y voy a
let me just put a name right here okay and i'm going to
11:56:07
proporcionar una coma y luego vamos a proporcionar algún tipo de reglas de validación
provide a comma and then we're going to be providing some sort of validation rules
11:56:11
así que solo usaré como requerido, esto debería ser requerido
okay so i'll just use like required this should be required
11:56:14
pero si alguien no especificó el nombre, entonces vamos a lanzar este error que dirá que el nombre es requerido, está bien, así que voy a guardar mi. Así es como vamos a hacer un conjunto para nuestro campo de entrada.
but if somebody did not specify the name so we are going to be throwing this error which will say like name is required okay so i'm going to save my So this is how we are going to be making a set of for our input field.
11:56:24
Así es como vamos a decirle a nuestro formulario react-hook que tiene que encargarse de este campo de entrada.
This is how we are going to be telling our react-hook form that you have to take care of this input field.
11:56:29
Si alguien no especificó nada dentro de este campo de entrada, entonces vamos a proporcionar este error que dirá que el nombre es requerido.
If somebody did not specify anything inside this input field, so we are going to be providing this error which will say like name is required.
11:56:37
Así que esta va a ser nuestra restricción o nuestra regla. Y así es como vamos a registrar para nuestro formulario react-hook.
So this is going to be our constraint or our rule. And this is how we are going to be registering the for our react-hook form.
11:56:43
Ahora, ¿qué pasa si alguien no proporcionó algo dentro de este campo de entrada? Así que simplemente vamos a lanzar algún tipo de error aquí.
Now what if somebody did not provide something inside this input field? So we are going to be just throwing some sort of error right here.
11:56:50
así que voy a usar mis llaves y dentro de eso vamos a
okay so i'm going to use like my curly braces and inside there we are
11:56:53
ir a nuestros errores que también estamos importando
going to be going into our errors which we are also importing
11:56:56
de o usar el formulario justo aquí vamos a
from or use form right here we are going to
11:56:59
agarrarlos y aquí tenemos que usar el punto
be grabbing them and here we have to use the dot
11:57:02
y de dónde viene nuestro error nuestro error
notation and from where is our error coming from our error
11:57:05
viene de este nombre así que voy a seleccionar eso así que si tienes algún
is coming from this name so i'm going to select that so if you got some
11:57:08
tipo de error vamos a usar este operador final está bien así que luego tenemos que especificar o mostrar ese error justo aquí vamos a
sort of error we're going to be using this end operator okay so then we have to specify or show that error right here we're going to be
11:57:16
usar como error punto nombre y vamos a obtener el mensaje
using like error dot name and we are going to be getting the message
11:57:19
de allí está bien y ahora aquí para este párrafo voy
out of there okay and now here for this paragraph i'm
11:57:22
a proporcionar también un poco de estilo a eso así que solo usaré como el color ahora se establecerá en rojo total voy a guardar mi archivo y ahora déjame probar esto
going to also provide a bit of styling to that so i'll just use like the color will be now set to totally red i'm going to save my file and now let me just test this out
11:57:29
aquí puedes ver que tenemos nuestro campo de entrada pero así que sabes qué déjame
here you can see we have our input field but so you know what let
11:57:32
también crear algún tipo de botón que solo permitirá
me also create some sort of a button which will just allows
11:57:36
que lo enviemos solo escribiré como tipo de enviar al archivo semi y ahora si no especifiqué nada allí y hago clic en enviar así que va a
us to submit i'll just write like type of submit to the semi file and now if i didn't specify anything to there and click on the submit so it's going to
11:57:44
darnos como nombre es requerido si solo escribo como
gives us like name is required if i just write like
11:57:47
no sé tal vez a b c guarda mi
i don't know maybe a b c save my
11:57:50
archivo y ahora déjame hacer clic en este botón de enviar una vez más así que va a
file and now let me click on this submit button one more time so it's
11:57:53
darnos ese abc justo aquí así es como vamos a registrar
going to give us that abc right here this is how we are going to be registering
11:57:57
nuestro campo de entrada así es como vamos a proporcionar una restricción para
our input field this is how we are going to be providing a constraint for
11:58:00
eso y así es como vamos a renderizar ese específico
that and this is how we are going to be rendering that specific
11:58:03
error justo aquí está bien así que luego está hecho también voy a eliminar esto
error right here okay so then it's done i'm going to also remove this
11:58:06
botón de aquí ahora déjame ocuparme del correo electrónico y así que voy a crear otro div y dentro de este div primero que nada
button from here now let me take care of the email and also so i'm going to create yet another div and inside this div first of all
11:58:13
tenemos que proporcionar nuestra etiqueta que tomará un correo electrónico y también tenemos que definir nuestro campo de entrada y va a tomar la entrada o el tipo de correo electrónico.
we have to provide our label which will take an email and also we have to define our input field and it's going to take the input or the type of email.
11:58:22
Ahora que tenemos que decirle a nuestro formulario de registro que tiene que hacer un seguimiento de este campo de entrada.
Now that we have to tell our record form that you have to keep track of this input field.
11:58:26
Así que vamos a usar la función de registro y vamos a proporcionar un correo electrónico justo aquí y también voy a proporcionar un poco de regla para eso como esto será requerido si alguien proporciona un correo electrónico inválido.
So we are going to be using the register function and we are going to be providing an email right here and I'm going to also provide a bit of rule to that like this will be required if somebody provide invalid email.
11:58:37
Así que vamos a escribir como el correo electrónico es requerido.
So we are going to be writing like email is required.
11:58:40
Eso va a ser lo primero y ahora también vamos a apoyar nuestro patrón
That's going to be the first thing and now we are going to be also supporting our pattern
11:58:43
como cuál será el patrón de nuestro correo electrónico está bien
like what will be the pattern of our email okay
11:58:46
así que para el valor, si sabes lo que es un jsx, genial
so for the value if you know what a jsx is cool
11:58:49
pero si no sabes lo que es un jsx, así es como se ve
but if you don't know what a jsx is but so this is how it
11:58:52
para ser honesto, yo tampoco sé lo que es un jsx
looks like to be honest i also don't know what a jsx is
11:58:56
simplemente copié el sniffer de un chat gpt, así que sí, estoy
i just copied the sniffer from a chat gpt so yeah i'm
11:58:59
usando eso aquí y también tenemos que especificar algún tipo de un
using that right here and we also have to specify some sort of a
11:59:02
mensaje aquí que dirá como dirección de correo electrónico no válida, así que ahora voy a guardar mi archivo, así que ahora que hemos
message right here which will say like invalid email address like so now i'm going to save my file so now that we successfully
11:59:09
informado a nuestro formulario reacook que tienes que hacer un seguimiento de
tell our reacook form that you have to keep track of
11:59:12
este campo de entrada y también le estamos diciendo que si alguien
this input field and also we are telling it if somebody
11:59:15
no especificó nada dentro de ahí, vamos a mostrar como
did not specify nothing inside there we are going to be showing like
11:59:18
se requiere correo electrónico y también si el correo electrónico es inválido
email is required and also if the email is invalid
11:59:22
así que vamos a mostrar como el correo electrónico es inválido ahora
so we are going to be showing like email is invalid now
11:59:25
debajo de eso también voy a proporcionar el id del correo electrónico y el placeholder
underneath there i'm going to also provide the id of email and the placeholder
11:59:28
también dirá correo electrónico aquí, voy a guardar mi archivo, pero también tenemos que mostrar esos errores, está bien, así que para mostrar esos errores estamos
will also say email right here i'm going to save my file but we also have to show those errors okay so to show those errors we are
11:59:36
usando como errors.email en este caso y
going to be using like errors.email in this case and
11:59:39
si ese es el caso, así que vamos, si ese es
if that is the case so come on if that is
11:59:42
el caso, así que vamos a crear un div y ahora dentro
the case so we are going to be just creating a div and now inside
11:59:45
de este div vamos a renderizar nuestro error aquí como error
this div we are going to be rendering our error right here like error
11:59:49
email.message y también tenemos que cambiar el color de eso a como el color se establecerá ahora totalmente en rojo, así que voy a guardar mi archivo, pero no podemos verlo porque tenemos que crear nuestro botón.
email.message and we also have to change the color of that to like color will be now set to totally red like so i'm gonna save my file but we cannot see there because we have to create our button.
12:00:00
que nos permitirá enviar este formulario. Así que solo usaré como enviar y el tipo también se establecerá en enviar.
which will allow us to submit this form. So I'll just use like submit and the type will be also set to submit.
12:00:05
Si no especifiqué nada para eso y si hago clic en este enviar, nos dará dos errores aquí.
If I didn't specify nothing to that and if I click on this submit, it's going to give us two errors right here.
12:00:10
Así que nos dará como nombre requerido y correo electrónico también requerido.
So it's going to give us like name is required and email is also required.
12:00:14
Así que si solo especifico algún tipo de nombre y para el correo electrónico, voy a escribir como, no sé, o sabes qué, prueba.
So if I just specify some sort of a name and for the email, I'm going to write like, I don't know, or you know what, test.
12:00:20
Sí, prueba estaría bien. Así que aquí puedes ver que ahora estamos obteniendo nuestra dirección de correo electrónico no válida.
Yeah, test would be fine. So here you can see we're now getting our invalid email address.
12:00:24
Así que si uso como prueba en gmail.com, ese error ahora ha desaparecido con éxito.
So if I use like test at gmail.com, that error is now successfully gone.
12:00:29
y ahora si hago clic en eso, ya no estamos obteniendo ese error. Así es como vamos a hacer un seguimiento de eso.
and now if I click on that we are no longer getting that error. This is how we are going to be keeping track of that.
12:00:34
Ahora fuera de este div vamos a crear otro div.
Now outside from this div we are going to be creating yet another div.
12:00:39
Así que solo crearé un div para lo que llamamos la contraseña.
So I'll just create a div for what we call for the password.
12:00:43
Así que solo crearé un campo de entrada con el tipo de contraseña y aquí tenemos que especificar primero nuestra función de registro para que tengamos que decirle a nuestro formulario de gancho de React que también tiene que hacer un seguimiento de este campo de entrada.
So I'll just create an input field with the type of password and here we have to specify first of all our register function so that we have to tell our React hook form that you also have to keep track of this input field
12:00:54
y vamos a proporcionar nuestra contraseña a eso y también el
and we are going to be providing our password to that and also the
12:00:57
la longitud mínima será el valor
minimum length will be value
12:01:01
proporcionemos un valor y la longitud mínima será de 8 caracteres
let's just provide a value and the minimum length will be 8 characters
12:01:04
si la longitud de la contraseña es menor de 8 caracteres, entonces
if the password length is less than 8 characters so
12:01:07
vamos a mostrar este error como que la contraseña debe
we are going to be showing this error like password must
12:01:10
tener al menos 8 caracteres y
be at least 8 characters and
12:01:13
ahora fuera de allí también vamos a proporcionar nuestro marcador de posición
now outside from there we are going to be also providing our placeholder
12:01:16
y el marcador de posición será solo una contraseña así que si guardo mi archivo y ahora debajo también voy a renderizar mis errores aquí así que si tienes
and the placeholder will be just a password like so so if I save my file and now underneath I'm going to also render my errors right here so if you have
12:01:25
algún tipo de error dentro de la contraseña, entonces vamos a mostrar eso
some sort of error inside the password so we are going to be showing that
12:01:28
error y también vamos a proporcionar un color rojo para allí
error and we are going to be also providing a color of red to there
12:01:31
así que aquí puedes ver que tenemos nuestro nombre, correo electrónico y también la contraseña
so here you can see we have our name email and also the password
12:01:34
y también podemos proporcionar una etiqueta para allí, pero yo
and we can also provide a label for there but i
12:01:37
supongo que no tenemos que hacerlo y ahora vamos a crear nuestro botón que
guess like we don't have to and now we are going to be creating our button which
12:01:41
dirá simplemente enviar y ahora también vamos a proporcionar un tipo de envío para allí así que si guardo mi archivo ahora déjame llenar este formulario así que solo voy a
will just say submit and now we are going to be also providing a type of submit to there so if i save my file now let me just fill this form so i'm going to just
12:01:49
proporcionar el nombre de Zan y test en gmail.com y solo voy a proporcionar como 123
I will just provide the name of Zan and test at gmail.com and I am going to only provide like 123
12:01:56
y ahora si hago clic en enviar, nos dará ese error como que la contraseña debe tener al menos 8 caracteres, si escribo como 4, 5, aún 7, 8, 9, 10 y aquí puedes ver que el error ahora ha desaparecido con éxito
and now if I click on submit it will give us that error like password must be at least 8 characters if I write like 4, 5, still 7, 8, 9, 10 and here you can see that error is now successfully gone
12:02:08
así que sí, así es como vamos a trabajar con la validación o la biblioteca de formularios de gancho de React, pero también te voy a mostrar el estado deshabilitado
so yeah this is how we are going to be working with the validation or the react hook form library but I am going to also show you the disable state
12:02:17
en el estado de envío del formulario, así que para eso podemos usar el deshabilitar
on the form submitting state so for there we can use the disable
12:02:20
vamos, no este, el deshabilitar y aquí
come on not this one the disable and here
12:02:23
tenemos que especificar si se está enviando, así que es
we have to specify the is submitting so it's
12:02:26
va a darnos un valor booleano, así que si nuestro formulario se está enviando
going to give us a boolean value so if our form is submitting
12:02:29
el botón estará deshabilitado, pero si nuestro formulario no
so the button will be disabled but if our form is not
12:02:32
el botón estará deshabilitado, pero si nuestro formulario no
submitting it's going to give us a false and our button will no
12:02:36
se está enviando, nos dará un falso y nuestro botón ya no
longer be disabled okay so just keep that in mind and i'm going to also change the text of there to like uh if it is submitting let me just use like if it is
12:02:44
estará deshabilitado, así que tenlo en cuenta y también voy a cambiar el texto de ahí a como, uh, si se está enviando, déjame usar como si se está
submitting so in this situation we are going to be using like loading dot
12:02:47
enviando, así que en esta situación vamos a usar como cargando punto
dot dot and if that's not the case we are going to be using submit
12:02:51
punto punto y si ese no es el caso, vamos a usar enviar
now let me just save my file and now i'm going to just write
12:02:54
ahora déjame guardar mi archivo y ahora solo voy a escribir
like hosan and this email and
12:02:57
como hosan y este correo electrónico y
also just write some sort of a random password and here
12:03:00
también solo escribir algún tipo de contraseña aleatoria y aquí
you can see if i click on that you cannot see that because that's super
12:03:03
puedes ver si hago clic en eso, no puedes ver eso porque es súper
quick so you cannot see that in the production you will see that so yeah that was just the basics of react hook form library now Now let me give you one more example of the ReiCook form.
12:03:13
rápido, así que no puedes ver eso en la producción, lo verás, así que sí, eso fue solo lo básico de la biblioteca de formularios de react hook, ahora déjame darte un ejemplo más del formulario ReiCook.
So if you care about that, you can totally watch that. Or if you don't, you can go ahead and jump to the next section.
12:03:20
Así que si te importa eso, puedes verlo totalmente. O si no, puedes saltar a la siguiente sección.
And now let's just create another form which will be a bit of advanced form. It's not that much advanced to be honest.
12:03:27
Y ahora solo vamos a crear otro formulario que será un poco más avanzado. No es tan avanzado, para ser honesto.
We're not going to be learning anything new. But this form is only for the practice. So let's just save there and go ahead and go to our app.
12:03:33
No vamos a aprender nada nuevo. Pero este formulario es solo para la práctica. Así que guardemos ahí y vayamos a nuestra aplicación.
Advanced form right here. Register there. Save my file. And I'm going to also go ahead and go to my SRC folder.
12:03:40
Formulario avanzado justo aquí. Regístrate allí. Guarda mi archivo. Y también voy a ir a mi carpeta SRC.
and use my style.css right here and I'm going to provide
12:03:44
y usar mi style.css justo aquí y voy a proporcionar
all of the css which you can find on my github repository so
12:03:47
todo el css que puedes encontrar en mi repositorio de github, así que
what I'm going to do is that I'm going to just create a bit of advanced
12:03:50
lo que voy a hacer es que solo voy a crear un poco de avanzado
form not that much advanced to be honest but the first thing that
12:03:53
formulario, no tan avanzado para ser honesto, pero lo primero que
we have to do is that we have to grab or use form from
12:03:57
tenemos que hacer es que tenemos que agarrar o usar el formulario de
where from the react hook form we
12:04:00
donde del formulario de react hook, también tendríamos que agarrar el manejador de envío de este formulario de react hook y también tenemos que importar nuestro estilo, así que vamos a usar como style.css, guarda mi archivo, y así es como se ve justo aquí, que se ve increíble.
would also need to grab the submit handler from this react hook form and we also have to import our styling so we are going to be using like style.css, save my file, and this is how it looks right here, which is looking amazing.
12:04:13
Ahora déjame proporcionar una interfaz de los datos del formulario. Así que vamos a proporcionar como nombre, apellido, correo electrónico, ciudad, estado, código postal, país y ubicación completa.
Now let me provide an interface of the form data. So we are going to be providing like first name, last name, email, city, state, zip code, country, and complete location.
12:04:21
Así que voy a usar eso dentro de mi componente. Así que lo que voy a hacer es que voy a usar mi use form una vez más.
So I'm going to use that inside my component. So what I'm going to do is that I'm going to use my use form once again.
12:04:27
De este use form, vamos a desestructurar algunas cosas. Solo desestructuraremos nuestro registro, que nos permite registrar nuestro campo de entrada.
From this use form, we are going to be destructuring a few things. We would just destructure our register, which allows us to register our input field.
12:04:35
también necesitaríamos nuestro manejar enviar cada vez que estemos enviando nuestro
we would also need our handle submit whenever we are submitting our
12:04:38
datos y también necesitaremos algunos pasos de este
data and we will also need a few steps from this
12:04:41
componente así que solo necesitaremos como los errores eso va a ser
component so we will just need like the errors that's going to be it
12:04:44
ahora déjame anotar mis datos del formulario aquí mismo
now let me just annotate my form data right here
12:04:47
para que no tengamos esos errores así que eso es genial
so that we don't get those errors so that's cool
12:04:50
ahora voy a quitar eso de aquí y cambiar este a el formulario así que usaré como oh sabes qué no vamos a hacer eso no vamos a hacer eso está bien vamos a
now i'm going to just remove that from here and change this one to the form so i'll use like oh you know what we're not going to do that we are not going to do that okay let's just
12:04:59
poner un nombre de clase de contenedor de formulario y dentro de este dev vamos a crear nuestro h2 que dirá formulario de registro y debajo de eso vamos a crear nuestro formulario.
put a class name of form container and inside this dev we are going to be creating our h2 which will say registration form and underneath there we are going to be creating our form.
12:05:10
no va a tomar ninguna acción pero vamos a proporcionar nuestro controlador on submit y cada vez que estemos enviando esto vamos a usar el manejar envío del formulario de gancho de reacción
It's not going to take any action but we are going to be providing our on submit handler and whenever we are submitting this we are going to be using the handle submit from the react hook form
12:05:19
y simplemente proporcionemos nuestra función on submit allí. on submit y simplemente creemos nuestro on submit aquí.
and let's just provide our on submit function to there. on submit and let's just create our on submit right here.
12:05:26
Así que básicamente no vamos a hacer nada loco pero solo vamos a registrar todos esos datos en la consola.
So basically we're not going to be doing anything crazy but we are going to be just logging all of that data to the console.
12:05:32
Así que usaré como on submit y cada vez que los estemos enviando vamos a usar nuestro controlador de envío y simplemente proporcionemos nuestros datos del formulario a ellos y eso va a ser igual a estos datos.
So I'll just use like on submit and whenever we are submitting them we are going to be using our submit handler and let's just provide our form data to them and that's going to be equal to this data.
12:05:42
Vamos a tomar esos datos como un perímetro y luego vamos a registrar esos datos en la consola.
We are going to be taking that data as a perimeter and then we're going to be logging that data to the console.
12:05:47
Y ahora dentro de este formulario lo que quiero hacer es crear una demostración.
And now inside this form what I want to do I want to create a demo.
12:05:50
Dentro de esto simplemente proporcionemos nuestra etiqueta que dirá como primero
Inside this let's just provide our label which will say like first
12:05:54
nombre y va a tomar como un nombre de pila como
name and it's going to take like a first name as
12:05:57
una etiqueta también vamos a proporcionar nuestro campo de entrada y
a label we're going to be also providing our input field and
12:06:00
el id se establecerá en primer nombre primero
the id will be set to first name first
12:06:04
nombre así y también vamos a proporcionar nuestro registro
name like so and we're going to be also providing our register
12:06:07
así que usaré como registrar y aquí tenemos que usar
so i'll use like register and here we have to use
12:06:10
nuestro primer nombre y ahora para el siguiente parámetro
our first name and now for the next parameter
12:06:13
tenemos que proporcionar nuestros patrones así que usaré o no un patrón sino restricciones así que usaré como requerido y eso
we have to provide our patterns so i'll use or not a pattern but or constraints so i'll use like required and that
12:06:20
debería ser requerido tenemos que proporcionar como el primer nombre es requerido
should be required we have to provide like first name is required
12:06:24
ahí vamos guarda mi archivo volvamos y
there we go save my file let's just go back and
12:06:27
así es como se ve y ahora debajo de eso también vamos a renderizar
this is how it looks like and now underneath there we are going to be also rendering
12:06:31
nuestros errores así que si tienes algún tipo de errores dentro de nuestro
our errors so if you have some sort of errors inside our
12:06:34
primer nombre así que en esta situación vamos a renderizar nuestro
first name so in this situation we're going to be rendering our
12:06:37
párrafo que dirá como errores primer nombre punto mensaje así que simplemente vamos a agarrar el mensaje de allí así que eso está hecho ahora debajo
paragraph which will say like errors first name dot message so we're going to be just basically grabbing the message from there so that's done now underneath
12:06:46
este div vamos a definir otro div más
this div we are going to be defining yet another div okay
12:06:49
así que dentro de ese div vamos a definir nuestra etiqueta que
so inside that div we're going to be defining our label which
12:06:52
dirá como apellido y dentro de ahí simplemente proporcionemos nuestro
will say like last name and inside there let's just provide our
12:06:55
apellido aquí vamos a proporcionar también nuestra entrada
last name right here we're going to be also providing our input
12:06:58
campo con el tipo de texto y el id de apellido
field with the type of text and the id of last
12:07:01
nombre hoy y ahora tenemos que registrar esto así que vamos a
name today and now we have to register this so we are going to be
12:07:04
usar nuestra función de registro simplemente proporcionemos nuestro apellido dentro de ahí y aquí esto va a ser requerido así que también tenemos
using our register function let's just provide our last name inside there and here this is going to be required so we also have
12:07:11
que proporcionar o requerir está bien así que usaré como apellido
to provide or require okay so i'll use like last
12:07:14
el apellido es requerido ahí vamos y
name is required there we go and
12:07:17
finalmente tenemos que renderizar esos errores vamos a usar como errores
finally we have to render those errors we are going to be using like errors
12:07:20
apellido y uh simplemente rendericemos nuestro párrafo aquí y dentro de este párrafo vamos a usar como errores punto apellido
dot last name and uh let's just render our paragraph right here and inside this paragraph we are going to be using like errors dot last name
12:07:30
punto mensaje ahí vamos a continuación también tenemos que encargarnos del correo electrónico así que simplemente creemos nuestra etiqueta
dot message there we go next we also have to take care of the email so let's just create our label
12:07:35
para el correo electrónico en minúsculas correo como
for the email in lowercase email like
12:07:39
así que vamos a proporcionar qué campo de entrada y
so and we are going to be providing what input field and
12:07:42
para este campo de entrada vamos a proporcionar un tipo de correo el
for this input field we are going to be providing a type of email the
12:07:45
id de correo y también simplemente registremos
id of email and also let's just register
12:07:48
ahí mismo está bien así que voy a usar como correo
there right here okay so i'm going to be using like email
12:07:51
y dentro de ahí esto es requerido
and inside there this is required there
12:07:54
proporcionar una dirección de correo electrónico es requerido y esto debería ser doble d también voy a proporcionar mi patrón y para el valor de este patrón vamos a pasar este patrón
by providing an email address is required and this should be double d i'm going to also provide my pattern and for the value of this pattern we are going to be passing this pattern
12:08:06
que copié del chat GPT para ser honesto y también vamos a proporcionar un mensaje
which I copied from the chat GPT to be honest and we are going to be also providing a message
12:08:11
que dirá como correo electrónico inválido a doble d r a doble s
which will say like invalid email a double d r a double s
12:08:15
también tenemos que renderizar nuestros errores así que voy a usar como errores
we also have to render our errors so I'm going to be using like errors
12:08:18
punto correo y tenemos que renderizar nuestros
dot email and we have to render our
12:08:21
errores usando nuestros párrafos así que voy a usar como errores punto
errors by using our paragraphs so I'm going to be using like errors dot
12:08:25
correo y luego punto mensaje ahora
email and then dot message now
12:08:28
fuera de allí vamos a crear un div una vez más y
outside from there we are going to be creating a div one more time and
12:08:31
dentro de allí vamos a crear nuestra etiqueta para la ciudad vamos
inside there let's just create our label for the city come on
12:08:34
ciudad y también vamos a proporcionar nuestra ciudad aquí y
city and let's just also provide our city here and
12:08:38
también el id se establecerá en ciudad y vamos a registrar
also the id will be set to city and let's just register
12:08:41
eso usando la función de registro
that by using dot dot dot register function
12:08:44
tenemos que proporcionar nuestra ciudad y también eso es
we have to provide our city and also that's
12:08:47
va a ser requerido bien, así que si eso es requerido vamos a usar como ciudad es requerida ahí vamos y también vamos a renderizar nuestros errores usando errores
going to be required okay so if that is required so we are going to be using like city is required there we go and also let's just render our errors by using errors
12:08:59
errores.ciudad maldita sea, ¿por qué demonios no estoy recibiendo los errores.ciudad?
errors.city goddammit why the hell am i not getting the errors.city
12:09:04
y si tenemos algún tipo de error proveniente de
and if we have some sort of error coming from
12:09:07
la ciudad vamos a renderizar nuestro errores.ciudad.mensaje ahí vamos va a haber mucho tecleo tenemos que crear otro div y también proporcionar nuestra etiqueta
the city we're going to be rendering our errors.city.message there we go there's going to be a lot of typing we have to create another div and also provide our label
12:09:19
y la etiqueta dirá estado y también proporcionaremos nuestro estado aquí para el campo de entrada que vamos a
and label will say state and also provide our state here for the input field we're going to be
12:09:25
reportar texto obviamente y id
reporting text obviously and id
12:09:28
se establecerá en estado eso va a ser requerido y
will be set to state that's going to be required and
12:09:32
vamos a reportar qué estado dentro no requerido
we are going to be reporting what state inside not required
12:09:35
pero eso va a ser registrado hemos registrado allí aquí bien así que va a tomar el estado y eso va a ser requerido
but that's going to be registered we have registered there here okay so it's going to take the state and that is going to be required
12:09:43
requerido ahí vamos así que el estado es requerido ahora para necesitar este campo de entrada tenemos que usar nuestro error
required there we go so state is required now to need this input field we have to use our error
12:09:50
voy a usar mi operador y
I'm going to use my end operator
12:09:54
proporcionar mi párrafo y cambiar eso a
and provide my paragraph and change that to
12:09:57
errores.estado.mensaje y
errors.state.message and
12:10:01
ahora fuera de allí supongo que tengo que duplicar eso como unas cuantas veces así que voy a crear para el código postal luego para el país y también uno para la ubicación completa.
now outside from there I guess I have to just duplicate there like a few times so I'm going to create for the zip code next for the country and also one for the complete location.
12:10:11
Bien, así que ahora aquí eso va a ser todo para el estado. También tenemos que crear uno más para el código postal. Así que solo cambiaré eso a un código postal así.
Okay, so now here that's going to be it for the stat. We also have to create one more for the zip. So I'll just change that to a zip like so.
12:10:18
Cambia este a código postal o en mayúsculas código postal.
Change this one to zip or in uppercase zip.
12:10:21
El ID se establecerá en código postal y el estado también será código postal y el código postal es requerido.
The ID will be set to zip and the stat will also be zip and zip is required.
12:10:28
A continuación, tenemos que crear un país, así que proporcionaré como país. Y aquí tenemos que proporcionar un país como etiqueta.
Next we have to create a country, so I'll provide like country. And here we have to provide a country as a label.
12:10:35
Y el ID se establecerá en país. Registrar, vamos a registrar nuestro país.
And the ID will be set to country. Register, we are going to be registering our country.
12:10:40
Y el país es obligatorio, así. Y el último que tenemos es una ubicación completa.
And country is required, like so. And the final one that we have is a complete location.
12:10:47
Así que solo escribiré como ubicación completa, L-O-C-A-T-I-O-N.
So I'll just write like complete location, L-O-C-A-T-I-O-N.
12:10:52
Y aquí también tenemos que proporcionar nuestra ubicación completa. Y para este texto, también lo voy a copiar y colocar aquí.
And here we also have to provide our complete location. And for this text, I'm going to also copy there and place there here.
12:10:58
y colócalo aquí también y la ubicación completa es
and place it here as well and complete location is
12:11:01
obligatoria, así que usaré como ubicación completa es obligatoria y
required so i'll use like complete location is required and
12:11:05
no cambiamos el inicio, así que en lugar de proporcionar
we did not change the start so instead of providing
12:11:08
un inicio para todos ellos, voy a cambiar allí a cambio de código postal
a start for all of them i'm going to change there to zip change
12:11:11
este a país y también este a la ubicación completa aquí, así que ahora si presiono enter, oh, también tengo que cambiar este valor aquí
this one to country and also this one to the complete complete location right here so now if i hit enter oh i also have to change this value right here
12:11:21
Así que voy a copiar allí, colocarlo aquí. También voy a copiar el país, colocarlo en el soporte.
So I'm going to copy there, place there here. I'm going to also copy the country, place there to the stand.
12:11:29
Y la ubicación completa también estará aquí. Así que ahora, finalmente, si guardo mi archivo, y ahora probemos esto.
And the complete location will also be here. So now finally, if I save my file, and now let's just test this out.
12:11:35
Así que aquí puedes ver que ahora estamos obteniendo nuestro botón de formulario, que solo dirá enviar.
So here you can see we are now getting our form button, which will just say submit.
12:11:40
Y también vamos a proporcionar un tipo de envío para eso. Guarda mi archivo. Ahora estamos obteniendo nuestro botón aquí.
And we are going to be also providing a type of submit to that. Save my file. We are now getting our button right here.
12:11:47
Así que si no especifiqué nada para eso, y hago clic en enviar, nos dará estas advertencias.
So if I didn't specify nothing to that, and click on a submit, so it's going to give us these warnings.
12:11:51
Dirá que el nombre es obligatorio, el apellido es obligatorio, la dirección de correo electrónico es obligatoria, la ciudad y el estado son obligatorios, el código postal, el país y la ubicación completa son obligatorios.
It's going to say like first name is required, last name is required, email address is required, city and state is required, zip country and complete is required, complete location is required.
12:12:01
¿Qué demonios? La ubicación completa es obligatoria. Así que nos dará que la ubicación completa es obligatoria.
What the hell? Complete location is required. So it's going to give us like a complete location is required.
12:12:09
Así que proporcionaré mi propio nombre Hussain, el apellido se establecerá en desarrollador web y proporcionaré un correo electrónico como prueba@gmail.com.
So I'll provide like my own name Hussain, last name is set to web dev and provide an email as a test at gmail.com.
12:12:17
y también la ciudad será algo, el estado será no sé, el código postal será
and also the city will be something state will be I don't know the zip code will be
12:12:24
4312 y el país será
4312 and country will be
12:12:28
y la ubicación completa será
and complete location will be
12:12:31
maldita sea, voy a copiar esto algo entonces
god damn it I'm going to copy this something then
12:12:36
no sé, entonces el código postal será 5312 y también el país es sí
I don't know then the zip code will be 5312 and also the country is yeah
12:12:47
y ahora si hago clic en el botón de enviar, no estamos obteniendo nada, pero también podemos ir a inspeccionar elemento, podemos ver todo ese contenido aquí, así que estamos obteniendo estos errores
and now if i click on the submit button we are not getting anything but we can also go ahead and go to the inspect element we can see all of that content right here so we are getting these errors
12:12:56
y ahora si, sabes, déjame refrescar allí, vamos a enviar una vez más
and now if i you know let me just refresh there we're going to submit one more time
12:12:59
y ahora estamos obteniendo todos esos datos como ciudad, ubicación completa
and now we are getting all of that data like city complete location
12:13:02
país, correo electrónico, nombre, apellido, estado y código postal, así que sí, eso fue mucho sobre el formulario de gancho de reacción que hemos aprendido, así que si tienes un
country email first name last name state and zip so yeah that was a lot about the react hook form that we've learned so if you have a
12:13:11
tiempo libre, definitivamente puedes seguir adelante y hacer otras cosas
spare time you can definitely go ahead and do some other stuff
12:13:15
con ellos, pero sí, he terminado con el formulario de gancho de reacción, bienvenido a la
with them but yeah i am done with the react hook form welcome to the
12:13:18
clase magistral de React 19, así que en esta sección vamos a cubrir
react 19 master class so in this section we are going to be covering
12:13:21
cada cosa que hay que aprender sobre React 19
every single thing that there is to learn about the react 19
12:13:24
y ten en cuenta que también haré un video separado sobre
and keep in mind i'm going to be also making a separate video about
12:13:27
React 19 porque sé que hay muchas
the react 19 because i know there are a lot
12:13:30
más características que vienen en React 19 y no puedo cubrir
more features coming in the react 19 and i cannot cover
12:13:34
eso ahora mismo porque ni siquiera se han lanzado aquí, he hablado con muchos desarrolladores de Meta y me están contando sobre ciertas características que
there right now because they are not even released here i've met with a lot of meta developer and they're telling me about a certain features which are
12:13:41
vienen en React 19, pero no ahora, pero
coming into the react 19 but not right now but
12:13:44
prometo que están viniendo, así que sí
i promise they are coming so yeah
12:13:47
ahora hablemos de la característica más grande de React 19
now let's talk about the biggest feature about the react 19
12:13:51
que son sus propios compiladores, React 19 ahora
which is their own compilers react 19 now
12:13:54
incluye su propio compilador que no solo acelerará el
includes its own compiler which will not only speed up the
12:13:57
rendimiento, sino que también automatizará ciertas tareas tediosas
performance but also automate a certain tedious task
12:14:00
reduciendo la sobrecarga para los desarrolladores, así que sí, tenemos un nuevo compilador, ¡hurra! A continuación, ya no tenemos que preocuparnos por la memorización y la memorización y cosas así.
reducing the overload for developers so yeah we have a new compiler hooray next we no longer have to care about the memoization and the memorization and stuff like that.
12:14:11
Con el nuevo compilador de React 19, no hay necesidad de la memorización o la memorización.
With React 19 new compiler, there is no need for the memorization or memoization.
12:14:16
El proceso de optimizar un componente para evitar re-renderizados innecesarios.
The process of optimizing a component to prevent unnecessary re-renders.
12:14:20
Anteriormente, dependíamos del memo utilizado y también del gancho de callback utilizado para estos propósitos, pero ahora, afortunadamente, son totalmente obsoletos debido al compilador de React 19.
Previously, we relied on the used memo and also on the used callback hook for these purposes, but now thankfully, they are totally obsolete because of the React 19 compiler.
12:14:31
También tenemos otra característica en React 19 que se llama los metadatos.
We also have another feature in React 19 which is called the metadata.
12:14:34
así que ya no necesitamos instalar paquetes de terceros para SEO y metadatos
so we no longer need to install third-party packages for SEO and metadata
12:14:40
porque React 19 ahora ofrece soporte integrado para estas características.
because React 19 now offers built-in support for these features.
12:14:44
Podemos colocar las etiquetas en cualquier lugar dentro de nuestro componente y eso funcionará perfectamente en el componente del cliente y también en el componente del servidor.
We can place the tags anywhere within our component and that will work totally fine in the client component and also on the server component.
12:14:52
Así que sí, eso también es algo grande. Ahora hablemos del tema favorito de todos, que se llama las directivas.
So yeah, that's also a big thing. Now let's talk about everyone's favorite topic which is called the directives.
12:14:59
Así que React 19 ahora incluye soporte integrado para las directivas de cliente utilizadas y también las directivas de servidor utilizadas.
So React 19 now includes built-in support for the used client and also the used server directives.
12:15:05
No vamos a cubrir la del servidor utilizado porque implica algún tipo de funcionalidad de backend. Pero no vamos a cubrir eso. No ahora mismo.
We are not going to be covering the used server one because it involves some sort of a backend functionality. But we are not going to be covering there. Not right now.
12:15:11
Pero haré un video separado sobre esto. Esto permite que el componente se renderice en el servidor, lo que resulta en un mejor SEO, un tiempo de carga de página más rápido y una obtención de datos más sencilla.
But I will make a separate video about this. This allows component to be rendered on the server resulting in improved SEO, faster page load time and more straightforward data fetching.
12:15:21
Así que sí, eso fue algunas cosas. Pero ahora hablemos sobre qué cosas son ahora completamente obsoletas en React 19.
So yeah, that was a few things. But now let's talk about what are the things which are now completely obsolete in the React 19.
12:15:28
Así que ya no tenemos que preocuparnos por el forward ref.
So we no longer have to worry about the forward ref.
12:15:31
Tampoco tenemos que preocuparnos por la carga diferida de React y también por el uso del contexto.
We also have to don't care about the React lazy loading and also the use context.
12:15:36
Quiero decir, sí, definitivamente podemos usar el contexto. Como que nada nos detiene, pero no vamos a usar el contexto.
I mean like yeah, we totally can use the use context. Like nothing is stopping us, but we are not going to be using the use context.
12:15:43
Solo vamos a usar use. Eso es todo. Lo cual es algo que voy a mostrarte en unos segundos.
We are going to be only using use. That's it. which is something I'm going to be showing you in a few seconds.
12:15:49
Ya no tenemos que preocuparnos por el memo, el use effect y también el use callback.
We no longer have to care about the memo, the use effect and also the use callback.
12:15:53
Vamos a usar el use effect para los efectos secundarios, pero no para la obtención de datos.
We are going to be using the use effect for the side effects, but not for the data fetching.
12:15:59
Así que sí, eso fue algunas cosas, pero ahora hablemos sobre el uso. Así que ahora hablemos sobre el hook use en React 19.
So yeah, that was a few things, but now let's talk about the use. So now let's talk about the use hook in React 19.
12:16:05
Así que el hook use te permite leer y cargar recursos de manera asíncrona, como promesas o contactos.
So the use hook lets you read and load resources asynchronously, such as promises or contacts.
12:16:10
Así que a diferencia de cualquier otro hook, podemos usar el hook use dentro de los bucles.
So unlike any other hook, we can use the use hook inside the loops
12:16:16
y también puedes usar eso dentro de la declaración condicional. En ciertas situaciones, puede servir como un reemplazo para el use effect.
and you can also use that inside the conditional statement. In certain situations, it can serve as a replacement for the use effect
12:16:22
al obtener los datos, algo que voy a mostrarte en unos segundos. Y
when fetching the data, something which I'm going to be showing you in a few seconds. And
12:16:26
también simplifica el uso del contexto al permitirte usar el contexto, como simplemente usar el use y luego proporcionar tu contexto allí en lugar de usar el hook use context y luego proporcionar tu contexto.
it also streamlines the context usage by allowing you to use the use context, like just use the use and then provide your context inside there instead of using the use context hook and then providing your context.
12:16:38
Así que sí, esta es la teoría sobre el hook use. Y ahora escribamos algo de código y luego sabrás de qué estoy hablando.
So yeah, this is the theory about the use hook. And now let's write some code and then you will get to know what I'm talking about.
12:16:44
Así que ahora hablemos sobre las acciones en React 19. React 19 introduce acciones que son funciones asíncronas diseñadas para simplificar las presentaciones de formularios.
So now let's talk about the actions in React 19. React 19 introduces actions which are asynchronous function designed to simplify form submissions.
12:16:52
Las acciones pueden ser utilizadas tanto en el cliente como en el servidor. Así que sí, esta es una teoría básica sobre las acciones.
Actions can be utilized on both client and also on the server side. So yeah, this is a basic theory about the actions.
12:16:59
Ahora entremos en la parte de codificación y luego sabrás de qué estoy hablando. Ahora hablemos sobre el hook use form status en React 19.
Now let's get into the coding part and then you will get to know what I'm talking about. Now let's talk about the use form status hook in React 19.
12:17:06
Así que use form status es un hook que te da información sobre el estado de la última presentación del formulario. y así es como se verá la sintaxis.
So use form status is a hook that gives you a status information about the last form submission. and this is how the syntax will look like.
12:17:13
Primero que todo, vamos a usar el use form status como si estuviéramos ejecutando nuestro hook y luego vamos a desestructurar el método de datos pendientes y también la acción.
First of all, we are going to be using the use form status like we are going to be executing our hook and then we are going to be destructuring the pending data method and also the action.
12:17:22
Totalmente autoexplicativo. Así que ahora déjame escribir algo de código y luego sabrás qué es un use form status.
Totally self-explanatory. So now let me just write some code then you will get to know what a use form status is.
12:17:28
Ahora hablemos sobre el hook use action en React 19.
Now let's talk about the use action hook in react 19.
12:17:31
Así que cuando estaba grabando este video, este hook solía ser un hook de estado de formulario, pero ya no es un hook de estado de formulario.
So when I was recording this video, this hook used to be a use form stat hook but this is no longer a use form state hook.
12:17:38
Este es un hook de estado de acción. Así que, esa es la única razón
This is a use action state hook. So, that's the only reason
12:17:42
Voy a hacer un video separado sobre las características de React 19 porque sé que habrá muchos cambios y puedo garantizarlo totalmente.
I'm going to be making a separate video about the react 19 features because I know there will be a lot of changes and I can totally guarantee that.
12:17:51
Así que, ahora hablemos de ello. Entonces, ¿qué es un estado de acción de uso?
So, now let's talk about it. So, what is a use action state?
12:17:54
Entonces, el estado de acción de uso es un gancho que te permite actualizar el estado basado en el resultado de una acción de formulario y así es como se verá la sintaxis.
So, use action state is a hook that allow you to update the state based on the result of a form action and this is how the syntax will look like.
12:18:02
Primero que nada, vamos a llamar a nuestro estado de acción de uso. Podemos proporcionar la función. También podemos proporcionar el valor inicial.
First of all, we are going to be calling our use action state. We can provide the function. We can also provide the initial value.
12:18:08
Y ahora nos dará el valor de retorno de un array. Y ahora dentro de este array, podemos desestructurar completamente el estado y también la acción del formulario, que podemos proporcionar para nuestro formulario.
And now it's going to give us the return value of array. And now inside this array, we can totally destructure the state and also the form action, which we can provide for our form.
12:18:17
Así que esta es la teoría. Y ahora vamos a entrar en la codificación. Entonces, sabrás de qué estoy hablando. Sabes lo que estás pensando.
So this is the theory. And now let's get into the coding. Then you will get to know what I'm talking about. You know what you're thinking.
12:18:23
Estás pensando, ¿dónde en el mundo está Hosean consiguiendo estos increíbles fondos de pantalla? Te voy a mostrar de dónde.
You're thinking where in the world is Hosean getting these amazing wallpapers? I'm going to show you from where.
12:18:30
Pero primero, tenemos que hacer una configuración para nuestro curso, vamos a
But first, we have to make a setup for our course let's
12:18:34
simplemente hacer una configuración para este curso que voy a
just make a setup for this course i'm going to
12:18:37
acercar un poco y lo primero que tenemos que hacer es que tenemos que instalar react
zoom in a bit and the first thing that we have to do is that we have to install react
12:18:40
lo usaré en npm crear leer en
i'll use it at npm create read at
12:18:43
la última y luego obtendré el nombre de como
latest and then i'll get the name of like
12:18:46
react 19 uh características
react 19 uh features
12:18:49
o algo así, voy a elegir reactjs y
or something like that i'm going to choose reactjs and
12:18:52
también tipo script, así que ahora vamos a entrar en el reactjs y
also type script so now let's get into the reactjs and
12:18:55
ahora vamos a estar usando npm i para instalar cada cosa
now we are going to be using npm i to install every single thing
12:18:59
dentro de ahí, eso está hecho, ahora react js
inside there that's done now react js
12:19:02
para el momento de esta grabación, la versión react 19 está
by the time of this recording react 19 version is
12:19:05
no disponible, así que vamos a estar usando los experimentales
not available so we're going to be using the experimentals
12:19:08
así que solo tienes que proporcionar este comando, así que ahora déjame colocar
so you just have to provide this command so now let me just place
12:19:11
ahí, así que primero que nada tienes que usar npm i, luego
there so first of all you have to use npm i then
12:19:14
react en experimental y también react dom en
react at experimental and also react dom at
12:19:17
experimental, así que voy a presionar enter, así que también va a instalar el interior
experimental so i'm going to hit enter so it's going to also install the inside
12:19:21
su proyecto, así que ahora déjame abrir eso en mi vs code y esto
their project so now let me just open that in my vs code and this
12:19:24
es cómo se ve, así que voy a eliminar la carpeta pública, voy a
is how it looks like so i'm going to remove the public folder i'm going to
12:19:27
también ir a la src y eliminar esta carpeta de assets, eliminar
also go into the src and remove this assets folder remove
12:19:30
el archivo app.css y vamos a vaciar esto
the app.css file and let's just empty out this
12:19:34
app.tsx y solo voy a escribir mi rafc dentro
app.tsx and i'm going to only write my rafc inside
12:19:37
ahí así que mi archivo y también voy a eliminar cada cosa de este archivo index.css y ahora voy a entrar en eso
there so my file and also i'm going to remove every single thing from this index.css file and now i'm going to go into that
12:19:43
10win css 10win css.com
10win css 10win css.com
12:19:47
haz clic en empezar, ve al marco y
click on the getting started go to the framework and
12:19:50
guías, elige, lee y copia este comando, abre mi terminal, coloca eso aquí y se va a instalar 10win css dentro de mi proyecto, también voy a presionar enter
guides choose read and copy this command open my terminal place that here and it's going to install 10win css inside my project i'm going to also hit enter some
12:20:00
Se va a inicializar Tailwind CSS dentro de mi proyecto. Así que voy a copiar ahí.
It's going to initialize Tailwind CSS inside my project. So I'm going to copy there.
12:20:04
Y vamos a entrar en nuestra configuración de Tailwind y reemplazar ahí con este nuevo contenido. Está bien.
And let's just go into our Tailwind config and replace there with this new content. Okay.
12:20:09
Y finalmente, también tenemos que copiar estas cosas de index.css y colocarlas aquí. Y tenemos que ejecutarlo usando npm run dev.
And finally, we also have to copy this index.css stuff and place there here. And we have to run there by using npm run dev.
12:20:16
Mira esto. Sol usa como localhost. Y sí, todo está funcionando como espero que funcione.
Check this out. Sol use like localhost. And yep, everything is working the way I expect them to work.
12:20:21
Avancé rápido el video y creé una carpeta de componentes. Y dentro de ahí tenemos nuestro archivo fetch to do.tsx.
I fast forward the video and created a component folder. And inside there we have our fetch to do.tsx file.
12:20:28
y ahora dentro de este archivo estamos obteniendo nuestros datos así que ahora déjame mostrarte
and now inside this file we are now fetching our data so now let me just show
12:20:31
cada cosa, primero estamos importando el use thread y
you every single thing first of all we are importing the use thread and
12:20:34
también el use effect, luego estamos creando una interfaz para nuestro to do
also the use effect then we are creating an interface for our to do
12:20:37
que solo contendrá el título y el título será
which will only hold the title and title will
12:20:40
una cadena, luego tenemos nuestro componente con el nombre de fetch to do y
be a string then we have our component with the name of fetch to do and
12:20:43
dentro de ahí tenemos nuestro hilo de to do que nos permite almacenar
inside there we have our to do thread which allows us to store
12:20:46
nuestros to do dentro de este hilo, a continuación también tenemos un hilo de carga que nos permite mostrar la carga o ocultar la carga, luego para el efecto secundario estamos usando el use effect y dentro de este use effect, ahora estamos obteniendo nuestros datos.
our to do's inside this thread next we also have a loading thread which allows us to either show the loading or hide the loading then for the side effect we are now using the use effect and Inside this use effect, we are now fetching our data.
12:20:58
Está bien, así que ahora estamos creando una función con el nombre de fetch data, que va a ser una función asíncrona.
Okay, so we are now creating a function with the name of fetch data, which is going to be an asynchronous function.
12:21:03
Y dentro de esta función, ahora estamos proporcionando un bloque try y catch. Así que primero vamos a obtener nuestros datos de esta URL.
And inside this function, we are now providing a try and catch block. So first of all, we are going to be fetching our data from this URL.
12:21:09
Si no tenemos los datos, vamos a lanzar esta respuesta. Pero si tenemos los datos, vamos a convertir eso a JSON.
If we don't have the data, so we are going to be throwing this response. But if we do have the data, so we are going to be converting that to JSON.
12:21:16
Finalmente, tenemos que enviar eso a nuestro to do para que podamos renderizar eso.
Finally, we have to send that to our to do so that we can render that.
12:21:18
Si ese no es el caso, vamos a obtener algún tipo de error, que estamos registrando en la consola.
If that's not the case, we are going to be getting some sort of error, which we are logging to the console.
12:21:24
y si ese tampoco es el caso, vamos a proporcionar nuestro cargador finalmente
and if that's also not the case we are going to be providing our loader finally
12:21:28
solo estamos llamando a nuestra función para obtener todos los datos así que ahora dejemos
we are just calling our function to get all of the data so now let
12:21:31
déjame colapsar, luego también estamos comprobando si tenemos la carga, así que
me just collapse then we are also checking if we have the loading so
12:21:34
vamos a mostrar este cargador y si ese no es el caso, así que
we are going to be showing this loader and if that's not the case so
12:21:37
finalmente tenemos que renderizar nuestro título de esto para hacerlo
finally we have to just render our title from this to do so
12:21:41
sí, ese fue nuestro componente completo y ahora, si quieres ejecutar o llamar a ese componente dentro de nuestra aplicación, así es como lo vamos a hacer. Y ahora voy a renderizar este componente aquí mismo.
yeah that was our entire component and now if you want to execute or call that component inside our app so this is how we are going to be doing there And now I'm going to render this component right here.
12:21:51
Así que usaré algo como fetch para hacerlo. Y cerremos ahí así.
So I'll use like fetch to do. And let's just close there like so.
12:21:56
Voy a intentar importar allí. Así es como vamos a importar esto. Así que guardemos nuestro archivo.
I'm going to try to import there. So this is how we are going to be importing this. So let's just save our file.
12:22:02
Y aquí puedes ver que ahora estamos obteniendo nuestro título aquí, que es un título de tarea aleatorio, lo que significa que todo está funcionando como esperamos que funcione.
And here you can see we are now getting our title right here, which is a random to do title, which means like everything is working the way we expand them to work.
12:22:10
Pero ya no tenemos que escribir todo ese código, como usar el use effect y usar la declaración if y else y toda esa basura.
But we no longer have to write like all of that code, like using the use effect and using the if and else statement and all of that crap.
12:22:17
Tenemos que simplemente eliminarlos. Y lo primero que tenemos que hacer es usar nuestro componente aquí, que es un componente de tarea fetch.
We have to just remove them. And the first thing that we have to do is that we have to just use our component right here, which is a fetch to do component.
12:22:24
Y dentro de este fetch de tarea, primero vamos a crear una variable con el nombre de data.
And inside this fetch to do, first of all, we are going to be creating a variable with the name of data.
12:22:29
Y dentro de estos datos, vamos a usar el use. ¿Y de dónde viene la palabra use? Use vendrá de ReactJS.
And inside this data, we are going to be using the use. And where in the word is use coming from? Use will be coming from the ReactJS.
12:22:36
Así que solo voy a importar el use de ReactJS. Así es como vamos a importar la función use o el hook use de ReactJS.
So I'll just import the use from the ReactJS. So this is how we are going to be importing the use function or the use hook from the ReactJS.
12:22:44
Y ahora dentro de este use, tenemos que especificar nuestra promesa. Así que solo proporcionaré una función que será una función de obtener datos.
And now inside this use, we have to specify our promise. So I'll just provide a function which will be a fetch data function.
12:22:51
Y ahora tenemos que crear esta función por separado. También podemos proporcionar nuestra función aquí si lo deseamos.
And now we have to create this function separately. We can also provide our function right here if you wanted to.
12:22:56
Así que solo crearé mi función por separado con el nombre de obtener datos. Y dentro de esta función, ¿qué quieres hacer?
So I'll just create my function separately with the name of like fetch data. And inside this function, what do you want to do?
12:23:03
Escribamos nuestra función asíncrona. Y dentro de esta función,
Let's just write our asynchronous function. And inside this function,
12:23:06
vamos a hacer una solicitud a esta URL, que
we're going to be making a request to this URL, which
12:23:09
es https y
is https and
12:23:12
luego json más holder punto type
then json plus holder dot type
12:23:16
icode punto com y luego las tareas
icode dot com and then to do's
12:23:19
y una es que vamos a almacenar eso en la variable res
and one is we're going to be storing that in the res variable
12:23:22
y ahora solo tenemos que devolver el res punto
and now we have to just return the res dot
12:23:25
json, está bien, así que ahora que hemos obtenido con éxito
json okay like so now that we successfully
12:23:28
nuestros datos y estamos proporcionando la función de uso de la palabra siguiente, tenemos que renderizar los datos en el dom, así que solo eliminaré este fetch de tarea de aquí y voy a
fetch our data and we are providing the to word use function next we have to render the data to the dom so i'll just remove this fetch to do from here and i'm going to
12:23:36
usar solo data punto y luego title, así que si yo
only use data dot and then title so if i
12:23:39
usa esto guarda mi archivo esto también nos va a dar un error y
use this save my file this also is going to give us an error and
12:23:43
¿por qué es eso? porque cada vez que queremos usar la función use o
why is that because whenever we want to use the use function or
12:23:46
el hook tenemos que envolver eso dentro del suspense así que voy
the hook we have to wrap that inside the suspense so i'm going
12:23:49
a seleccionar este div y tenemos que convertirlo a suspense
to just select this div and we have to convert there to suspense
12:23:53
así que el suspense es un tema enorme que vamos a
like so suspense is a huge topic which we are going
12:23:56
cubrir en este curso pero no ahora bien y aquí puedes ver que ahora estamos obteniendo nuestro título que se ve genial así que sí, así es como vamos a obtener nuestros datos usando el hook use, así que ahora déjame mostrarte eso una vez más.
to be covering in this course but not right now okay and here you can see we're now getting our title which is looking cool so yeah this is how we are going to be fetching our data by using the use hook so now let me just show you that once again.
12:24:07
Primero que nada, vamos a importar el hook use y dentro de este hook use vamos a proporcionar nuestra promesa.
First of all we are going to be importing the use hook and inside this use hook we are going to be providing our promise.
12:24:13
Bien, así que aquí estamos proporcionando nuestra función de obtener datos y
Okay so here we are now providing our fetch data function and
12:24:16
ahora estamos creando esa función de obtener datos y dentro de esta función de obtener datos ahora estamos obteniendo nuestros datos de esta URL y luego estamos convirtiendo esos datos a nuestro json.
now we are creating that fetch data function and inside this fetch data function we are now fetching our data from this url and then we are converting their data to our json.
12:24:26
Bien, así es como nos va a permitir obtener los datos y así es como vamos a mostrar esos datos en el DOM.
Okay so this is how it's going to allow us to fetch the data and this is how we are going to be showing their data to the DOM.
12:24:31
Ahora déjame mostrarte cómo vamos a usar el hook use con contexto.
Now let me show you how we are going to be using the use hook with context.
12:24:34
Así que primero que nada, tengo mi componente app y dentro de este componente app, ahora estoy renderizando mi componente de tema.
So first of all, I have my app component and inside this app component, I'm now rendering my theme component.
12:24:41
Así que ahora déjame ir a mi tema y vaya, eso es mucho código, Hosea, eso es mucho código.
So now let me go ahead and go to my theme and whoa, that's a lot of coding, Hosea, that's a lot of coding.
12:24:48
Así que ahora déjame explicarles todos uno por uno. Primero que nada, estamos definiendo un tipo de tema avanzado.
So now let me just explain all of them one by one. First of all, we are defining a type forward theme.
12:24:53
Va a ser un tema claro o un tema oscuro y luego estamos creando una interfaz.
It's going to be either a light or a dark theme and then we're creating an interface.
12:24:57
Y luego dentro de esta interfaz, tenemos un tema que vendrá de
And then inside this interface, we have a theme which will be coming from
12:25:00
ese tema, ya sea el tema claro o el tema oscuro, luego
that theme like either the light or the dark theme then
12:25:03
tenemos una función de alternar que solo devolverá el blanco, luego estamos creando
we have a toggle function which will only return the white then we are creating
12:25:06
nuestro contexto y este contexto tomará el contexto de tema
our context and this context will either take the theme context
12:25:10
o indefinido, así que para el valor inicial estamos
type or undefined so for the initial value we
12:25:13
especificando indefinido, ahora estamos creando nuestro proveedor y dentro de este proveedor va a tomar un hijo, así que ahora solo estamos anotando ahí mismo y ahora dentro de ahí estamos creando nuestro tema
are now specifying undefined to there now we are creating our provider and inside this provider is going to take a children so we are now just annotating there right here and now inside there we are now creating our theme
12:25:24
que será compartible para todos nuestros componentes. Así que ahora solo estamos creando un compartir para nuestro tema y el valor inicial se establecerá en claro.
which will be shareable for all of our components. So we are now just creating a share for our theme and the initial value will be set to light.
12:25:31
También estamos creando una función de alternar tema que nos permite proporcionar el claro o el oscuro o alternar entre el claro o el oscuro.
We are also creating a toggle theme function which allows us to either provide the light or dark or toggle that to either light or dark theme.
12:25:40
Luego simplemente estamos pasando el tema y también la función de alternar tema a nuestro proveedor de contexto como proveedor de contexto de tema para ser precisos.
Then we are just passing the theme and also the toggle theme function to our context provider like theme context provider to be precise.
12:25:47
Y aquí puedes ver que tenemos nuestro componente de tema y ahora dentro de este componente de tema estamos envolviendo nuestro componente de tarjeta
And here you can see we have our theme component and now inside this theme component we are now wrapping our card component
12:25:53
usando nuestro proveedor de tema, está bien y
by using our theme provider okay and
12:25:56
finalmente solo estamos creando un gancho personalizado que es un uso de tema
finally we are just creating a custom hook which is a use theme
12:25:59
y estamos verificando si tenemos el contexto, así que genial
and we are checking if we have the context so cool
12:26:02
obten el contexto, pero si no tienes el contexto entonces
get the context but if you don't have the context then
12:26:05
muestra este error como que el uso de tema debe estar dentro del proveedor de tema
show this error like use theme must be within the theme provider
12:26:09
componente, así que eso es todo para este componente ahora
component so that's everything for this component now
12:26:12
déjame ir a mi componente de tarjeta y no estamos haciendo nada loco, pero primero estamos importando nuestro contexto del tema
let me go ahead and go to my card component and we are not doing anything crazy but we are first of all importing our context from theme
12:26:19
contexto y ahora los estamos pasando al uso del contexto
context and we are now passing them to the use context
12:26:22
y si no tenemos el contexto, entonces vamos a estar renderizando
and if we don't have the context so then we're going to be rendering
12:26:25
este error, así que si tenemos el contexto, vamos a
this error so if we have the context so we're going
12:26:28
desestructurar el tema y también la función de alternar tema
to be destructuring the theme and also the toggle theme function
12:26:31
desde ahí estamos proporcionando un poco de estilo a eso y
from there we're providing a bit of styling to there and
12:26:34
ahora estamos renderizando nuestro tema totalmente de manera dinámica, así que si nuestro tema
we are now rendering our theme totally dynamically so if our theme
12:26:37
es igual a claro, entonces vamos a cambiar el color de fondo a
is equal to light then we're going to be changing the background color to
12:26:40
totalmente blanco, pero si ese no es el caso, vamos a cambiar el color de fondo a un color tipo azul verdoso, está bien y también estamos
totally white but if that's not the case we're going to be changing the background color to kind of a tealish color okay and we are also
12:26:47
proporcionando nuestro h1, proporcionando nuestro estilo totalmente de manera dinámica
providing our h1 providing our styling totally dynamically
12:26:50
y también estamos creando algún tipo de párrafo y
and also we are creating some sort of a paragraph and
12:26:54
proporcionando nuestro estilo a ellos y finalmente tenemos nuestro botón
providing our style to them and and finally we have our button
12:26:57
que nos permite alternar nuestro tema, así que así es como
which allows us to toggle our theme so this is how
12:27:00
se verá la interfaz de usuario, como puedes ver, tengo esta interfaz de usuario, tengo esta
the ui will look like as you can see i have this ui i
12:27:03
tarjeta de tema y también algún tipo de lorem ipsum, si
have this theme card and also some sort of a lorem ipsum if
12:27:06
hago clic en este interruptor para el modo oscuro, se convertirá en modo oscuro, si hago clic allí una vez más, se convertirá en modo totalmente claro
i click on this switch to dark mode it's going to make it as a dark mode if i click on there once again so it's going to make it totally light mode
12:27:13
así que sí, esto es lo que está pasando ahora usando el react 19
so yeah this is what's going on now using the react 19
12:27:16
versión, ya no tenemos que usar lo que
version we no longer have to use what do
12:27:20
llamamos, eh, este uso del contexto, así que
we call it uh this use context so
12:27:23
ahora podemos reemplazar eso completamente con la función de uso, así que cómo estamos
now we can totally replace that with the use function so how are
12:27:26
vamos a hacer allí, voy a comentar esta línea y voy a importar
we going to be doing there i'm going to comment this line out and i'm going to be importing
12:27:29
la función de uso o gancho de dónde de
the use function or hook from where from
12:27:32
react js y ahora ya no tenemos que usar el contexto de uso, solo vamos a usar el uso, así que ahora si guardo mi archivo, pruebo esto y hago clic allí
the react js and now we no longer have to use the use context we're going to be only using the use okay so now if i save my file test this out and click on there
12:27:42
aún funciona exactamente igual, así que sí, eso es
still it works exactly the same so yeah that's
12:27:46
el único cambio que tenemos que hacer para el react 19
the only change that we have to do for the react 19
12:27:49
ahora hablemos sobre acciones en react 19, pero
now let's talk about actions in react 19 but
12:27:52
primero que nada quiero decir que solo vamos a cubrir acciones en
first of all i want to say that we're going to be only covering actions on
12:27:55
el lado del cliente, no vamos a cubrir allí en el lado del servidor porque
the client side we're not going to be covering there on the server side because
12:27:59
no aprendimos sobre el backend, así que por eso no vamos a cubrir allí, no ahora, pero lo cubriremos muy pronto, así que lo que voy a hacer es que voy a crear
we did not learn about the backend so that's why we're not going to be covering there not right now but we will cover there very soon so what i'm going to do is that i'm going to create
12:28:07
mi carpeta de componentes y dentro de allí vamos a definir nuestro
my components folder and inside there we're going to be defining our
12:28:10
archivo form.jsx o sabes qué, esto
form.jsx file or you know what this
12:28:14
debería ser un tsx más bien, así que ahora déjame cambiar eso a tsx, voy a
should be a tsx rather so now let me just change that to tsx i'm
12:28:17
usar mi componente rafc e ir a mi aplicación y
going to use my rafc component and go into my app and
12:28:20
registrar mi componente aquí mismo, así que vamos a crear nuestro formulario y
register my component right here so let's just create our form and
12:28:24
registrar este componente y aquí puedes ver que ahora estamos obteniendo nuestro formulario, así que primero voy a proporcionar mi interfaz de usuario para eso y luego proporcionaremos el resto de las cosas, así que cambiaré
register this component and here you can see we are now getting our form so first of all i'm going to provide my ui to that and then we will provide the rest of the stuff so i'll change
12:28:33
es dar a un formulario y ahora dentro de este formulario vamos
is give to a form and now inside this form we
12:28:36
a crear una etiqueta y esta etiqueta será una
are going to be creating a label and this label will be a
12:28:39
etiqueta de nombre, así que solo escribiré como etiqueta para el nombre y
name label so i'll just write like label for the name and
12:28:42
también vamos a proporcionar un campo de entrada con el tipo de texto y
we are going to be also providing an input field with the type of text and
12:28:45
también vamos a proporcionar un id y el id se establecerá en nombre y por favor no olvides esto, tienes que especificar un nombre si quieres trabajar con un formulario
we are going to be also providing an id and the id will be set to name and please do not forget this one you have to specify a name if you want to work with a form
12:28:55
ok, así que tienes que especificar algún tipo de nombre para tu campo de entrada, así que solo escribiré como nombre para este y ahora voy a guardar eso, así que ahora debajo de esto también vamos a crear, déjame escribir un br aquí, así que también vamos a crear una etiqueta para el correo electrónico
okay so you have to specify some sort of a name for your input field so i'll just write like name for this one and now i'm going to save that so now underneath this one we're going to be also creating let me just write a br right here so we're going to be also creating a label for the email
12:29:07
escribiré como etiqueta y solo escribiré como correo electrónico y
i'll write like label and i'm going to just write like email and
12:29:10
también correo electrónico allí, ahora déjame proporcionar mi campo de entrada con el tipo
also email there now let me just provide my input field with the type
12:29:13
de ustedes saben qué correo electrónico estaría bien, así que solo cambiaré eso a correo electrónico que yo
of you know what email would be fine so i'll just change that to email i'll
12:29:16
también proporcionaré mi identificación de correo electrónico y una vez más no puedo enfatizar lo suficiente que tienes que especificar el nombre si estás trabajando con las acciones, tenemos que especificar algún tipo de nombre
also provide my id of email and once again i can't stress that enough you have to specify the name if you are working with the actions we have to specify some sort of a name
12:29:25
para eso y sí, ahora debajo de este vamos a crear nuestro
for that and yeah now underneath this one we're going to be creating our
12:29:28
br una vez más y vamos a crear una etiqueta más y también
br once again and let's just create one more label and also
12:29:32
un campo de entrada para la contraseña, así que solo escribiré como contraseña y
an input field for the password so i'll just write like password and
12:29:35
entonces la contraseña dentro de ahí, así que solo usaré mi entrada
then password inside there so i'll just use my input
12:29:38
campo con el tipo de contraseña en este caso y vamos a estar
field with the type of password in this case and we're going to be
12:29:41
también proporcionando una identificación y la identificación tomará una contraseña y una vez más vamos a proporcionar un nombre y el nombre será contraseña, así que ahora debajo de eso, vamos a crear algo que nos permita enviar nuestro formulario.
also providing an id and the id will take a password and once again we're going to be providing a name and the name will be password so now underneath that let's just create which allows us to submit to our form.
12:29:52
Así que solo escribiré un BR. Y ahora vamos a crear un botón para enviar.
So I'll just write a BR. And now we're going to be creating a button for the submit.
12:29:57
Así que solo pondré un tipo y el tipo será enviar. Está bien. Y sí, solo voy a guardar este archivo. Así es como se ve mi formulario.
So I'll just put a type and the type will be submit. Okay. And yeah, I'm going to just save this file. This is how my form looks like.
12:30:03
Sé que se ve súper feo. Así que ahora déjame proporcionar un poco de estilo a eso.
I know it is looking super ugly. So now let me just provide a bit of styling to that.
12:30:08
Así que lo que voy a hacer es proporcionar este estilo a este campo de entrada, a este campo de entrada y también a este campo de entrada.
So what I'm going to do is that I'm going to provide this styling to this input field, to this input field, and also to this input field.
12:30:15
También vamos a proporcionar un estilo diferente para este botón de enviar. Así que ahora déjame presionar esto. Así que ahora si guardo mi archivo y reviso esto.
We're going to be also providing a different styling for this submit button. So now let me just press this. So now if I save my file and check this out.
12:30:21
Así que aquí puedes ver cómo se ve mi interfaz de usuario. i
So here you can see this is how my UI looks like. i
12:30:24
sé que es increíble, ¿verdad? sí, lo es
know super amazing right yeah it is
12:30:27
increíble, así que hablemos sobre los formularios, así que
amazing so let's talk about the forms so
12:30:31
como dije, los formularios son solo una función asincrónica que
as i said that forms are just an asynchronous function which
12:30:34
vamos a estar adjuntando el formulario hacia adelante, así que lo que tenemos que hacer
we are going to be attaching forward form so what we have to do
12:30:37
quiero decir, como acción o función asincrónica que vamos a estar adjuntando hacia adelante
i mean like action or asynchronous function which we are going to be attaching forward
12:30:41
formulario no sé qué demonios acabo de decir en primer lugar, así que
form i don't know what the hell i just said in the first place so i'll
12:30:44
solo usaré como acción, solo tenemos que especificar nuestra acción y cambiar eso al código php si ustedes están al tanto
just use like action we just have to specify our action and change that to the php code if you guys are aware
12:30:51
de un código php, ustedes ya saben todas esas cosas, pero si
of a php code you guys already know all of that stuff but if
12:30:54
no lo saben, no tienen que preocuparse por eso, así que aquí tenemos que especificar
you don't you don't have to worry about that so here we have to specify
12:30:57
algún tipo de función de flecha o algún tipo de función, así que
some sort of a arrow function or some sort of a function so i'll
12:31:00
usaré como función de acción de formulario y esto debería ser
use like form action function and this should be
12:31:03
acción función de acción de formulario y ahora voy a copiar
action form action function and now i'm going to copy
12:31:06
ellos y ahora déjame crear eso aquí mismo, así que usaré como
them and now let me just create that right here so i'll use like
12:31:10
constante acción de formulario y va a tomar un perímetro especial que será un formulario de datos, está bien, así que ahora dentro de eso lo que tenemos que hacer es crear algún tipo de datos de usuario, así que usaré como constante datos de usuario
const form action and it's going to take a special perimeter which will be a form data okay so now inside then what we have to do we have to create some sort of a user data so i'll use like const user data
12:31:22
va a ser igual a este objeto y ahora voy a proporcionar la propiedad de nombre
it's going to be equals to this object and now i'm going to provide the property of name
12:31:25
ahí y esos datos vendrán de este formulario de datos
to there and that data will be coming from this form data
12:31:28
ahí y esos datos vendrán de este formulario de datos, ahora estamos adjuntando esta función a
we are now attaching this uh function to
12:31:32
este formulario usando nuestra acción, luego estamos proporcionando este perímetro que es un formulario de datos, así que ahora vamos a copiar y pegar ahí, luego tenemos una propiedad dentro de esto, si solo uso el punto get
this form by using our action then we are providing this perimeter which is a form data so now we are going to be copying and pasting there then we have a property inside this if i just use the dot get
12:31:43
y aquí ahora podemos obtener nuestros datos, así que dónde en el mundo
and here we can now get our data so where in the world
12:31:46
está viniendo este nombre, este nombre está viniendo de
is this name coming from this name is coming from
12:31:49
este nombre que ahora estamos proporcionando aquí, está bien, así que es
this name which we are now providing right here okay so it's
12:31:53
va a seleccionar ese formulario de nombre o esa entrada de nombre, para ser precisos, ahora
going to select that name form or that name input to be precise now
12:31:56
voy a proporcionar una coma, también voy a proporcionar un correo electrónico y para el correo electrónico
i'm going to provide a comma i'm going to also provide an email and for the email
12:31:59
vamos a proporcionar nuestro método de objetivo de formulario una vez más y ahora vamos a proporcionar nuestro correo electrónico y finalmente también tenemos que crear eso para la contraseña, así que
we're going to be providing our form data target method once again and now we're going to be providing our email and finally we have to also create that for the password so i'll
12:32:07
usaré como datos de formulario y luego método get y proporcionar nuestra contraseña
use like form data and then get method and provide our password
12:32:11
en este caso contraseña, ahí vamos, ahora voy a guardar
in this case password there we go now i'm going to save
12:32:14
mi archivo y ahora debajo de eso tenemos que simplemente registrar en la consola este usuario
my file and now underneath that we have to just log to the console this user
12:32:18
datos y ahora déjame simplemente guardarlos, nos está dando un error
data and now let me just save them it is giving us an error
12:32:21
y sabes qué, déjame simplemente proporcionar cualquier tipo
and you know what let me just provide like any type
12:32:24
ahí, así que sí, ahora estamos obteniendo todos sus datos, así que sabes qué, simplemente vamos a revisar esto y ahora si abro mi consola, simplemente vamos a ir a nuestra
to there so yeah we are now getting all of their data so you know what let's just go ahead and check this out and now if i open my console let's just go ahead and go to our
12:32:32
consola y voy a proporcionar mi nombre como Huzan y luego algo o prueba en gmail.com y alguna contraseña aleatoria.
console and I am going to provide my name like Huzan and then something or test at gmail.com and some random password.
12:32:43
Ahora, si hago clic en el botón de enviar, nos va a dar esos datos aquí mismo.
Now if I click on the submit button it's going to give us that data right here.
12:32:47
Como puedes ver, tengo mis datos de nombre, tengo mis datos de correo electrónico y también tengo mis datos de contraseña.
As you can see I have my name data, I have my email data and I also have my password data.
12:32:52
Así que ahora eres totalmente libre de hacer lo que quieras con esos datos.
So now you are totally free to do whatever you want to do with that data.
12:32:56
Puedes modificar totalmente ahí, puedes enviar eso a un servidor, puedes hacer lo que quieras con esos datos. Así que ahora déjame explicarlo una vez más.
You can totally modify there, you can send that to a server, you can do whatever you want to do with that data. So now let me just explain that once again.
12:33:03
Primero que todo, vamos a crear algún tipo de formulario y luego tenemos que especificar algún tipo de campo de entrada de nombre hacia adelante para que podamos seleccionar ese campo de entrada específico por ese nombre específico.
First of all, we are going to be creating some sort of a form and then we have to specify some sort of a name forward input field so that we can select that specific input field by that specific name.
12:33:13
También tenemos que usar nuestra acción y para esta acción, vamos a proporcionar algún tipo de función.
We also have to use our action and for this action, we are going to be providing some sort of a function.
12:33:18
Así que puedes pasar tu función aquí o puedes crearla por separado como lo hice aquí.
So you can pass your function right here or you can create this separately as I did right here.
12:33:23
Está bien, así que ahora dentro de esta función, tomará estos datos del formulario como un perímetro, y puedes obtener tus datos utilizando este método form data.get, y aquí tienes que especificar tu nombre.
Okay, so now inside this function, it's going to take this form data as a perimeter, and you can totally get your data by using this form data.get method, and here you have to specify your name.
12:33:33
Está bien, y luego puedes hacer lo que quieras con esos datos. Así que sí, eso fue solo lo básico de las acciones en React.js del lado del cliente.
Okay, and then you can do whatever you want to do with that data. So yeah, that was just the basics of actions in React.js on the client side.
12:33:41
No vamos a cubrir el lado del servidor porque aún no hemos llegado allí.
We're not going to be covering the server side because we are not there yet.
12:33:44
Así que ahora hablemos del hook más fácil, un poco raro y también no tan útil en React 19, que se llama el hook use form.
So now let's talk about the most easy, a bit weird, and also not that much useful hook in React 19, which is called the use form hook.
12:33:53
Así que lo que voy a hacer es crear mi carpeta de componentes, y voy a crear mi form.tsx dentro de allí.
So what I'm going to do is that I'm going to create my components folder, and I'm going to create my form.tsx inside there.
12:33:59
Y simplemente usemos nuestro rfce, guardemos mi archivo y registremos este componente aquí.
And let's just use our rfce, save my file, and register this component right here.
12:34:04
Esto se usará como un formulario, y aquí entra, así que nos dará ese formulario justo aquí, que se ve genial.
This will use like form, and here it enters, so it's going to give us that form right in here, which is looking cool.
12:34:11
Así que simplemente vamos a eliminarlos. Y primero que nada, voy a eliminar eso y cambiarlo a un formulario.
So let's just remove them. And first thing first, I'm going to just remove that and change that to a form.
12:34:16
Y dentro de este formulario, vamos a crear nuestro div. Y dentro de este div, tenemos que proporcionar nuestra etiqueta.
And inside this form, we're going to be creating our div. And inside this div, we have to provide our label.
12:34:21
Y para esta etiqueta, tenemos que proporcionar algún tipo de etiqueta como nombre o algo así. Y ahora debajo de eso, también vamos a crear un campo de entrada con un tipo de texto.
And for this label, we have to provide some sort of a label like name or something. And now underneath there, we're going to be also creating an input field with a type of text.
12:34:28
También vamos a proporcionar una clase de borde. Todo alrededor se establecerá en 2. Y el ID se establecerá en nombre.
We're going to be also providing a class of border. All around will be set to 2. And the ID will be set to name.
12:34:35
Y también vamos a proporcionar un nombre específico porque vamos a usar nuestra acción dentro de allí. Y esto debería ser obligatorio.
And we're going to be also providing a specific name because we're going to be using our action inside there. And this should be required.
12:34:42
y ahora debajo de este div vamos a definir otro div así que
and now underneath this div we are going to be defining yet another div so
12:34:46
usemos nuestro div y proporcionemos mi etiqueta dentro de allí y tenemos que especificar el correo electrónico y el correo electrónico así
let's use our div and provide my label inside there and we have to specify the email and email like so
12:34:52
dentro de allí tenemos que especificar nuestra entrada con un tipo de
inside there we have to specify our input with a type of
12:34:55
correo electrónico y también vamos a proporcionar un
email and we are going to be also providing an
12:34:58
id y el id será un correo electrónico también tenemos que
id and the id will be an email we also have to
12:35:01
especificar el nombre y el nombre será un correo electrónico y
specify the name and the name will be an email and
12:35:04
esto también debería ser obligatorio y finalmente
this should be required too and finally
12:35:07
vamos a crear un botón pero lo vamos a crear allí
we are going to be creating a button but we are going to be creating there
12:35:11
en un componente separado que será un botón de formulario, así que
in a separate component which will be a form button okay so
12:35:14
por eso dije que el hook de estado del formulario es un poco raro porque siempre que tenemos que usar esa función tenemos que crear un componente separado
that's why i said that form status hook is a bit weird one because whenever we have to use that function we have to create a separate component
12:35:22
o usar ese hook tenemos que crear un componente separado para eso así que
or use that hook we have to create a separate component for that so
12:35:25
lo que voy a hacer es que voy a seguir adelante y definir o crear mi componente
what i'm going to do is that i'm going to go ahead and define or create my component
12:35:28
para ello aquí con el nombre de form button dot tsx
for it here with the name of form button dot tsx
12:35:32
solo voy a usar mi rafce dentro de ahí y
i'm going to only use my rafce inside there and
12:35:35
solo llama a esta función semi archivo importa este componente
just call this function semi file import this component
12:35:39
aquí ahora también voy a crear una acción para mi formulario así que usaré como uh acción y aquí tenemos que especificar algún tipo de acción así que daré el nombre de como mi acción.
right here now i'm going to also create an action for my form so i'll use like uh action and here we have to specify some sort of action so i'll give the name of like my action.
12:35:49
Voy a copiar eso. Vamos a crear esta acción aquí mismo.
I'm going to copy that. Let's just create this action right here.
12:35:52
Así que lo que voy a hacer es que solo voy a crear mi acción y esto debería ser una acción asincrónica.
So what I'm going to do is I'm going to just create my action and this should be an asynchronous action.
12:35:57
Aquí tenemos que especificar nuestros datos del formulario y dentro de estos datos del formulario vamos a estar usando como un rojo y luego nueva promesa.
Here we have to specify our form data and inside this form data we're going to be using like a red and then new promise.
12:36:04
Y esa es la única razón por la que marcamos eso como un componente o acción asincrónica para ser precisos.
And that's the only reason we mark that as an asynchronous component or action to be precise.
12:36:09
Y dentro de esta promesa tenemos que proporcionar un resolver y cuando esto se resuelva vamos a estar disparando esta función que es un set timeout y aquí tenemos que especificar la función resolver para eso.
And inside this promise we have to provide a resolve and when this is resolved we are going to be firing this function which is a set timeout and here we have to specify the resolve function to that.
12:36:18
Y también tenemos que proporcionar el retraso de 2000. Ahora debajo de eso vamos a estar obteniendo nuestros datos.
And also we have to provide the delay of 2000. Now underneath there we are going to be getting our data.
12:36:23
Así que usaré como nueva publicación o publicación más bien. Y dentro de ahí vamos a estar primero obteniendo el nombre.
So I'll use like new post or post rather. And inside there we are going to be first of all getting the name.
12:36:29
Y el nombre vendrá de los datos del formulario. Y luego tenemos que usar el método get para obtener los datos usando nuestro nombre.
And name will be coming from the form data. And then we have to use the get method to get the data by using our name.
12:36:35
Voy a duplicar y cambiar ahí a correo electrónico. Y también cambiar este a correo electrónico también.
I'm going to also duplicate and change there to email. And also change this one to email as well.
12:36:40
Y ahora voy a estar usando como console.love de nueva publicación. Y ahora déjame guardar mi archivo.
And now I'm going to be using like console.love of new post. And now let me just save my file.
12:36:45
ahora estamos obteniendo este error así que solo voy a anotar ahí con la bandera any ahora este componente está terminado
we are now getting this error so i'll just annotate there with the any flag now this component is done
12:36:50
voy a proceder e ir a mi componente de botón de formulario y ahora vamos a
i'm going to go ahead and go to my form button component and now let's just
12:36:53
usar nuestro gancho de estado de formulario dentro de ahí así que lo primero
use our form status hook inside there so the first thing
12:36:56
que quiero hacer es que quiero agarrar mi uso de estado de formulario tenemos
that i want to do is that i want to grab my use form status we
12:37:00
que agarrarlos manualmente de dónde de react dom
have to grab them manually from where from the react dom
12:37:04
no de react js sino de react dom así que ahora que hemos llegado allí con éxito así que ahora voy a estar usando esto usaré como
not from the react js but from the react dom like so now that we successfully get there so now i'm going to be using this i'll use like
12:37:11
usar estado de formulario y ejecutar allí voy a almacenar en algún tipo
use form status and execute there i'm going to store in some sort
12:37:14
de variable como formulario o algo así ahora déjame registrar este formulario
of variable like form or something now let me just log this form
12:37:17
en la consola así que ahora si guardo mi archivo y ahora voy a
to the console so now if i save my file and now i'm going to go
12:37:20
adelante e ir a mi consola y aquí puedes ver que
ahead and go to my console and here you can see we
12:37:23
ahora estamos obteniendo un objeto y así que ahora si solo actualizo allí así que tenemos un
are now getting an object and so now if i just refresh there so we have an
12:37:26
acción que podemos proporcionar para nuestro formulario, no estamos interesados
action which we can provide for our form we are not interested
12:37:30
ahí también podemos tener datos que también podemos renderizar
in there we can also have a data which we can also render
12:37:33
dentro de nuestro componente no estamos interesados, ahí también tenemos diferentes métodos, no estoy muy seguro de qué en la palabra es un método, pero sí
inside our component we are not interested in there we also have a different methods i'm not quite sure what in the word is a method but yeah
12:37:40
tenemos esta bandera que está pendiente, así que ahora está dando
we have this flag which is a pending so now it is giving
12:37:43
nos un estado de nuestro formulario, está bien, así que
us a status of our form okay so
12:37:46
ahora solo estamos interesados en este pendiente, así que voy a desestructurar
we are now only interested in this pending so i'm going to just destructure
12:37:49
así que para desestructurar ahí, solo voy a usar
there so to destructure there i'm going to only use
12:37:52
este corchete y voy a usar como pendiente dentro
this bracket and i'm going to use like pending inside
12:37:55
ahí, está bien, así que ahora si solo uso como pendiente semi
there okay so now if i just use like pending semi
12:37:58
archivo una vez más y refresco ahí y ahora nos va a dar falso, ¿verdad?
file once again and refresh there and now it's going to give us false right
12:38:02
aquí, así que ahora lo que voy a hacer es que voy a simplemente eliminar ahí y cambiar
here so now what i'm going to do is that i'm going to just remove there and change
12:38:05
ahí con un componente de botón o solo un botón simple y queremos
there with a button component or just a simple button and we
12:38:08
también proporcionar un tipo y el tipo se establecerá en enviar y
also want to provide a type and the type will be set to submit and
12:38:11
aquí tenemos que especificar nuestra bandera, así que solo usaré como si
here we have to specify our flag so i'll just use like if
12:38:14
eso está pendiente, entonces hacer que este componente esté deshabilitado, pero
that is pending then make this component disable but
12:38:18
si eso no está pendiente, entonces podemos simplemente hacer lo que
if that's not pending so then we can just do whatever we
12:38:21
queremos hacer con eso y también voy a proporcionar como si tuviéramos un pendiente
want to do with that and i'm going to also provide like if we have a pending
12:38:24
estado, así que en esta situación podemos simplemente usar como enviando punto punto punto, pero si no es el caso, podemos simplemente escribir como enviar así
state so in this situation we can just use like submitting dot dot dot but if that's not the case we can just write like submit like so
12:38:32
enviar, ahí vamos, así que ahora si guardo mi archivo y pruebo esto
submit there we go so now if i save my file and test this
12:38:35
así que ahora déjame refrescar ahí y sí, sabes qué, déjame
out so now let me just refresh there and yeah you know what let me just
12:38:38
adelante y poner un inicio a este, copiaré
go ahead and put a start to this one i'll copy
12:38:42
esta vez y colocaré ahí mismo dentro
this time and place there right here inside
12:38:45
este campo de entrada, así que ahora ambos se ven bien, así que
this input field so now both of them are looking cool so
12:38:48
lo que voy a hacer es que voy a especificar hosain test en
what i'm going to do is i'm going to specify hosain test at
12:38:52
gmail.com y ahora si hago clic en este enviar y miro lo que pasó, ahora nos está dando un enviando y luego se enviará
gmail.com and now if i click on this submit and watch what happened it's now giving us a submitting and then it will submit
12:38:59
sus datos, nos va a dar todos sus datos aquí y luego nos dará su envío, déjame intentar eso una vez más, está bien, así que usaré algo, luego algo en gmail.com
their data it's going to give us all of their data right here and then it will give us their submit let me just try that once again okay so i'll use like something then something at gmail.com
12:39:11
tranquilo, ahí vamos, así que ahora si hago clic en eso una vez más, déjame limpiar esto
calm there we go so now if i click on there once again let me just clear this
12:39:14
si hago clic en eso una vez más, aquí puedes ver que ahora
out if i click on there once again here you can see it is now
12:39:17
nos está dando un envío y luego nos va a dar esos datos y
giving us a submitting and then it's going to give us that data and
12:39:20
luego nos va a dar su envío, no sé por qué estamos obteniendo este error, pero
then it's going to give us their submit i don't know why we are getting this error but
12:39:23
estamos llegando, así que este gancho solo nos dará el estado
we are getting there so this hook will only gives us the status
12:39:26
sobre nuestro formulario, así que ahora en este caso, ahora estamos
about our form so now in this case we are now
12:39:30
solo interesados en el estado pendiente, así que podemos usar totalmente
only interested in the pending state so we can totally use
12:39:33
eso, así que ahora hablemos sobre el gancho de estado de acción en react 19
that so now let's talk about the use action state hook in react 19
12:39:36
así que lo que voy a hacer es crear mis componentes
so what i'm going to do is i'm going to create my components
12:39:40
carpeta y dentro estarán proporcionando nuestro count.tsx y ahora dentro de ahí, simplemente usemos
folder and inside they will be providing our count.tsx and now inside there let's just use
12:39:46
nuestro RAFCE y registremos este componente justo aquí como mi contador o solo un conteo y ejecuta eso.
use our RAFCE and register this component right in here like my counter or just a count and execute that.
12:39:54
Y aquí puedes ver que ahora estamos obteniendo nuestro conteo, que se ve genial. Así que la primera cosa que quería usar, que quiero llamar
And here you can see we're now getting our count, which is looking cool. So the first thing that I wanted to use that I want to call
12:40:00
gancho de inicio de acción, así que usaré algo como usar acción y
use action start hook so i'll use like use action and
12:40:03
luego ven, usa el gancho de inicio de acción y
then come on use action start hook and
12:40:06
ahora vamos a obtener eso de react js, así que
now we are going to be grabbing that from the react js so
12:40:10
lo importaré usando import y luego usar acción viene
i'll import that by using import and then use action come
12:40:13
en el inicio de acción, todavía no me está dando una sugerencia, así que
on action start it is still not giving me a suggestion so
12:40:16
vamos a obtener eso de react js, está bien, importar
we are going to be grabbing that from the react js okay import
12:40:20
ahí vamos, así que ahora si digo mi archivo, todavía estamos obteniendo este error, no sé por qué, pero estamos obteniendo este error y lo que voy a hacer es que voy a
there we go so now if i say my file still we are getting this error i don't know why but we are getting this error and what i'm going to do is that i'm going
12:40:29
intentar explicar eso, pero quiero que me des unos segundos porque
try to explain that but i want you to give me a few seconds because
12:40:32
se necesita muchas cosas que estás
it takes a lot of things you're
12:40:35
desestructurando el estado y también la acción del formulario
going to be destructuring the state and also the form action
12:40:38
que podemos proporcionar para nuestro formulario, está bien, así que vamos a desestructurar
which we can provide for our form okay so we're going to be destructuring
12:40:41
el estado y también la acción del formulario y para el valor inicial
the state and also the form action and for the initial value
12:40:45
vamos a especificar primero la función de incremento que permitirá
we're going to be specifying first of all the increment function which will allow
12:40:48
cambiar nuestro formulario y también podemos especificar un valor inicial y el valor inicial será como básicamente cualquier cosa que quieras proporcionar, solo voy a proporcionar cero como valor inicial
us to change our form and we can also specify initial value and the initial value will be like basically anything you want to provide i'm going to only provide zero for the initial value
12:40:59
así que déjame explicarlo una vez más, primero
so let me just explain that once again first of all we
12:41:02
vamos a proporcionar algún tipo de función que nos permita cambiar nuestro
are going to be providing some sort of a function which allows us to change our
12:41:05
datos o nuestro estado inicial o simplemente nuestro estado, entonces
data or our initial state or just our state then
12:41:08
podemos proporcionar un valor inicial para nuestro estado y puede
we can provide an initial value for our state and it
12:41:11
ser cualquier cosa, puedes proporcionar una cadena, puedes proporcionar un objeto, puedes proporcionar
can be anything you can provide a string you can provide an object you can provide
12:41:14
un arreglo, puedes proporcionar cualquier cosa que prefieras, pero ahora en este caso
array you can provide anything that you prefer but now in this case
12:41:18
ahora estoy creando un contador, así que ahora estoy especificando un
i'm now creating a counter so i'm now specifying a
12:41:21
valor cero dentro del k y vamos a desestructurar el estado para que contenga el valor de cero dentro, lo que significa que
zero value inside the k and we're going to be destructuring the state to be holding the value of zero inside there which means like
12:41:28
ahora estamos desestructurando allí para que podamos usar el interior
we are now destructuring there so that we can use the inside
12:41:31
nuestra interfaz de usuario, entonces tenemos una acción y ya has
our ui then we have an action and you already
12:41:34
aprendido qué es la acción, así que también te voy a mostrar eso en
learned like what in the what is the action so i'm going to also show you that in
12:41:37
unos segundos, lo que significa que vamos a estar usando el interior de nuestro formulario
a few seconds which means like we're going to be using the inside of our form
12:41:40
así que ahora déjame guardar eso y voy a cambiarlo a un formulario
so now let me just save that and i'm going to change that to a form
12:41:44
una vez más y también cambiar este a un formulario, así que ahora vamos a
once again and also change this one to a form so now let's
12:41:47
simplemente eliminar este conteo de aquí y voy a estar usando mi h1 en
just remove this count from here and i'm going to be using my h1 come
12:41:50
este h1 y solo diré como, uh, solo renderizaré mi recto dentro de allí, pero me dará un error y adivinas por qué nos dará un error.
on this h1 and i'll just say like uh i'll just render my straight inside there but it will give me an error and you guessed it why it will give us an error.
12:41:59
Así que solo proporcionaré un estilo de como texto 3xl. Nos dará un error porque tenemos que crear esta función aquí o esta acción, como quieras llamarlo.
So I'll just provide a styling of like text 3xl. It's going to give us an error because we have to create this function right here or this action whatever you want to call that.
12:42:07
Así que solo usaré como una bandera asíncrona y crearé mi función dentro de allí así y el nombre será incrementar.
So I'll just use like async flag and create my function inside there like so and the name will be increment.
12:42:13
Así que tomará algunos parámetros. Ahora déjame proporcionar como el estado anterior y también obtendrá los datos del formulario.
So it's going to take a few perimeter. Now let me provide like previous state and it's going to also get the form data.
12:42:20
Si no quieres proporcionar este estado anterior, no tienes que hacerlo, pero si quieres obtener los datos, tienes que especificar los datos del formulario allí.
If you don't want to provide this previous state you don't have to but if you want to get the data you have to specify the form data 2 there.
12:42:27
Está bien, así que quiero usar mi estado anterior. Así que también nos dará un estado anterior para ello aquí.
Okay, so I want to use my previous state. So it's going to also give us a previous state for it here.
12:42:31
Así que ahora, si quiero registrar en la consola mis datos, voy a estar usando como el método get de los datos del formulario.
So now if I want to log to the console of my data, so I'm going to be using like form data dot get method.
12:42:39
Y aquí tenemos que especificar el nombre dentro de allí. ¿Y por qué es eso? Oh, no creamos lo que llamamos.
And here we have to specify the name inside there. And why is that? Oh, we did not create what we call it.
12:42:45
No creamos nuestro campo de entrada. Pero sí, vamos a obtener nuestros datos usando este nombre. Y además, simplemente usemos nuestra declaración de retorno.
We did not create our input field. But yeah, we are going to be getting our data by using this name. And also, let's just use our return statement.
12:42:52
Y aquí tenemos que especificar nuestro estado anterior más uno, está bien.
And here we have to specify our previous state plus one okay
12:42:56
Así que ahora voy a guardar mi archivo, sé que nos está dando muchos errores, pero
so now i'm going to save my file i know it is giving us a lot of errors but
12:42:59
no tenemos que preocuparnos por los errores en este momento, solo tenemos que preocuparnos por
we don't have to worry about the errors right now we only have to care about
12:43:02
esto usa acciones de formulario, así que así es como vamos a renderizar
this use form actions so this is how we are going to be rendering
12:43:05
nuestros datos y ahora déjame mostrarte, así que aquí puedes ver que ahora estamos obteniendo el inicial
our data and now let me show you so here you can see we're now getting the initial
12:43:08
valor de cero porque estamos proporcionando un cero allí, pero si cambio eso a este número y guardo mi archivo, ahora déjame refrescar eso y aquí puedes ver que nos va a dar ese número justo aquí, así que voy a hacer eso
value of zero because we are providing a zero to there but if i change that to this number and save my file now let me just refresh that and here you can see it's going to give us that number right here so i'm going to make that
12:43:20
como un cero justo aquí una vez más y ahora tenemos que crear
as a zero right here once again and now we have to create
12:43:23
nuestro botón que nos permite incrementar o cambiar nuestro
our button which allows us to increment or change our
12:43:26
estado, así que usaré ese botón y dentro de este botón voy a
state so i'll use that button and inside this button i'll
12:43:29
proporcionar mi bandera de incremento justo aquí y también voy a proporcionar un poco de
provide my increment flag right here and also i'm going to provide a bit of
12:43:32
estilo como el fondo se establecerá en totalmente tail de 300 300
styling like background will be set to totally tail of 300 300
12:43:36
y también el padding se establecerá en dos y voy a estar usando mi acción de formulario
and also padding will be set to two and i'm going to be using my form action
12:43:39
dentro de allí y aquí tenemos que especificar nuestra acción de formulario
inside there and here we have to specify our form action
12:43:42
está bien, que estamos proporcionando justo aquí, voy a proporcionar mi br, así que usaré como br y ahora debajo de allí tienes que crear qué entrada
okay which we are providing right here i'm going to provide my br so i'll use like br and now underneath there you have to create what input
12:43:50
y el tipo se establecerá en texto, también vamos a proporcionar un
field and the type will be set to text we're going to be also providing a
12:43:53
placeholder y solo diré como por favor ingresa tu nombre
placeholder and i'll just say like please enter your name
12:43:56
ingresa maldita sea, ingresa tu nombre así y
enter god damn it enter your name like so and
12:44:00
también voy a proporcionar un poco de clases a esto, así que como el borde se establecerá en dos píxeles alrededor y ahora déjame usar ese nombre y qué proporcioné justo aquí, ahora estamos obteniendo nuestros datos usando este nombre
also i'm going to provide a bit of classes to it so like border will be set to two pixel all around and now let me just use that name and what did i provide right here we are now getting our data by using this name
12:44:11
así que tenemos que especificar ese nombre, vamos nombre
so we have to specify that name come on name
12:44:14
justo aquí, así que ahora si guardo mi archivo, prueba esto y aquí
right here so now if i save my file test this out and here
12:44:17
puedes ver que ahora estamos obteniendo mucha rareza, pero ahora déjame refrescar
you can see we're now getting a lot of weirdness but now let me just refresh
12:44:20
ahí y sí, si hago clic en esta función de incremento
there and yeah if i click on this increment function
12:44:23
así que nos va a permitir incrementar o contar y
so it's going to allow us to increment or counter and
12:44:26
si escribo algo allí dentro y hago clic en este incremento, es
if i type something inside there and click on this increment it's
12:44:30
va a darnos también los datos dentro de allí, así que sí, esa fue nuestra acción de estado de uso, déjame explicarlo una vez más, esta función
going to also give us the data inside there so yeah that was our use action state let me just explain that once again this function
12:44:37
tomará una función de incremento o algún tipo de función que nos permita cambiar nuestro valor inicial y así es como vamos a proporcionar un valor inicial allí.
will take an increment function or some sort of a function which allows us to change our initial value and this is how we are going to be providing an initial value to there.
12:44:44
Nos va a dar un estado que podemos renderizar dentro de nuestra interfaz de usuario.
It's going to give us a state which we can render inside our UI.
12:44:48
También nos va a dar una acción de formulario que podemos ejecutar en nuestro botón específico o en nuestra acción específica.
It's going to also give us a form action which we can execute on our specific button or on our specific action.
12:44:54
Así que esta es la forma en que vamos a crear nuestra función de incremento. Va a tomar un estado anterior y también va a tomar datos de formulario.
Okay, so this is how we are going to be creating our increment function. It's going to take a previous state and it's going to also take a form data.
12:45:00
Y ahora estamos registrando esos datos en nuestra consola. Y también estamos incrementando nuestro contador en uno.
And now we are logging that data to our console. And we're also just incrementing our counter by one.
12:45:07
Y sí, eso fue todo sobre el estado de acción de uso en React 19. Bien, así que ahora hablemos sobre el gancho de transición de uso en React.js.
And yeah, that was just about the use action state in React 19. Okay, so now let's talk about the use transition hook in React.js.
12:45:13
Así que lo que voy a hacer es crear mi carpeta de componentes.
So what I'm going to do is that I'm going to create my components folder.
12:45:18
Y dentro de allí, vamos a crear muchos componentes. Así que usaré algo como home.tsx.
And inside there, we're going to be creating a lot of components. So I'll use like home.tsx.
12:45:22
también voy a usar el contact.tsx
tsx i'm going to also use the contact.tsx
12:45:25
y también el post.tsx
and also um the post.tsx
12:45:29
así que usaré mi rafce dentro de este componente
so i'll use my rafce inside this component
12:45:32
rafce rafce rafce
rafce rafce rafce
12:45:37
rafce dame un pipsy
rafce give me a pipsy
12:45:40
o qué, qué demonios estoy diciendo, así que
or what what the fuck am i saying so
12:45:44
esto es crear lo que empieza, usaré algo como active tab y luego set active tab va a ser igual
this is create what starts i'll use like active tab and then set active tab is going to be equals
12:45:50
a esta función que es una función de inicio de uso y el valor inicial
to this function which is a use start function and the initial value
12:45:53
se establecerá en home y ahora tenemos que crear una función que
will be set to home and now we have to create a function which
12:45:57
nos permita renderizar nuestro contenido, así que usaré algo como render content
allows us to render our content so i'll use like uh render content
12:46:01
y aquí solo vamos a crear una función y
and here we're going to be just creating a function and
12:46:04
aquí solo tenemos que usar nuestro switch y casos, así que
here we just have to use our switch and cases baby so
12:46:08
usaré algo como active tab y para el caso de active tab
i'll use like active tab and for the active tab case
12:46:11
vamos a proporcionar un home y ahora vamos a devolver el componente home del sls import tab, eliminar el
we're going to be providing a home and now we're going to be returning the home component from the sls import tab remove the
12:46:18
spread de aquí y también proporcionar un caso para el post
spread from here and also provide a case for the post
12:46:21
así y devolver el post post
like so and return the post post
12:46:25
ahí vamos y también voy a cerrar eso ahora
there we go and i'm going to also close that now we
12:46:28
también tenemos que usar el caso y el caso se establecerá para el contacto
also have to use the case and the case will be set for the contact
12:46:31
y si ese es el caso, vamos a devolver el contacto
and if that's the case so we're going to be returning the contact
12:46:35
componente y primero quiero darte el ejemplo sin
component and first i want to give you the example without
12:46:38
usar el gancho de transición y luego vamos a refactorizar ese gancho, quiero decir, luego vamos a refactorizar ese código para usar el
using the use transition hook and then we're going to be refactoring that hook i mean like then we're going to be refactoring that code to use the
12:46:45
gancho de transición, así que ahora usaré como inicio e importar
use transition hook so now i'll use like home and import
12:46:48
ahí justo aquí, está bien, todo está funcionando como
there right here okay everything is working the way we
12:46:51
esperamos que funcione y ahora tenemos que crear nuestra interfaz de usuario, así que
expect him to work and now we have to create our ui so
12:46:54
voy a proceder a crear mi interfaz de usuario justo aquí, usaré
i'm going to go ahead and create my ui right here i'll
12:46:57
primero de todo mi día con la clase de pestañas y dentro
use first of all my day with the class of tabs and inside
12:47:00
ahí tenemos que crear nuestro botón y solo usaré como inicio
there we have to create our button and i'll just use like home
12:47:03
y luego cambiar ahí a publicación y luego cambiar ahí a contacto y voy a llamar a mi función ahí, así que cuando alguien intente hacer clic en esto
and then change there to post and then change there to contact and i'm going to be calling my function on there so when somebody tried to click on this
12:47:11
función vamos a activar estas funciones, así que como establecer
function we are going to be firing these functions so like set
12:47:14
pestaña activa y solo proporcionemos nuestras pestañas dentro
active tab and let's just provide our tabs inside
12:47:17
ahí, así que usaré como inicio, también voy a proporcionar una publicación dentro
there so i'll use like home i'm going to also provide a post inside
12:47:21
ahí y también voy a proporcionar un contexto, así que ahora si guardo mi archivo
there and i'm going to also provide a context so now if i save my file
12:47:24
y debajo de eso vamos a renderizar nuestro
and underneath that we are going to be rendering our
12:47:27
contenido, así que solo crearé un div con la clase de contenido
content so i'll just create a div with the class of content
12:47:30
contenido maldita sea contenido
content god damn it content
12:47:33
ahí vamos y ahora tenemos que renderizar o cómo lo llamamos, renderizar la función de contenido dentro, ahora déjame, solo guardaré mi archivo, pero aquí hay un pequeño truco.
there we go and now we have to render or what do we call it render content function inside there now let me I will just save my file but here is a bit of catch.
12:47:44
Si sigo adelante, también proporcionaré un poco de estilo a estos botones.
If I go ahead and I will also provide a bit of styling to these buttons.
12:47:48
Así que solo seleccionaré y proporcionaré un nombre de clase de borde 2 y guardaré mi archivo. Sí, eso está bien.
So I will just select and provide a class name of border 2 and save my file. Yup that's cool.
12:47:54
Así que usaré emparejamiento por todas partes. Estaremos configurados en 4 y creo que se ve mejor. Así que si hago clic en el inicio, nos dará un inicio.
So I will use pairing for all around. We will be set to 4 and I guess that's looking better. So if I click on the home, it will give us a home.
12:48:01
Si hago clic en una publicación, nos dará una publicación. Si hago clic en el contacto, nos dará un contacto.
If I click on a post, it will give us a post. If I click on the contact, it will give us a contact.
12:48:05
Pero lo que voy a hacer es que voy a proceder a ir a la publicación. Solo quiero renderizar muchas publicaciones.
But what I am going to do is that I am going to go ahead and go to the post. I want to just render a lot of posts.
12:48:12
Así que simplemente generaré, vamos, generaré un montón de publicaciones.
So I'll just generate, come on, generate a lot of posts.
12:48:17
De acuerdo, para hacer eso, vamos a usar nuestras publicaciones. Y dentro de eso, vamos a usar el método array.from.
Okay, so to do that, we're going to be using our posts. And inside there, we're going to be using array.from method.
12:48:24
Y simplemente proporcionemos nuestra longitud y cuántas quieres.
And let's just provide our length and how many you want.
12:48:28
Así que simplemente proporcionaré como 1, 2, 3, 4, 5, 6.
So I'll just provide like 1, 2, 3, 4, 5, 6.
12:48:33
De acuerdo, y luego no necesitamos los datos. Solo necesitamos el índice.
Okay, and then we don't need the data. We only need the index.
12:48:37
y voy a escribir como publicación dentro de eso o simplemente una publicación simple
and I'm going to just write like post inside there or just a simple post
12:48:40
y renderizaré mis datos dentro de eso como índice más
and render my data inside there like index plus
12:48:43
uno ahí vamos, así que ahora nos va a dar un montón de publicaciones
one there we go so now it's going to give us a lot of post
12:48:46
y ahora tenemos que iterar sobre todas sus publicaciones usando
and now we have to iterate over through all of their post by using
12:48:50
el método map y renderizar ahí, así que usaré como post.map
the map method and render there so I'll use like post.map
12:48:53
y aquí solo voy a proporcionar una publicación dentro de eso como una función de flecha y también voy a crear un div y dentro de este div tenemos que especificar qué clave y la clave se establecerá
and here I'm going to only provide a post inside there as an arrow function and I'm going to also create a div and inside this div we have to specify what key and the key will be set
12:49:02
en publicación y proporcionar un nombre de clase de publicación y dentro de este div tenemos que renderizar nuestra publicación.
to post and provide a class name of post and inside this div we have to render our post.
12:49:08
Así que ahora, si guardo mi archivo y ahora si hago clic en esta publicación y miro lo que pasó, todo está congelado ahora.
So now if I save my file and now if I click on this post and watch what happened everything is now freezed out.
12:49:15
No puedo hacer clic en el inicio. No puedo hacer clic en el contacto.
I cannot click on the home. I cannot click on the contact.
12:49:18
Sabes qué, déjame decir eso una vez más, si voy y hago clic en esta publicación una vez más, ahora puedo hacer clic en el
You know what let me just say that once again if I go ahead and click on this post once again now I can click on the
12:49:27
inicio, puedo ir a la página de contacto
home i can go to the contact page
12:49:30
hasta que renderice todos esos datos no me dejará
until i render all of that data it will not let
12:49:33
ir a ningún otro componente y todo está totalmente congelado
me to go to any other component and everything is now totally freeze
12:49:36
así que si quieres probar este código por ti mismo, puedes ir totalmente
up so if you want to try this code by yourself you can totally go
12:49:39
adelante y probarlo por ti mismo, pero creo que estoy demostrando algo
ahead and try that by yourself but i think i'm demonstrating there a
12:49:42
un poco genial, si hago clic en esta publicación no puedo ir
bit cool if i click on this post i cannot go
12:49:45
a ningún otro componente hasta que todos esos datos se rendericen, de acuerdo, así que está tomando mucho tiempo y ahora para este tipo de situaciones vamos a usar el hook de uso de transición.
to any other component until all of that data is rendered okay so it is taking a lot of time and now for these kind of situation we are going to be using using the use transition hook.
12:49:55
No vamos a usar un hook de uso de transición en la vida cotidiana.
We are not going to be using a use transition hook in the day-to-day life.
12:49:59
esa es solo la cosa que tienes que tener en cuenta, pero
that's just the thing you have to keep in mind but
12:50:02
cada vez que quieras renderizar una gran cantidad de datos, como quiero decir
whenever you want to render a lot of data like i mean
12:50:06
esta cantidad de datos, así que para esta situación puedes usar el gancho de transición y sí, déjame mostrarte cómo podemos refactorizar nuestro código para usar el gancho de transición
this amount of data so for this situation you may use the use transition hook and yeah let me just show you how we can refactor our code to use the use transition hook
12:50:16
así que para hacer eso, primero voy a entrar en mi componente de aplicación y voy a importar el
so to do that first of all i'm going to go into my app component and i am going to import the use
12:50:21
gancho de transición de React, así que solo usaré como
transition hook from the react js so i'll just use like
12:50:24
uh, gancho de transición, así que solo voy a
uh use transition so i'll just
12:50:27
crear, primero que nada, o sabes qué, déjame llamar a esto usar
create first of all or you know what let me just call this use
12:50:30
transición, uh, función y voy a
transition uh function and i am going to
12:50:33
almacenar allí algún tipo de algo o algo así como que estoy
store there some sort of a something or something like i'm
12:50:37
voy a almacenar el interior de algo y registrar ese algo
going to store the inside the something and log that something
12:50:40
en la consola, así que ahora, si guardo mi archivo y voy a continuar e ir a mi elemento de inspección, ir a mi consola y ahora déjame refrescar allí, así que nos va a dar algunas cosas, primero nos va a dar el falso, también nos va a dar una función.
to the console so now if i save my file and i'm going to go ahead and go to my inspect element go to my console and now let me just refresh there so it's going to give us a few things it's going to give us first of all the false it's going to also give us a function.
12:50:53
Así que ese falso será el estado, como si está pendiente o no.
So that false will be the state like is it pending or not.
12:50:57
Está bien, así que si está pendiente, nos dará verdadero, pero si no está pendiente, nos dará falso.
Okay so if it is pending it's going to give us true but if it is not pending it's going to give us false.
12:51:02
Así que ahora, en este caso, no está pendiente, así que ahora nos está dando un falso y sí, tenemos una función que podemos proporcionar para datos cargados.
So now in this case it is not pending so it is now giving us a false and yeah we have a function which we can provide forward loaded data.
12:51:11
Así que lo que voy a hacer es que voy a reestructurar mi, ¿cómo lo llamamos?, está pendiente y también voy a reestructurar el inicio
So what I'm going to do is that I'm going to restructure my what do we call it is pending and I'm going to also restructure the start
12:51:19
de la función de transición desde allí. Ahora voy a eliminar esta línea de código.
start transition function from there. Now I'm going to delete this line of code.
12:51:24
A continuación, solo tenemos que refactorizar este código, así que también voy a colapsar allí
Next we only have to refactor this code so I'm going to also collapse there
12:51:28
y ahora voy a continuar y simplemente cambiar eso, en lugar de usar este establecer pestaña activa, voy a cambiar eso a algo como manejar el cambio de pestaña.
and now I'm going to go ahead and just change that instead of using this set active tab I'm going to change that to like a handle tab change or something.
12:51:36
Voy a copiar el nombre de allí y ponerlo aquí, y también voy a reemplazar allí con este manejar cambio.
I'm going to copy the name of there and put it there here and also I'm going to just replace there with this handle change.
12:51:44
Ahora voy a continuar y simplemente crear esa función manejar cambio, así que usaré esa constante
Now I'm going to go ahead and just create that handle change function so I'll use that constant
12:51:48
manejar cambio, va a tomar una pestaña como un parámetro y
handle change it's going to take a tab as a perimeter and
12:51:51
ahora dentro de esta función vamos a estar usando nuestra función de inicio de transición
now inside this function we're going to be using our start transition function
12:51:54
que viene de este uso de transición, así que solo tenemos que
which is coming from this use transition so we have to just it's
12:51:58
nos va a dar una función asíncrona que causa una actualización directa que
going to give us an asynchronous function which causes a straight update that
12:52:01
puede ser diferida, sé que esto es un poco complicado de
can be deferred i know this is a bit mouthful to
12:52:04
decir, pero sí, voy a proporcionar mi función de flecha
say but yeah i am going to provide my arrow
12:52:07
dentro de allí y ahora dentro de esta función de flecha estoy
function inside there and now inside this arrow function i'm
12:52:10
voy a usar un conjunto de pestañas activas y proporcionar mi pestaña allí, básicamente llamaré a este conjunto de pestañas activas y tenemos que especificar esta pestaña
going to be using a set active tab and provide my tab inside there i'll basically call this set active tab and we have to specify this tab
12:52:18
dentro de allí que estamos proporcionando justo aquí
inside there which we are providing right here
12:52:21
como ahora estamos proporcionando un inicio, también estamos proporcionando una publicación y también
like we are now providing a home we are also providing a post and we are also
12:52:24
proporcionando este contacto justo aquí, así que también voy a
providing this contact right here okay so i'm going to also
12:52:27
usar mi bandera justo aquí, así que si está pendiente
use my flag right here so if it is pending so
12:52:30
usaré como si estuviera pendiente en esa situación, solo queremos
i'll use like if it is pending in that situation we only
12:52:34
mostrar algún tipo de cargador, así que usaré como párrafo y estoy
want to show some sort of a loader so i'll use like paragraph and i'm
12:52:37
diciendo como cargando punto punto punto y digamos nuestro archivo y
going to say like loading dot dot dot and let's just say our file and
12:52:40
esa es la refactorización que tenemos que hacer, así que ahora estoy dentro de la pestaña de inicio, si hago clic en esta publicación, nos dará esa carga y esa
that's the refactor that we have to do so now i'm inside the home tab if i click on this post so it's going to give us that loading and that
12:52:47
la carga proviene de esta bandera de pendiente, está bien
loading is coming from this is pending flag okay
12:52:51
así que nos dará eso, quiero decir, como esa carga y luego se renderizará
so it's going to give us that i mean like that loading and then it's going to render
12:52:54
todo nuestro contenido justo aquí, déjame refrescar eso, estoy
all of our content right here let me just refresh that i
12:52:57
ahora dentro del componente de inicio, si hago clic en la publicación, entonces
am now inside the home component if i click on the post then
12:53:00
también puedo hacer clic en el contacto y nos llevará al contacto
i can also click on the contact and it's going to bring us to the contact
12:53:03
así que sí, eso fue solo lo básico de lo que
so yeah that was just the basics of what
12:53:06
llamamos a la función o gancho de uso de transición, para ser precisos en el proyecto de pestañas de avance en el tiempo de react 19, así que voy a
do we call it the use transition function or hook to be precise in react 19 time forward tabs project setup so i'm going to
12:53:12
usar npm create read at latest y
use npm create read at latest and
12:53:16
el nombre será pestañas, voy a elegir
the name will be tabs i'm going to choose
12:53:19
react.js y typescript y ahora déjame entrar en el
react.js and typescript and now let me go into the
12:53:22
proyecto de pestañas e instalar cada cosa para
tabs project and install every single thing for
12:53:25
ellos, luego está hecho, también voy a instalar los íconos de react
them then it's done i'm going to also install the react icons
12:53:28
biblioteca, ni siquiera sé si vas a usar íconos de react o no, así que supongo que eso estará aquí, así que voy a abrir eso en mi vs code justo aquí, así que cierra eso, ahora déjame hacer una limpieza, así que voy a eliminar esta carpeta pública
library i don't even know if you are going to be using react icons or not so i guess that's going to be here so i'm going to open that in my vs code right here so close that now let me make a cleanup so i'm going to remove this public folder
12:53:40
y también eliminaré este assets app.css y también
and i will also remove this assets app.css and also
12:53:43
eliminaremos cada cosa del app.tsx y
we will remove every single thing from the app.tsx and
12:53:46
lo reemplazaremos con nuestro propio componente personalizado, voy a
replace it with our own custom component i'm going to
12:53:49
también eliminaré cada cosa de allí y el resto de ellos es
also remove every single thing from there and the rest of them is
12:53:52
bien, así que ahora déjame hacer clic en esto para comenzar y ir a
fine so now let me just click on this getting started and go to
12:53:55
los marcos y guías, elige leer y copiar
the frameworks and guides choose read and copy
12:53:59
este comando y ahora déjame abrir mi terminal y colocar allí correctamente
this command and now let me open my terminal and place there right
12:54:02
aquí, así que va a instalar tabla y css en mi máquina, así que voy a
here so it's going to install table and css in my machine so i'm going
12:54:05
regresar, ahora déjame presionar enter, lo que está haciendo allí es
to go back now let me hit enter what it's doing there I'm
12:54:09
voy a copiar allí y vamos a mi
going to copy there and let's just go into my
12:54:12
archivo tailwind config.js y reemplazarlo con esto
tailwind config.js file and replace it with this
12:54:15
contenido así que también voy a continuar y
content like so I'm going to also go ahead and
12:54:18
copiar allí e ir a mi index.css y colocar
copy there and go to my index.css and place
12:54:21
mi estilo allí y déjame probar esto, así que voy a copiar esta línea, ir a mi app y reemplazarla con este nuevo h1 aquí mismo
my styling there and let me just test this out so I'm going to copy this line out go to my app and replace it with this new h1 right here
12:54:30
guardar mi archivo y ahora déjame usar mi npm run dev así que
save my file and now let me use my npm run dev so
12:54:33
va a iniciar mi servidor y solo refresquemos allí, ahora
it's going to start my server and let's just refresh there we
12:54:37
estamos obteniendo nuestro hola mundo con el estilo, lo que significa que todo
are now getting our hello world with the styling which means like everything
12:54:40
está funcionando como esperamos, lo primero que quiero hacer
is working the way we expect them to work the first thing that i want to do
12:54:43
es que quiero eliminar este h1 de aquí y nosotros
is that i want to remove this h1 from here and we
12:54:46
vamos a renderizar nuestra barra lateral y también nuestro perfil, pero primero déjame crear un dev y dentro de este dev vamos a renderizar ambos componentes, así que solo crearé un componente con el nombre de o ya sabes, una carpeta con el nombre de componentes.
are going to be rendering our sidebar and also our profile but first of all let me just create a dev and inside this dev we're going to be rendering both of their components so i'll just create a component with the name of or you know what a folder with a name of components.
12:54:59
Y dentro de allí, vamos a definir nuestro sidebar.tsx y también nuestro profile.tsx.
And inside there, we're going to be defining our sidebar.tsx and also our profile.tsx.
12:55:04
Voy a entrar en la barra lateral, usar mi RAFC dentro de allí.
I'm going to go into the sidebar, use my RAFC inside there.
12:55:08
Ve a mi perfil y usa mi RAFC dentro de allí también. Y ahora déjame renderizar ambos componentes.
Go to my profile and use my RAFC inside there as well. And now let me render both of these components.
12:55:14
Así que voy a usar la barra lateral y renderizarlos.
So I'm going to use like sidebar and render them.
12:55:18
Voy a usar también el perfil y también renderizar este componente. Y así es como se ven ambos.
I'm going to also use the profile and also render this component. And this is how both of them looks like.
12:55:24
así que voy a comenzar a trabajar en la barra lateral, así que voy a entrar en el
so I'm going to start working on the sidebar so I'm going to go into the
12:55:27
componente de la barra lateral y no vamos a hacer nada loco dentro
sidebar component and we're not going to be doing anything crazy inside
12:55:30
de la barra lateral, pero vamos a proporcionar mucho estilo, así que
the sidebar but we're going to be providing a lot of styling so
12:55:33
lo que voy a hacer es que voy a eliminar este dev y lo voy a reemplazar
what I'm going to do is that I'm going to remove this dev and I'm going to replace
12:55:37
por el aside aside ahí estamos
it with the aside aside there we
12:55:40
bien y también voy a poner el nombre de la clase de sidebar fijo y la parte superior se establecerá en cero la izquierda se establecerá en cero déjame volver un par de veces y
go okay and I'm going to also put the class name of sidebar fixed and top will be set to zero left will be set to zero let me go back for a few times and
12:55:52
y la altura se establecerá en pantalla lo que significa que será completamente ancho se establecerá
and height will be set to screen which means like totally full width will be set
12:55:55
en 20 también voy a proporcionar un color de fondo de 1a
to 20 i'm going to also provide a background color of 1a
12:55:59
1c y 1e eso va a ser el fondo
1c and 1e that's going to be the background
12:56:02
color también voy a cambiar el texto a completamente blanco y
color i'm going to also change the text to totally white and
12:56:05
dentro de este sidebar déjame acercar un poco vamos a crear
inside this sidebar let me just zoom in a bit we're going to be creating
12:56:08
lo que ul que tendrá las clases de emparejamiento por todas partes
what ul which will have the classes of pairing for all around
12:56:11
se establecerá en cuatro flex y flex se establecerá en columna y escribamos lo que justifique así justifique se establecerá en entre y los elementos se establecerán en el centro.
will be set to four flex and flex will be set to column and let's just write what justify like so justify will be set to between and items will be set to center.
12:56:22
Para la altura vamos a establecerla completamente llena. Déjame guardar mi archivo.
For the height we are going to be setting their totally full. Let me just save my file.
12:56:26
Voy a crear un div con una clase de superior y dentro de ahí vamos a crear nuestro aliado con una clase de margen para la parte inferior que ahora se establecerá en dos y crear un div con una clase de flex y también los elementos se establecerán en el centro.
I'm going to create a div with a class of top and inside there we are going to be creating our ally with a class of margin for the bottom will be now set to two and create a div with a class of flex and also items will be set to center.
12:56:37
Dentro de ese div vamos a crear nuestro fa home y ahí estará nuestro ícono y también voy a estilizar este ícono.
Inside there div we are going to be just creating our fa home and there's going to be our icon and I'm going to also style this icon.
12:56:44
Así que solo escribiré como el nombre de la clase de margen para la derecha se establecerá en dos el margen para la parte inferior se establecerá en 3 y el tamaño lo voy a aumentar a 18.
So I'll just write like class name of margin for the right will be set to two margin for the bottom will be set to 3 and the size i'm going to increase that to 18.
12:56:52
Guarda mi archivo y así es como se ve todo aquí solo tenemos nuestro ícono de inicio y que se ve genial.
Save my file and this is how everything looks like right here we only have our home icon and which is looking cool.
12:56:59
Ahora debajo de este li sabes qué déjame duplicar este li un par de veces
Now underneath this li you know what let me just duplicate this li for like a few times
12:57:04
vamos a duplicar eso una vez y voy a cambiar eso a fa user fa user y agarrar eso de los íconos de react déjame guardar eso y sí estamos obteniendo el usuario que se ve genial
let's just duplicate that one time and i'm going to change that to fa user fa user and grab that from the react icons let me just save that and yeah we are getting the user which is looking cool
12:57:16
y también voy a duplicar eso por última vez así que
and I'm going to also duplicate there for the final time so
12:57:19
vamos a duplicar eso y cambiar este ícono a fa
let's just duplicate there and change this icon to fa
12:57:23
buscar así y sí
search like so and yeah
12:57:26
ahora estamos obteniendo nuestra búsqueda que se ve genial y ahora debajo
we are now getting our search which is looking cool and now underneath
12:57:29
de este div vamos a definir nuestro div inferior como
this div we are going to be defining our bottom div like
12:57:32
eso fue para la interfaz superior déjame colapsar
that was for the top ui let me just collapse
12:57:35
ahí eso fue para la interfaz superior que puedes ver aquí ahora vamos a empujar nuestros íconos hacia abajo así que para eso vamos a crear nuestro div inferior derecho
there that was for the top ui which you can see right here now we are going to be pushing our icons to the bottom so for that we are going to be creating our bottom div right
12:57:44
aquí así que déjame darle una clase de fondo y básicamente puedes darle cualquier clase que prefieras voy a escribir un li dentro del li vamos a usar lo que i o md settings
here so let me just give it a class of bottom and you can basically give it in any class that you prefer i'm going to write a li inside the li we are going to be using what i o md settings
12:57:54
ajustes y también voy a proporcionar
s w t i n g s and i'm going to also provide
12:57:57
el tamaño de 18 a eso y ahora debajo de ellos vamos
the size of 18 to that and now underneath them we're going
12:58:00
a estar también renderizando lo que fa usuario incorrecto
to be also rendering what fa user wrong
12:58:03
o iconos de react y el nombre de clase del producto de margen para la parte superior se establecerá en cinco y el tamaño se establecerá en 18 semi archivo y ahora también estamos obteniendo estos iconos aquí.
or react icons and product class name of margin for the top will be set to five and the size will be set to 18 semi file and now we are also getting these icons right here.
12:58:13
Básicamente puedes cambiar cualquier cosa que desees, pero en mi caso se ve mejor.
Basically you can change anything that you like but in my case that's looking better.
12:58:18
Así que eso fue todo sobre la barra lateral. A continuación, vamos a trabajar con el componente de perfil.
So that was it about for the sidebar. Next we're going to be working with the profile component.
12:58:24
Ahora déjame acercar un poco y lo primero que quiero hacer es crear un hilo para la URL del banner y también para la URL del perfil.
Now let me just zoom in a bit and the first thing that I want to do is that I want to create a thread for the banner URL and also for the profile URL.
12:58:31
Así que solo crearé una URL de banner en
So I'll just create a banner URL in
12:58:34
minúsculas y luego estableceré la URL del banner y eso va a ser igual al hilo utilizado y para el inicial
lowercase and then set banner URL and that's going to be equal to the used thread and for the initial
12:58:40
valor voy a especificar esta cadena, así que la cual va a
value I'm going to specify this string okay so which is going to
12:58:43
ser básicamente solo un prototipo o una
be basically just a prototype or a
12:58:46
imagen simple, sabes, déjame mostrarte que si voy a una nueva pantalla
simple image you know let me just show you that if I go to a new screen
12:58:49
y vamos a obtener como 1500 x 400, así que esta va a ser básicamente nuestra imagen de banner y solo para prototipo y podremos cambiar eso en unos segundos, así que eso va a ser para el banner
and we're going to be getting like 1500 x 400 so this is going to be basically our banner image and just for prototype and we will be able to change that in a few seconds okay so that's going to be for the banner
12:59:01
vamos a estar también creando una URL de perfil, así que solo crearé como URL de perfil y también establecer
we're going to be also creating a profile url so I'll just create like profile url and also set
12:59:07
la URL de perfil y eso va a ser igual a
profile url and that's going to be equals to
12:59:10
el hilo utilizado y este hilo utilizado tendrá
the used ted and this used ted will
12:59:14
este enlace aquí, es solo una imagen de marcador de posición con
have this link right here it is just a placeholder image with
12:59:17
100, así que ahora déjame también mostrarte eso, así que esto
100 so now let me also show you that one so this
12:59:20
es cómo maldita sea, voy a
is how god damn it uh i'm gonna
12:59:23
tener que copiar solo el enlace de la imagen y
have to copy only the image link and
12:59:26
déjame colocar eso aquí y sí, esto es lo que vamos a obtener para el perfil, ahora déjame ir a la interfaz de usuario, así que solo eliminaré este perfil y proporcionaré mi nombre de clase allí.
let me just place that here and yeah this is what we are going to be getting for the profile now let me go into the ui so i'll just remove this profile and provide my class name to there.
12:59:36
Así que va a ser relativo y el ancho se establecerá en
So it's going to be relative and width will be set to
12:59:40
94% igual que allí. Y el margen para la izquierda se establecerá en 5rems.
94% just like there. And the margin for the left will be set to 5rems.
12:59:47
Dentro de este div vamos a crear un div con la clase de relativo. Y dentro de este div vamos a definir nuestra imagen.
Inside this div we're going to be creating a div with the class of relative. And inside this div we're going to be defining our image.
12:59:53
Y voy a eliminar eso. Ahora vamos a proporcionar nuestra imagen de banner. Así que voy a copiar eso y colocarlo
And I'm going to remove that. Now we're going to be providing our banner image. So I'm going to copy that and place it
13:00:00
ahí justo aquí y para el texto alternativo simplemente
there right here and for the alternative text I'll just
13:00:03
lo pondré como algún tipo de, ya sabes, imagen de fondo
put it like some sort of a you know what background image
13:00:06
o algo así estaría bien y para las clases pondré
or something like that would be fine and for the classes I'll put
13:00:09
que el ancho estará configurado para ser totalmente completo y la altura será de 6 a 60
it like width will be set to totally full and height will be 6 to 60
13:00:13
y también el objeto estará configurado para cubrir, así que
and also the object will be set to cover so it's
13:00:16
va a tomar todo el día libre, así que ahora déjame mostrarte ahí y aquí
going to take the entire day off so now let me show you there and here
13:00:19
puedes ver que ahora estamos obteniendo nuestro banner que se ve genial, ahora déjame también encargarme del perfil, pero ahora debajo de eso vamos a tener que crear nuestro botón, así que este botón incluirá muchas clases, así que ahora déjame proporcionar todas ellas.
you can see we are now getting our banner which is looking cool now let me also take care of the profile but now underneath that we're going to have to create our button so this button will include a lot of classes so now Let me just provide all of them.
13:00:30
Lo primero que quiero hacer es que quiero que esto sea absoluto. Esto ahora es relativo.
The first thing that I want to do is that I want to make it so that this is going to be absolute. This is now relative.
13:00:38
Así que este botón será absoluto para este relativo. La parte superior se establecerá en 2 y el lado derecho se establecerá en 2.
So this button will be absolute for this relative. Top will be set to 2 and the right side will be set to 2.
13:00:45
El fondo será gris de 800. ¿Sabes qué? 800.
Background will be gray of 800. You know what? 800.
13:00:50
Y el texto se establecerá en totalmente blanco. El espaciado por todos lados se establecerá en 2. Redondeado totalmente completo.
And text will be set to totally white. Pairing for all around will be set to 2. Rounded totally full.
13:00:56
Y cada vez que alguien pase el mouse por ahí, queremos cambiar el color de fondo a gris de 600 así.
And whenever somebody hover over there, we want to change the background color to gray of 600 like so.
13:01:03
Y dentro de ahí, déjame simplemente guardar mi archivo. Dentro de este botón, vamos a crear nuestra etiqueta. Y sabes qué?
And inside there, let me just save my file. Inside this button, we're going to be creating our label. And you know what?
13:01:10
No vamos a proporcionar ningún HTML4 hoy. Oh sí, proporcionaremos HTML4.
We're not going to be providing any HTML4 today. Oh yeah, we will provide HTML4.
13:01:15
Así que simplemente escribiré como carga de banner o algo así. Cargar.
So I'll just write like banner upload or something like that. Upload.
13:01:19
Y también vamos a proporcionar un nombre de clase de cursor a puntero.
And we're going to be also providing a class name of cursor to pointer.
13:01:24
etiqueta vamos a crear un ícono de cámara FA
label we are going to be creating an FA camera icon
13:01:27
simplemente obtengamos eso de los íconos de react y voy a aumentar el tamaño de eso a 24.
let's just get that from the react icons and I'm going to increase the size of that to 24.
13:01:32
Ahora déjame simplemente guardar eso y sí, así es como vamos a obtener nuestro ícono.
Now let me just save that and yeah this is how we are going to be getting our icon.
13:01:36
Ahora debajo de esta etiqueta vamos a definir nuestro campo de entrada, así que simplemente escribiré un tipo de entrada que se establecerá en archivo en este caso porque vamos a cargar algún tipo de imagen.
Now underneath this label we are going to be defining our input field so I'll just write an input type will be set to file in this case because we are going to be uploading some sort of an image.
13:01:44
Así que también voy a proporcionar el ID de carga de banner a este porque ya hemos especificado esta carga de banner para el HTML4.
So I'm going to also provide the ID of banner upload to this one because we've already specified this banner upload for the HTML4.
13:01:52
Está bien. Y también voy a proporcionar la bandera de aceptación. Así que va a aceptar cada imagen.
Okay. And I'm going to also provide the accept flag. So it's going to accept every single image.
13:01:57
Y también vamos a proporcionar un nombre de clase de oculto hoy. Así que se va a ocultar ahí.
And also we are going to be providing a class name of hidden today. So it's going to hide there.
13:02:01
Y cuando alguien intente cambiar algo, vamos a activar esta función, que es un cambio de banner manejador. Se sabe que guarda eso.
And when somebody tries to change something, we are going to be firing this function, which is a handle banner change. It's known to save that.
13:02:08
Obviamente nos dará un error porque tenemos que crear esta función. Está bien. Así que, ya sabes, déjame simplemente crear esta función de inmediato.
It's going to obviously give us an error because we have to create this function. Okay. So, you know, let me just create this function right away.
13:02:15
Así que voy a ir a la parte superior y aquí voy a definir mi imagen de banner.
So I'm going to go to the top and here I'm going to define my banner image.
13:02:18
Así que usaré algo como const banner o handle, disculpa, handle banner image o handle banner change.
So I'll use like const banner or handle, excuse me, handle banner image or handle banner change.
13:02:24
Va a tomar el evento. Primero vamos a crear nuestro archivo. Así que solo usaré un archivo y va a venir de event.target.files.
It's going to take the event. We're going to be first of all creating our file. So I'll just use a file and it's going to be coming from the event.target.files.
13:02:32
Y solo queremos obtener el primer elemento de ahí. Está bien.
And we only want to get the first element out of there. Okay.
13:02:37
Voy a definir eso explícitamente como cualquier cosa porque esto es solo un archivo. Así que realmente no importa el tipo. Y no vamos a hacer nada loco.
I'm going to explicitly define that as any because this is just a file. So it doesn't really matter the type. And we're not going to be doing anything crazy.
13:02:44
Y ahora déjame comprobar. Si tenemos el archivo, en esta situación, vamos a ejecutar este set banner URL y queremos cambiar eso a URL.createObjectURL.
And now let me just check. If we got the file, if we have the file, so in this situation, we're going to be running this set banner URL and we want to change that to the URL.createObjectURL.
13:02:57
Y aquí vamos a especificar nuestro archivo. Así que ahora, ¿qué demonios es esta URL y luego .createObjectURL?
And here we're going to be specifying our file. So now what in the world is this URL and then .createObjectURL.
13:03:03
Esta línea de código se utiliza para crear una URL temporal que apunta al objeto blob o archivo en JavaScript.
This line of code is used to create a temporary URL that point to the blob or file object in JavaScript.
13:03:10
Así que sí, esto es lo que vamos a hacer ahora. Y ya hemos terminado con esto. Así que ahora déjame probar esto.
So yeah, this is what we're going to be doing right now. And we're totally done with this one. So now let me just test this out.
13:03:16
Primero, voy a ir a mi canal de YouTube y luego voy a descargar mi propio banner y lo voy a guardar en mi escritorio.
First of all, I'm going to go to my YouTube channel and then I'm going to download my own banner and I'm going to save that to my desktop.
13:03:22
Y ahora voy a hacer clic en este ícono y aquí voy a elegir mi banner justo aquí.
And now I'm going to click on this icon and here I'm going to just choose my banner right here.
13:03:27
Así que cada vez que haga clic en eso, va a agregar mi banner de mi canal de YouTube y lo va a agregar justo aquí.
So whenever I click on that, it's going to add my banner from my YouTube channel and it's going to add that right here.
13:03:33
Así que eso se ve genial, pero también tenemos que cuidar nuestra imagen de perfil.
So which is looking cool, but we also have to take care of our profile image as well.
13:03:38
Así que ahora debajo de eso, también vamos a crear un logo o una imagen de perfil, lo que quieras llamar eso.
So now underneath that, we are going to be also creating a logo or a profile image, whatever you want to call that.
13:03:44
Así que ahora debajo de este div aquí vamos a definir nuestro logo del canal.
So now underneath this div here we're going to be defining our come on channel logo.
13:03:51
Ahí vamos. Y aquí vamos a cuidar nuestro logo del canal. Voy a crear un div con una clase de legs y items se establecerán en el centro.
There we go. And here let's just take care of our channel logo. I'm going to create a div with a class of legs and items will be set to center.
13:03:58
El margen izquierdo se establecerá en cuatro y el margen superior se establecerá en un valor arbitrario como dos rems.
Margin for the left will be set to four and margin for the top will be set to arbitrary value like two rems.
13:04:05
Y ahora dentro de este div vamos a definir nuestra imagen. Y para el texto de la imagen vamos a proporcionar nuestra URL de perfil que ya hemos configurado arriba.
And now inside this div we're going to be defining our image. And for the image text we're going to be providing our profile URL which we've already set up up above.
13:04:13
y ahora para este texto alternativo voy a escribir algo como logo del canal
and now for this alternative text I'm going to write like channel logo
13:04:17
o algo así y para el nombre de la clase voy a
or something like that and for the class name I'm going
13:04:20
proporcionar un ancho de 40 y la altura también se establecerá en
to provide a width of 40 and the height will be also set to
13:04:23
40 y el objeto se establecerá para cubrir totalmente, está bien y
40 and object will be set to totally cover okay and
13:04:26
también voy a hacerlo totalmente redondeado para que tengamos nuestro perfecto
I'm going to also make it totally rounded full so that we get our perfect
13:04:29
círculo también voy a cambiar eso a borde totalmente ancho y relativo r-e-l-a-t-i-v-e ahí vamos así que ahora voy a guardar mi archivo y sí, estamos obteniendo
circle I'm going to also change that to border totally wide and relative r-e-l-a-t-i-v-e there we go so now I'm going to save my file and yeah we are getting
13:04:38
perfil, una especie de logo, pero también necesitamos un ícono de cámara allí. Así que ahora déjame poner un ícono de cámara allí.
profile, kind of a logo, but we also need a camera icon there. So now let me just put a camera icon there.
13:04:45
Así que primero voy a crear mi botón con
So I'm going to first of all create my button with
13:04:49
la clase de absoluto y dentro de ahí
the class of absolute and inside there
13:04:52
también voy a poner el margen para la izquierda de 3.6 RAM y el margen para la parte superior se establecerá en 10 RAM y el fondo se establecerá en un gris total de 800
I'm going to also put the margin for the left of 3.6 RAM and margin for the top will be set to 10 RAM and background will be set to totally gray of 800
13:05:03
y el texto se establecerá en blanco total, el relleno por todos lados se establecerá en 2, el redondeado se establecerá en 4
and text will be set to totally white, padding for all around will be set to 2, rounded will be set to 4
13:05:10
y cada vez que alguien pase el cursor por ahí, vamos a cambiar el color de fondo a un gris de 600
and whenever somebody hover over there we are going to be changing the background color to gray of 600
13:05:15
y dentro de este botón vamos a renderizar nuestro ícono de cámara fa
and inside this button we are going to be rendering our fa camera icon
13:05:20
y también voy a proporcionar un nombre de clase o, ya sabes, no un nombre de clase, sino el tamaño de 24.
and I'm going to also provide a class name or you know not class name but the size of 24.
13:05:25
Así que si guardo mi archivo y reviso esto, está bien
So if I save my file and check this out so okay
13:05:30
estamos obteniendo algo que no es lo que queremos, así que voy a
we are getting something this is not what we want so I'm going to
13:05:33
cortar ahí y crear mi etiqueta primero que nada y
cut there and create my label first of all and
13:05:36
para la etiqueta voy a proporcionar algo como carga de perfil y
for the label I'm going to provide like profile upload and
13:05:39
también vamos a proporcionar un nombre de clase de cursor y que
we're going to be also providing a class name of cursor and which will
13:05:42
se establecerá en puntero y dentro de esta etiqueta vamos a proporcionar nuestra cámara y solo especifiqué estas dos
be set to pointer and inside this label we're going to be providing our camera and I just specify these two
13:05:49
clases y eliminé las otras, así que aquí puedes ver que
classes and i removed the other ones so here you can see we
13:05:52
estamos proporcionando un margen para la izquierda, pero ahora los estamos reescribiendo
are providing a margin for the left but we are now rewriting them
13:05:56
usando el menos y solo especifiqué seis rem y nosotros
by using the minus and i just specify six rem and we
13:05:59
también estamos proporcionando un índice z para que podamos ver nuestro
are also providing a z index so that we can see our
13:06:02
ícono, así que si elimino esto, no podemos ver allí si
icon so if i remove this we are not able to see there if
13:06:05
proporciono mi índice z, así que ahora podemos ver nuestro ícono
i do provide my z index so we are now able to see our icon
13:06:08
ahí también voy a proporcionar el margen para la parte superior de dos rems para que podamos ver allí o, ya sabes, seis rem estaría bien, maldita sea
there i'm going to also provide the margin for the top of two rems so that we can see there or you know what six rem would be fine god damn it
13:06:16
ocho o nueve rems, nueve rem se ve genial
eight or nine rems nine rem is looking cool
13:06:19
sí, nueve rem se ve genial, ahora debajo de esta etiqueta, ¿qué
yeah nine rem is looking cool now underneath this label what
13:06:23
quieres hacer? Solo queremos crear nuestro campo de entrada, así que usaré algo como
do you want to do we just want to create our input field so i'll use like
13:06:26
entrada y el tipo se establecerá en archivo aquí, también
input and the type will be set to file here we
13:06:29
tenemos que especificar el id que se establecerá en carga de perfil
also have to specify the id which will be set to profile upload
13:06:32
está bien, así que también vamos a proporcionar
okay like so we're going to be also providing
13:06:35
la bandera de excepción que se establecerá en imagen y cada imagen será establecida como oculta, así que solo queremos contratar el día y cuando alguien
the except flag which will be set to image and every single image okay and classroom will be set to hidden so we just want to hire day and when somebody
13:06:44
intente cambiar eso, vamos a activar esta función que manejará
to try to change that we're going to be firing this function which will handle
13:06:48
que manejará el cambio de perfil
which will be handle profile change
13:06:51
voy a copiar el nombre de eso, iré a la parte superior y crearé esto
i'm going to copy the name of that go to the top and create this
13:06:54
función debajo de eso, solo usaré como const manejar cambio de perfil, va a tomar el evento y eso se establecerá en cualquier y aquí voy a escribir como archivo no archivos, sino solo un archivo
function underneath that i'll just use like const handle profile change it's going to take the event and that's going to be set to any and here i'm going to write like file not files but just a file
13:07:06
que vendrá del evento punto objetivo punto archivo o malditos archivos y el primer archivo
which will be coming from the event dot target dot file or goddammit files and the first file
13:07:13
Ahora debajo de eso solo tenemos que verificar si tenemos el archivo. Así que en esta situación vamos a usar como establecer URL de perfil.
Now underneath that we just have to check if we have the file. So in this situation we are going to be using like set profile URL.
13:07:19
Y vamos a proporcionar una API de URL. Y luego dentro de eso tenemos nuestra crear objeto URL.
And we are going to be providing a URL API. And then inside there we have our create object URL.
13:07:25
Y luego solo pega nuestro archivo dentro de eso. Así que aquí puedes ver si hago clic allí. Pero antes de hacerlo, tengo que guardar mi imagen de perfil.
And then just paste our file inside there. So here you can see if I click on there. But before I do I'm going to have to save my profile image.
13:07:32
Y también guardar allí. Ahora déjame hacer clic en este ícono. Puedo elegir mi imagen. ¿Y quién es este tipo increíble? Genial.
And also save there. Now let me click on this icon. I can choose my image. And who is this amazing guy? Awesome.
13:07:40
Así que sí, puedo cambiar el color de fondo. Quiero decir, como la imagen de fondo y también puedo cambiar la imagen de perfil.
So yeah I can change the background color. I mean like background image and I can also change the profile image.
13:07:46
Ahora debajo de este botón vamos a proporcionar detalles del canal. Detalles. Ahí vamos.
Now underneath this button we're going to be providing over channel details. Details. There we go.
13:07:53
Y ahora debajo de eso, solo vamos a crear o div la clase de margen para la izquierda que se establecerá en 4. El margen para la parte superior también se establecerá en 4.
And now underneath there let's just create or div the class of margin for the left will be set to 4. Margin for the top will be also set to 4.
13:08:00
Está bien, así que H1 con la clase de texto a Excel y la fuente se establecerá en negrita. Que tomará mi propio nombre.
Okay so H1 with the class of text to Excel and font will be set to bold. Which will take my own name.
13:08:06
Puedes especificar tu propio nombre si lo deseas. Así que escribiré como Hussain Web Dev Baby. Ver si guardo allí. Ahora estamos llegando allí.
You can specify your own name if you wanted to. So I'll write like Hussain Web Dev Baby. See if I save there. We're now getting there.
13:08:13
pero eso no se ve tan genial. Solo proporciona un margen para la izquierda de 4m estaría bien.
but that's not looking that cool. Just provide a margin for the left of 4m would be fine.
13:08:20
Y ahora debajo de eso, vamos a crear nuestro párrafo con un nivel de 1 millón de vistas. ¿Acaso obtuve 1 millón de vistas?
And now underneath there, we're going to be creating our paragraph with a level of 1 million views. Did I even get a 1 million views?
13:08:27
No estoy muy seguro de eso, pero crea un párrafo con una clase de margen para la parte superior de 2, y que tendrá un poco de descripción.
Not quite sure about that, but create a paragraph with a class of margin for the top of 2, and which will have a bit of description.
13:08:34
Voy a colocar esta descripción justo aquí. Como esta es una breve descripción para el canal de YouTube.
I'm going to just place this description right here. Like this is a short description for the YouTube channel.
13:08:37
Da una visión general del contenido y lo que el espectador puede esperar,
It gives the overview of the content and what viewer can expect,
13:08:41
o sí, esperar, así que también
or yeah expect so i'll
13:08:44
proporcionaré el margen para la izquierda de cuatro
also provide the margin for the left of four
13:08:48
a este para rem copiar allí y
to this one for rem copy there and
13:08:51
crear un nombre de clase para el párrafo y colocar eso allí todavía
create a class name for the paragraph and place that there still
13:08:55
increíble, finalmente voy a crear un botón de suscripción
amazing finally i'm going to create a subscribe button
13:08:58
y ustedes deberían suscribirse a mi canal de youtube, así que margen
and you guys should subscribe to my youtube channel so margin
13:09:02
para la parte superior se establecerá en cuatro y el color de fondo se establecerá en rojo de 600 y también proporcionaré un texto de totalmente blanco, el relleno para el eje y será 2.
for the top will be set to four and background color will be set to red of 600 and i'm going to also provide a text of totally white padding for the y axis will be 2.
13:09:11
El emparejamiento para el xx será 4 y totalmente redondeado.
Pairing for the xx will be 4 and totally rounded.
13:09:15
Y cada vez que alguien pase el mouse por ahí, vamos a hacer eso arbitrariamente.
And whenever somebody hover over there, we are going to be doing that arbitrarily.
13:09:20
Así que solo escribiré como fondo totalmente rojo y 500 dentro de ahí. Y dentro de este botón, solo diré como suscribirse.
So I'll just write like background totally red and 500 inside there. And inside this button, I'll just say like subscribe.
13:09:27
Suscríbete, bebé. Semi archivo. Ahora estamos obteniendo nuestro botón de suscripción, pero también tenemos que especificar el margen para la izquierda
Subscribe baby. Semi file. Now we are getting our subscribe button, but we also have to specify the margin for the left
13:09:36
todo para rev así y sí
all for rev like so and yeah
13:09:39
esto se ve mejor ahora que tenemos que crear nuestro componente de pestañas
this is looking better now that we have to create our tabs component
13:09:42
así que voy a crear un componente con el nombre de tab.tsx
so I'm going to create a component with the name of tab.tsx
13:09:45
o pestañas más bien y voy a estar usando mi rafce
or tabs rather and I'm going to be using my rafce
13:09:49
dentro de ahí, ahora déjame guardar este archivo y aquí tenemos que llamar a nuestro componente de pestañas justo aquí, así que voy a guardar mi archivo ahora, mira esto, así que aquí puedes ver que tenemos nuestro componente de pestañas, que se ve genial.
inside there now let me just save this file and here we have to call our tabs component right here okay so I'm going to save my file right now check this out so here you can see we have our tabs component, which is looking cool.
13:10:00
Así que lo que voy a hacer es que primero, déjame acercar un poco. Voy a colocar los datos de las pestañas justo aquí.
So what I'm going to do is that first of all, let me just zoom in a bit. I'm going to place the tabs data right here.
13:10:06
Así que aquí puedes ver que tenemos nuestro arreglo de pestañas. Y dentro de este arreglo de pestañas, tenemos algunos objetos.
So here you can see we have our tabs array. And inside this tab array, we have a few objects.
13:10:11
Así que cada objeto tendrá el ID, ícono, etiqueta y contenido. Así es como se verá nuestro contenido.
So each object will have the ID, icon, label and content. So this is how our content will look like.
13:10:17
Primero que nada, vamos a crear un arreglo con seis elementos y luego vamos a iterar sobre cada uno de esos elementos.
First of all, we are going to be creating array with six items and then we're going to be iterating over through each of that item.
13:10:23
Luego estamos creando un componente de tarjeta y ese componente de tarjeta aceptará la clave prop, título, descripción y también la imagen.
Then we are creating a card component and that card component will accept the key prop, title, description and also the image.
13:10:30
Está bien, así que sí, aquí puedes ver que tenemos ahí como unas pocas veces y vamos a estar iterando sobre eso.
Okay, so yeah, here you can see we have there like a few times and we are going to be iterating over through there.
13:10:36
Así que lo que voy a hacer es que voy a importar todos esos íconos. Como primero, vamos a importar el FA home y también vamos a crear esta tarjeta o, sabes qué, déjame crear esta tarjeta de inmediato.
So what I'm going to do is that I'm going to just import all of that icons. Like first of all, we're going to be importing the FA home and we're going to be also creating this card or you know what, let me just create this card right away.
13:10:45
Así que voy a crear un componente con el nombre de card.tsx y vamos a usar nuestro RAFC dentro de ahí.
So I'm going to just create a component with the name of card.tsx and let's just use our RAFC inside there.
13:10:52
y también voy a importar eso justo aquí, voy
and i'm going to also import that right in here i'm
13:10:55
a eliminar esta d y reescribir eso y presionar enter, así que se va a importar
going to remove this d and rewrite that and hit enter so it's going to import
13:10:58
eso justo aquí, así que vamos a importar
that right here okay so let's just import
13:11:02
este ícono y también vamos a crear el about
this icon and we are going to be also creating the about
13:11:05
componente, así que también voy a hacer eso ahora mismo, así que vamos a crear about.tsx y usar el rdfc dentro de ahí, guarda este archivo y ve a este componente de pestañas
component so i'm going to also do that right now okay so let's just create what about.tsx and use the rdfc inside there save this file and go to this tabs component
13:11:16
y importa mi acerca justo aquí, está bien y
and import my about right here okay and
13:11:20
también vamos a importar este icono, simplemente
we're going to be also importing this this icon let's just
13:11:23
importa este icono, también voy a importar este
import this icon i'm going to also import this
13:11:27
icono de teléfono y supongo que ese va a ser el último, también tenemos que
phone icon and i guess that's going to be the last one we also have to
13:11:30
crear este componente de contacto, así que voy a crear un componente con el nombre de contact.tsx
create this contact component so i'm going to create a component with the name of contact.tsx
13:11:34
y solo usaré el rfc dentro de ahí y ahora déjame importar allí justo aquí, así que si guardo mi archivo, eso va a ser como todos los datos, así que voy a colapsar allí
and i'll just use the rfc inside there and now let me import there right here so if i save my file so that's going to be like all of the data so i'm going to collapse there
13:11:43
y sí, eso está hecho. Lo siguiente que tenemos que hacer es crear nuestro estado para nuestra pestaña.
and yeah that's done. The next thing that we have to do is that we have to create our stat for our tab.
13:11:50
Así que solo escribiré como pestaña activa y luego estableceré la pestaña activa.
So I'll just write like active tab and then set active tab.
13:11:55
Va a ser igual al uso de estado y para el valor inicial vamos a proporcionar todos sus datos de pestañas y vamos a obtener la primera pestaña de allí y de esa primera pestaña vamos a obtener el id.
It's going to be equals to the use stat and for the initial value we're going to be providing all of their tabs data and we are going to be getting the first tab out of there and from that first tab we are going to be getting the id.
13:12:07
Está bien, así que eso está hecho y ahora vamos a entrar en la interfaz de usuario. Así que voy a quitar esta pestaña de aquí.
Okay so that's done and now let's get into the UI. So I'm going to remove this tab from here.
13:12:11
Voy a poner un nombre de clase y el espaciado alrededor se establecerá en 4.
I'm going to put a class name and pairing all around will be set to 4.
13:12:15
El margen para la parte superior se establecerá en 3rem y dentro de este div vamos a crear un div con una clase de flex y borde en la parte inferior y también borde gris de 200.
Margin for the top will be set to 3rem and inside this div we are going to be creating a div with a class of flex and border for the bottom and also border gray of 200.
13:12:25
Déjame volver y dentro de este div ahora vamos a iterar sobre todas sus pestañas.
Let me just go back and inside this div now we are going to be iterating over through all of their tab.
13:12:30
Está bien, así que lo que voy a hacer es que voy a escribir como pestañas y luego iterar sobre todas sus pestañas y déjame
Okay so what I'm going to do is then I'm going to write like tabs and then iterate over through all of their tab and let me just
13:12:36
escribirlo como pestaña, así que dentro de ahí vamos a estar
write it tab like so inside there we are going to be
13:12:39
creando nuestro botón y este botón tendrá mucho estilo, pero
creating our button and this button will have a lot of styling but
13:12:42
sabes qué, sí, solo voy a hacer eso ahora
you know what yeah i'm gonna just do that right
13:12:45
para la clave vamos a obtener la clave usando el
now for the key we're going to be getting the key by using the
13:12:49
id de la pestaña, también proporcionaré los nombres de clase para ellos, pero
tab.id i'll also provide the class names to them but
13:12:52
eso será dinámico, así que tendré que usar la plantilla literal para
that will be dynamic so i'm gonna have to use the template literal for
13:12:55
eso, así que usaré como flex uno, el texto se establecerá completamente centrado, el espaciado para el eje y se establecerá en dos, el espaciado para el eje x
that so i'll use like flex one text will be set to totally center pairing for the y axis will be set to two pairing for the x
13:13:01
se establecerá en 4 y la fuente se establecerá en mediana
axis will be set to 4 and font will be set to medium
13:13:05
así que el texto se establecerá en completamente pequeño y
like so text will be set to totally small and
13:13:08
tenemos que renderizar nuestra pestaña activa justo aquí
we have to render our active tab right here
13:13:11
así que si nuestra pestaña está activa y déjame escribir como triple
so if our tab is active and let me just write like triple
13:13:14
es igual a tab.id así que si ese es el
equals to tab.id so if that's the
13:13:17
caso así que en esta situación vamos a cambiar el borde a borde inferior de 2 pero si ese no es el caso vamos a establecer allí a texto
case so in this situation we're going to be changing the border to border bottom of 2 but if that's not the case we're going to be setting there to text
13:13:25
gris de 600 justo aquí déjame escribir un
gray of 600 right here let me just write a
13:13:28
600 maldita sea 600 y cuando alguien
600 god damn it 600 and when somebody
13:13:31
hace clic allí vamos a encontrar esta función así que yo
clicks on there we're going to be finding this function so i'll
13:13:34
solo usaré esta función de flecha que dirá como establecer activo
just use like this arrow function which will say like set active
13:13:37
tab y aquí tenemos que especificar el tab.id dentro de allí dentro de este botón vamos a crear un div con una clase de piernas y luego elementos déjame escribir elementos y centrar
tab and here we have to specify the tab.id inside there inside this button we're going to be creating a div with a class of legs and then items let me just write items and center
13:13:48
vamos a proporcionar también una justificación de centro el espacio se establecerá en el eje x de dos
we're going to be also providing a justify of center space will be set to the x axis of two
13:13:53
dentro de este div solo usaré como lo que llamamos un
inside this div I'll just use like what do we call a
13:13:56
tab.icon y también debajo de eso estoy
tab.icon and also underneath that I'm
13:13:59
voy a crear un span que tomará el tab.level
going to create a span which will take the tab.level
13:14:02
voy a guardar este archivo así que ahora estamos obteniendo estas pestañas
I'm going to save this file so we are now getting these tabs
13:14:05
si hago clic en el acerca de nos dará la sección acerca de si
if I click on the about it's going to give us the about section if
13:14:08
hago clic en el proyecto así que nos dará los cursos del proyecto y también el contacto así que eso se ve genial ahora debajo de este div lo que voy a hacer es que voy a crear un div con una clase de margen y para la parte superior se establecerá en 4.
I click on the project so it's going to give us the project courses and also the contact so that's looking cool now underneath this div what I'm going to do is that I'm going to create a div with a class of margin and for the top will be set to 4.
13:14:20
El emparejamiento se establecerá en 4. Y también totalmente redondeado grande. Y dentro de este, vamos a usar tabs.find.
Pairing will be set to 4. And also totally rounded large. And inside this one, we're going to be using tabs.find.
13:14:28
Y aquí tenemos que especificar el tab. Y ahora solo tenemos que usar el tab.id. Eso va a ser triple igual al tab activo.
And here we have to specify the tab. And now we just have to use the tab.id. That's going to be triple equals to the active tab.
13:14:35
Solo escribe sobre el tab activo. Y si ese es el caso, solo queremos obtener el contenido de allí. Ahora déjame guardar mi archivo.
Just write over active tab. And if that is the case, we only want to get the content out of there. Now let me just save my file.
13:14:41
Y aquí puedes ver que nos dará como tarjeta, tarjeta, tarjeta, tanto tiempo. Así que lo que voy a hacer es que voy a entrar en mi componente de tarjeta.
And here you can see it's going to give us like card, card, card, that much time. So what I'm going to do is that I'm going to go into my card component.
13:14:48
y ahora déjame ocuparme de eso. Es hora de crear el componente de tarjeta.
and now let me just take care of that. Time to create the card component.
13:14:52
Así que primero necesitamos el título, la descripción, la imagen y también el enlace de nuestras props.
So we first of all need the title, description, the image and also the link from or props.
13:14:59
Y para ellos también vamos a crear una interfaz
And for them we are going to be also creating an interface
13:15:03
así que solo crearé una interfaz con el nombre de props de tarjeta y
so i'll just create interface with the name of card props and
13:15:06
dentro de allí solo proporcionemos nuestro título y eso va a ser una cadena y
inside there let's just provide our title and that's going to be a string and
13:15:09
la descripción también será una cadena y
description will be also a string and
13:15:13
la imagen será una cadena y finalmente tenemos que proporcionar
the image will be string and finally we have to provide
13:15:16
el enlace todo es una cadena de texto está bien y
the link everything is a string okay and
13:15:19
también tenemos que anotar allí con nuestra propiedad de tarjeta
we have to also annotate there with our card prop
13:15:22
aquí en el archivo semi siguiente tenemos que usar eso así que
right here semi file next we have have to use that so
13:15:25
lo que voy a hacer es que voy a simplemente eliminar esta tarjeta volver y
what i'm going to do is that i'm going to just remove this card go back and
13:15:29
dentro de allí primero definiremos nuestra tarjeta
inside there we will first of all define our card
13:15:32
proporcionando un máximo vamos a simplemente proporcionar nuestro ancho máximo
by providing a max come on let's just provide our max width
13:15:35
de pequeño y también proporcionar el mx como margen para
of small and also provide the mx like margin for
13:15:38
el eje x se establecerá en automático y el margen por todas partes se establecerá
the x-axis will be set to auto and margin all around will be set
13:15:41
en un borde y vamos a simplemente proporcionar el color de fondo y el color de fondo se establecerá en uh 1a 1c y 1e así y también vamos a proporcionar un
to one rim and let's just provide the background color and background color will be set to uh 1a 1c and 1e like so and we're going to be also providing a
13:15:52
sombra grande redondeada se establecerá en media y
rounded large shadow will be set to medium and
13:15:55
el desbordamiento se establecerá en oculto en este
overflow will be set to hidden in this
13:15:58
caso ahora déjame usar mi imagen y para la imagen vamos
case now let me just use my image and for the image we
13:16:01
a estar renderizando nuestra imagen totalmente de manera dinámica así que solo usaré el
are going to be rendering our image totally dynamically so i'll just use the
13:16:04
imagen simplemente escribiré como título aquí y
image i'll just write like title right here and
13:16:08
también proporcionaré el nombre de clase el ancho se establecerá en totalmente completo y
i'm going to also provide the class name width will be set to totally full and
13:16:11
también la altura se establecerá en 48 así y el objeto
also height will be set to 48 like so and object
13:16:16
se establecerá en cubrir totalmente para que podamos ver todo esto ahora déjame guardar mi archivo
will be set to totally cover so that we can see all of this now let me just save my file
13:16:21
y aquí puedes ver que ahora estamos obteniendo todas sus imágenes que se ven
and here you can see we are now getting all of their images which are looking
13:16:24
genial ahora debajo de eso vamos a definir nuestro div con la clase
great now underneath there we are going to be defining our div with the class
13:16:27
de padding por todas partes se establecerá en seis y
of padding all around will be set to six and
13:16:31
ahora dentro de allí vamos a usar nuestro h2 con la clase de texto para sobresalir y la fuente se establecerá en totalmente negrita el margen para la parte inferior se establecerá en dos y aquí vamos a renderizar nuestro título
now inside there let's just use our h2 with the class of text to excel and the font will be set to totally bold margin for the bottom will be set to two and here let's just render our title
13:16:42
así que vamos a estar usando también un párrafo con la clase de texto totalmente configurado en gris
like so we are going to be also using a paragraph with the class of text totally set to gray
13:16:47
de 700 el margen para la parte inferior se establecerá en cuatro
of 700 margin for the bottom will be set to four
13:16:50
y vamos a renderizar nuestra descripción aquí así que
and let's just render our description right here so
13:16:53
solo usaré nuestra descripción y ahora debajo de eso
i'll just use our description and now underneath that
13:16:57
tenemos que crear nuestra etiqueta de anclaje que no tomará
we have to create our anchor tag which will not take
13:17:00
nada pero solo vamos a proporcionar nuestro enlace justo aquí así que
anything but we are just going to be providing our link right here so
13:17:03
solo usaré un enlace y voy a poner muchos nombres de clase
i'll just use a link and i'm going to put a lot of class names
13:17:06
aquí, así que solo usaré como bloque en línea y también el relleno para el eje x se establecerá en cuatro, el relleno para el eje y se establecerá en dos, color de fondo
here so i'll just use like inline block and also padding for the x axis will be set to four padding for the y axis will be set to two background color
13:17:14
se establecerá en totalmente blanco, el color del texto se establecerá en totalmente negro
will be set to totally white text color will be set to totally black
13:17:17
la fuente será semi negrita así y
font will be semi bold like so and
13:17:21
totalmente redondeada, grande y sombra cada vez que
totally rounded large and shadow whenever
13:17:25
alguien pase el cursor sobre allí, así que solo queremos cambiar el color de fondo
somebody hover over there so we just want to change the background color
13:17:28
a gris de 600 y también al pasar el cursor
to gray of 600 and also on the hover
13:17:31
el texto se establecerá en totalmente blanco, también voy a especificar el
text will be set to totally white i'm going to also specify the
13:17:34
transiciones y la duración se establecerá en 200 dentro de esta etiqueta de anclaje, solo seleccionaremos aprender más, si guardo mi archivo y así es como se ve, pero están
transitions and duration will be set to 200 inside this anchor tag we will just select learn more if i save my file and this is how it looks like but they are
13:17:43
viéndose horribles, se ven súper
looking awful they're looking super
13:17:46
horribles, para arreglar eso voy a entrar en mi css y
awful to fix that i'm going to go into my css and
13:17:50
proporcionar esta línea de css, así que solo queremos cambiar el color de fondo
provide this line of css so we only want to change the background color
13:17:53
a este y proporcionar un color de texto a ese, está bien
to this one and provide a text color to that one okay
13:17:56
así que ahora si cambiamos allí y eso no se ve tan
so now if we change there and that's not looking that
13:17:59
genial, sí, no se ve tan genial, quita eso una vez más, también quita el color del texto y sí, se ve genial
cool yeah it is not looking that cool remove that once again also remove the text color and yeah it is looking cool
13:18:09
sí, se ve genial, así que podemos hacer muchas cosas con ellos, pero ya sabes, no tengo mucho tiempo para
yeah it is looking great so we
13:18:12
esta interfaz, puedes cambiar la interfaz como quieras, pero
can do a lot sort of stuff with them but you know i don't have a lot of time for
13:18:15
solo quiero concentrarme en la lógica, así que entremos en la sección de acerca de
this ui you can change the ui to like however you want but
13:18:18
la sección de acerca de será súper directa, así que
i only want to focus on the logic so let's get into the about
13:18:21
solo voy a continuar y quitar el acerca de aquí y cambiar
section the about section will be super straightforward so
13:18:25
eso a sección y también cambiar ese a sección también y pongamos nuestro nombre de clase de fondo gris de 100 y el relleno para el eje y se establecerá en 12.
i'll just go ahead and remove the about right here and change
13:18:28
El relleno para el eje x se establecerá en 4. Y para el tamaño de pantalla más pequeño, vamos a establecer el relleno para el eje x en 6.
that to section and also change that one to section as well and let's just put our class name of background gray of 100 and padding for the y axis will be set to 12.
13:18:38
Y para el tamaño de pantalla más grande el relleno para el eje x se establecerá en 8.
Pairing for the x axis will be set to 4. And for the smaller screen size we are going to be setting the pairing for the x axis of 6.
13:18:45
Y para la pantalla más grande, el emparejamiento para el eje x se establecerá en 8.
And for the larger screen pairing for the x axis will be set to 8.
13:18:49
Y dentro de esta sección vamos a crear un div con la clase de ancho máximo que se establecerá en 4xl.
And inside this section we are going to be creating a div with the class of max width which will be set to 4xl.
13:18:56
Y también el margen para el eje x se establecerá en automático. Dentro de este div, simplemente vamos a crear nuestro h2 con la clase de texto 3xl para ser precisos.
And also margin for the x axis will be set to auto. Inside this div let's just create our h2 with the class of text 3xl to be precise.
13:19:04
Y la fuente se establecerá en extra bold
And font will be set to extra bold
13:19:07
está bien y el texto también se establecerá en gris 900
okay and the text will be also set to gray of 900
13:19:11
y el margen para la parte inferior se establecerá en cuatro
and margin for the bottom will be set to four
13:19:14
maldita sea seis ahí vamos
god damn it six there we go
13:19:17
y voy a escribir algo sobre hosin y puedes especificar
and i'm going to write like about hosin and you can specify
13:19:21
tu propio nombre y aquí puedes ver que ahora estamos obteniendo más sobre hosin
your own name and here you can see we are now getting more about hosin
13:19:24
lo cual se ve genial, pero ahora debajo de este h2, ¿qué quieres hacer? Solo quieres crear un párrafo que dirá algo como texto de totalmente grande y el texto se establecerá en gris 700. Ahora déjame simplemente colocar todas esas cosas sobre mí.
which is looking great but now underneath this h2 what do you want to do you just want to create a paragraph and which will say like text of totally large and text will be set to gray of 700 now let me just I will just place all of that stuff about myself.
13:19:37
No tienes que preocuparte por nada de eso. También puedes copiar y colocar eso o simplemente puedes pedirle a chatgbt que escriba allí por ti.
You don't even have to worry about any of that. You can also copy and place that or you can just ask chatgbt to write there for you.
13:19:43
Debajo de eso, también voy a crear un párrafo. Una vez más, con la clase de margen para la parte superior que se establecerá en 4.
Underneath there I am going to also create a paragraph. Once again with the class of margin for the top will be set to 4.
13:19:50
El texto se establecerá en no extra grande, sino solo grande. El texto se establecerá en grado 700. Así que simplemente escribiré un 700.
Text will be set to not extra large but just large. Text will be set to grade of 700. So I will just write a 700.
13:20:00
ingresa y dentro de ahí voy a colocar más contenido. Así que estos son solo los videos si quieres ver allí y esto es solo una sección sobre mí.
enter and inside there I'm going to place my more content. So these are just the videos if you want to watch there and this is just about section about me.
13:20:09
Ahora déjame simplemente ir a los proyectos y eso también está hecho.
Now let me just go ahead and go to the projects and that's also done.
13:20:12
También tenemos que ir a los cursos, eso también está hecho, pero finalmente tenemos que ocuparnos de esta sección de contacto y hemos terminado.
We also have to go into the courses that's also done but finally we have to take care of this contact section and we are done.
13:20:19
Ahora déjame ir a mi contacto y simplemente proporcionemos mi sección de contacto aquí mismo.
Now let me go ahead and go to my contact and let's just provide my contact section right here.
13:20:25
Como puedes ver, tengo un array de enlaces y dentro de este array tengo algunos objetos. Cada objeto tendrá la referencia, la etiqueta y también el ícono.
As you can see I have a links array and inside this array I have a few objects. Each object will have the reference, the label and also the icon.
13:20:32
Así que lo que voy a hacer es que también voy a colocar todos los íconos aquí mismo. Así que sus errores ahora han desaparecido con éxito.
So what I'm going to do is that I'm going to also place all of the icons right here. So their errors are now successfully gone.
13:20:39
Si quieres proporcionar tus propios enlaces, eres más que bienvenido a hacerlo. Pero si quieres proporcionar los míos, también puedes copiar eso de mi repositorio de GitHub.
If you want to provide your own links you are more than welcome to do that. But if you want to provide mine so you can also go ahead and copy that from my GitHub repository.
13:20:46
Así que déjame cerrar eso y ahora vamos a iterar a través de allí y luego vamos a renderizar allí.
So let me just close that and now we are going to be iterating over through there and then we are going to be rendering there.
13:20:52
Así que lo que voy a hacer es que voy a eliminar este contacto de aquí y seleccionar este div y cambiarlo a una sección.
So what I'm going to do is then I'm going to just remove this contact from here and select this div and change there to a section.
13:20:59
Voy a proporcionar el nombre de clase de fondo gris 100. El emparejamiento para el eje y se establecerá en 12.
I'm going to provide the class name of background gray of 100. Pairing for the y-axis will be set to 12.
13:21:04
El emparejamiento para el eje x se establecerá en 4. Y para el tamaño de pantalla más pequeño, vamos a proporcionar el emparejamiento para el eje x de 6.
Pairing for the x-axis will be set to 4. And for the smaller screen size, we're going to be providing pairing for the x-axis of 6.
13:21:11
Y para el tamaño de pantalla grande, vamos a proporcionar el emparejamiento para el eje x de 8.
And for the large screen size, we're going to be providing pairing for the x-axis of 8.
13:21:15
Dentro de esta sección, vamos a crear nuestro h2 con las clases de texto 3xl. Y la fuente se establecerá en negrita extra.
Inside this section, we're going to be creating our h2 with the classes of text 3xl. And font will be set to extra bold.
13:21:23
y el texto será gris 900 y el margen inferior se establecerá en 6.
and text will be gray 900 and margin for the bottom will be set to 6.
13:21:28
Así que contáctame y guarda mi archivo. Ahora aquí puedes ver que estamos obteniendo nuestra sección de contáctame justo aquí
So contact me and save my file. Now here you can see we're now getting our contact me section right here
13:21:35
y ahora debajo de eso, simplemente vamos a crear o hacer con la clase de enlaces y los elementos ahora se centran. Y aquí vamos a iterar sobre todos esos enlaces.
and now underneath there let's just create or do with the class of links and items is now set to center. And here we're going to be iterating over through all of that links.
13:21:43
Desde aquí, como puedes ver, tenemos todos esos enlaces. Ahora quieres iterar sobre todos ellos y proporcionar cada uno de los enlaces.
From here like as you can see we have all of that links. Now you want to iterate over through all of them and provide each of the link.
13:21:49
Dentro de los enlaces, vamos a renderizar nuestra etiqueta de anclaje y voy a eliminar este href y cambiarlo a link.href.
Inside the links we're going to be rendering our anchor tag and I am going to remove this href and change that to link.href.
13:21:57
También proporcionaré la clave y para esta clave simplemente renderizaré como link.label.
I'll also provide the key and for this key I'll just render like link.label.
13:22:02
También tenemos que proporcionar el objetivo y el objetivo se establecerá en guion en blanco. Proporciona la relación y también las clases.
We also have to provide the target and target will be set to dash blank. Provide the relation and also the classes.
13:22:09
Así que para las clases, flex y los elementos se centrarán.
So for the classes flex and items will be set to center.
13:22:13
El espacio se establecerá en el eje x de 2 y el texto se establecerá en gris 900 y alguien pasará el cursor por allí
Space will be set to x axis of 2 and text will be set to gray of 900 and somebody hover over there
13:22:20
así que el texto se establecerá en gris 600 margen
so text will be set to gray 600 margin
13:22:23
para la derecha se establecerá en dos rems como
for the right will be set to two rems like
13:22:27
así que rem dos rem allí
so rem two rem there
13:22:30
vamos y ahora dentro de este, ¿qué quieres
we go and now inside this one what do you want to
13:22:33
¿solo quieres escribir sobre un enlace punto icono?
do you just want to write over a link dot icon
13:22:36
guarda mi archivo y ahora debajo de este icono de enlace
save my file and now underneath this link icon
13:22:40
simplemente vamos a crear nuestro span, las clases serán texto grande, eso será todo y aquí tenemos que renderizar nuestro enlace punto nivel así y eso será todo para la sección de contexto.
let's just create our span the classes will be text large that's going to be it and here we have to render our link dot level like so and And that's going to be it for the context section.
13:22:50
Así que simplemente revisemos esto. Aquí puedes ver que tenemos un Twitter o X. Hoy en día tenemos un YouTube, GitHub e Instagram.
So let's just check this out. Here you can see we have a Twitter or X. Nowadays we have a YouTube, GitHub and Instagram.
13:22:57
Está bien, así que esa es la sección de contexto. Tenemos cursos, proyectos, acerca de y inicio. También podemos proporcionar nuestra propia imagen de perfil.
Okay, so that's the context section. We have a courses, projects, about and home. We can also provide our own profile image.
13:23:04
También podemos proporcionar la imagen del banner desde nuestra computadora. Y este es solo nuestro proyecto básico.
We can also provide the banner image from our computer. And this is just our basic project.
13:23:10
Es hora de hacer una configuración para nuestro tercer proyecto. Así que simplemente escribamos npm create read y latest. El nombre del proyecto es blogs.
Time to make a setup for our third project. So let's just write npm create read and latest. The project name is blogs.
13:23:17
y voy a elegir ReactJS con TypeScript, entrar en los blogs y ahora simplemente instalemos cada cosa.
and I'm going to choose ReactJS with TypeScript, go into the blocks and now let's just install every single thing.
13:23:23
Ahora voy a entrar en Tailwind CSS, hacer clic en comenzar, ir al marco y guía.
Now I'm going to go into the Tailwind CSS, click on the getting started, go to the framework and guide.
13:23:29
Ahora déjame copiar este comando y colocarlo aquí dentro de mi terminal integrada.
Now let me copy this command and place it right here inside my integrated terminal.
13:23:34
Presiona enter para configurar Tailwind CSS y también voy a copiar este contenido.
Hit enter to configure Tailwind CSS and also I'm going to copy this content.
13:23:38
Vamos a copiar eso y entrar en mi configuración de Tailwind y reemplazarlo con este contenido. Así que hagámoslo.
Let's just copy there and go into my Tailwind config and replace it with this content. So let's just do that.
13:23:45
Voy a copiar cada cosa de allí. Ve a el archivo index.css y reemplázalo con este nuevo. Está bien.
I'm going to also go ahead and copy every single thing from there. Go to the index.css file and replace it with this new one. Okay.
13:23:53
Y supongo que eso será todo. Pero voy a copiar allí. Esto va a la aplicación. No CSS, sino app.tsx.
And I guess that's going to be it. But I'm going to copy there. This is going to the app. Not CSS, but app.tsx.
13:24:00
Y elimina cada cosa de allí. Y solo escribiré el rfce. Y escribamos esta palabra h1 aquí. Está bien.
And remove every single thing from there. And I'll just write the rfce. And let's just write this h1 word here. Okay.
13:24:06
Así que voy a abrir mi terminal una vez más y usar npm run dev. Y veamos esto. Sí. Estamos obteniendo un hola mundo.
So I'm going to open my terminal once again and use npm run dev. And let's just check this out. Yep. We are getting a hello world.
13:24:13
pero también voy a hacer un poco de limpieza así que solo eliminaré esta carpeta de assets
but I'm going to also make a bit of cleanup so I'll just remove this assets folder
13:24:16
la carpeta pública la carpeta app.css y
the public folder the app.css folder and
13:24:20
sí, supongo que el resto estará bien, a continuación vamos
yeah I guess the rest of them will be fine next we are going
13:24:23
a definir nuestra navegación así que solo crearé un div y dentro
to be defining our navigation so I'll just create a div and inside
13:24:26
de este div vamos a renderizar nuestra navegación pero primero dejemos
this div we are going to be rendering our navigation but first of all let
13:24:29
mejor crear una carpeta con el nombre de componentes y dentro de ellas vamos a crear nuestro navigation.tsx usaré el rafce y registraré dentro del componente de la aplicación como navegación.
me just create a folder with the name of components and inside them we are going to be creating our navigation.tsx I'll use the rafce and register inside the app component like navigation.
13:24:43
Este componente, archivo semi y aquí puedes ver que ahora estamos obteniendo nuestra navegación que se ve genial.
This component, semi file and here you can see we are now getting our navigation which is looking cool.
13:24:48
Así que escribamos nuestra navegación y luego vamos a saltar a las siguientes cosas.
So let's just type our navigation then we are going to be jumping into the next stuff.
13:24:51
Así que cambiaré este div a nav porque estamos creando nuestra navegación y crearé un nombre de clase de border2
So I'll change this div to nav because we are creating our navigation and I'll create a class name of border2
13:24:59
y el texto se establecerá en completamente negro, el borde será gris de 200, el padding se establecerá en 4 y será un flex, la justificación se establecerá en entre y los elementos se centrarán.
and text will be set to totally black, border will be gray of 200, padding will be set to 4 and it's going to be a flex, justify will be set to between and items will be set to center.
13:25:11
Dentro de esta navegación vamos a crear un div con la clase de flex y luego los elementos se centrarán, el borde se establecerá en 2 y completamente redondeado, 4
Inside this navigation we are going to be creating a div with the class of flex and then items will be set to center border will be set to 2 and totally rounded, 4
13:25:20
preparando para el eje x se establecerá en 4, preparando para el eje y se establecerá en 2, el ancho máximo se establecerá en medio y el margen para la izquierda se establecerá en un valor arbitrario.
preparing for the x axis will be set to 4, preparing for the y axis will be set to 2, max width will be set to medium and margin for the left will be set to arbitrary value.
13:25:30
Así que solo usaré como 5rem.
So I'll just use like 5rem.
13:25:33
Dentro de esto vamos a renderizar nuestro ícono pero primero tenemos que instalar allí.
Inside this we are going to be rendering our icon but first of all we have to install there.
13:25:37
Así que usaré npm i y luego react icons para que se instale allí en mi máquina.
So I'll use npm i and then react icons so it's going to install there in my machine.
13:25:43
Ahora que eso está hecho, déjame usar mi npm render una vez más. de nuevo y
Now that's done let me use my npm render once again. again and
13:25:46
solo usaré como fa search desde donde desde
I will just use like fa search from where from
13:25:49
los íconos de react así que vamos a renderizarlos ahora debajo
the react icons so let's just render them now underneath
13:25:53
vamos a usar un campo de entrada con el tipo de texto que voy
them we are going to be using what input field with the type of text I'm
13:25:56
a proporcionar también el placeholder que dirá como buscar
going to also provide the placeholder which will say like search
13:25:59
punto punto punto y también proporcionaré el nombre de la clase de fondo
dot dot dot and I will also provide the class name background
13:26:02
se establecerá como totalmente transparente y también
will be set to totally transparent and also
13:26:05
el contorno se establecerá en ninguno y el ancho se establecerá en totalmente completo, de acuerdo, voy a volver para que ustedes puedan ver todo un poco mejor y así es como se ve aquí.
outline will be set to none and width will be set to totally full okay I'm going to go back so you guys can see everything a bit better and this is how it looks like right here.
13:26:17
Sé que se ve horrible, pero sí, todavía se ve un poco mejor.
I know it is looking awful but yeah it is looking still a bit better.
13:26:21
Ahora debajo de este div vamos a crear una sección con la clase de flex y luego los elementos vienen.
Now underneath this div we're going to be creating a section with the class of flex and then items come on.
13:26:27
Los elementos se centrarán y también proporcionaré un margen a la derecha de 5rem así, y dentro de esta sección simplemente rendericemos sobre FAUSER CIRCLE.
Items will be set to center and I'm going to also provide margin for the right of 5rem like so and inside this section let's just render over FAUSER CIRCLE.
13:26:39
Los renderizo y voy a proporcionar el nombre de la clase de texto que se establecerá en 3 Excel. El margen a la derecha se establecerá en 2.
I render them and I'm going to provide the class name of text will be set to 3 Excel. Margin for the right will be set to 2.
13:26:46
Si guardo mi archivo y reviso esto, aquí pueden ver que ahora estamos obteniendo nuestro ícono. También estamos obteniendo este campo de búsqueda aquí.
If I save my file and check this out so here you can see we are now getting our icon. We are also getting this search field right here.
13:26:53
Ahora iré a mi F.TSX una vez más y aquí dentro crearé un div con la clase de flex y justificar al centro
Now I'll go to my F.TSX once again and here inside there I'll create a div with the class of flex and justify center
13:27:00
y dentro de este div vamos a crear nuestra área principal aquí, pero no ahora.
and inside this div we're going to be creating our main area right here but not right now.
13:27:06
Ahora, debajo de eso vamos a crear nuestro div con una clase de ancho y el ancho será un valor arbitrario como 30% y simplemente cerremos allí.
Now Now underneath there we are going to be creating our div with a class of width and the width will be arbitrary value like 30% and let's just close there.
13:27:15
Dentro de este div vamos a definir algunos componentes. Comencemos con un componente de personas a seguir.
Inside this div we are going to be defining a few components. Let's just start from a people to follow component.
13:27:20
Así que simplemente crearé un componente con el nombre de people to follow.tsx y voy a usar mi RAFC dentro de allí y renderizar personas a seguir aquí en el archivo semi.
So I'll just create a component with the name of people to follow.tsx and I'm going to use my RAFC inside there and render people to follow right here semi file.
13:27:32
y aquí pueden ver que ahora estamos obteniendo más componentes de personas a seguir que se ven geniales.
and here you can see we are now getting more people to follow component which is looking great.
13:27:36
Así que lo primero que quiero hacer es colocar a estas personas a seguir y tenemos algunos nombres de personas y también la lista de seguidores.
So the first thing that I want to do is that I want to place these people to follow and we have a few people names and also the following list.
13:27:43
Así que lo que voy a hacer es iterar a través de allí y renderizar eso en este componente.
So what I'm going to do is that I'm going to iterate over through there and render that into this component.
13:27:48
De acuerdo, así que simplemente eliminaré a estas personas a seguir. Voy a proporcionar un poco de clase a esto, así que el fondo se establecerá en totalmente blanco y el padding se establecerá en 4 y redondeado totalmente grande sombra
Okay so I'll just remove this people to follow. I'm going to provide a bit of classing to it so background will be set to totally white and padding will be set to 4 and rounded totally large shadow
13:28:00
Y ahora debajo de eso crea un h3 con la clase de fuente semibold.
And now underneath there create a h3 with the class of font semibold.
13:28:05
El texto será grande y el margen para la parte inferior se establecerá en 4.
Text will be large and margin for the bottom will be set to 4.
13:28:09
Lo que seleccionará a las personas o a quién seguir o como quieras llamarlo. Luego crea un div con la clase de espacio y.
Which will select people or who to follow or whatever you want to call there. Then create a div with the class of space y.
13:28:16
Dentro de allí simplemente vamos a iterar a través de todas esas personas a seguir. Así que simplemente pondré el rojo aquí. Y voy a usar el método map.
Inside there let's just iterate over through all of that people to follow. So I'll just put the red here. And I'm going to use the map method.
13:28:23
Va a tomar a la persona y también el índice. y
It's going to take the person and also the index. and
13:28:26
dentro de esta función de flecha vamos a crear nuestra tarjeta de usuario que tomará una clave como prop y dentro de la clave vamos a proporcionar nuestro índice y luego también tomará a la persona como el valor principal.
inside this arrow function we are going to be creating our user card which will take a key as a prop and inside the key we are going to be providing our index and then it's going to also take the person as the main value.
13:28:38
Así que voy a cerrar eso y crear mi componente de tarjeta aquí.
So I'm going to close that and create my card component right here.
13:28:42
Simplemente usaré nuestro user card.tsx
I'll just use our user card.tsx
13:28:46
dentro de ahí, simplemente usemos nuestro archivo rafc semi y rendericemos eso aquí mismo.
inside there let's just use our rafc semi file and render that right here.
13:28:51
Así que tenemos que renderizar nuestro componente de tarjeta de usuario y aquí puedes ver que ahora estamos obteniendo la tarjeta de usuario muchas veces.
So we have to render our user card component and here you can see we're now getting user card user card a lot of time
13:28:58
Ahora déjame entrar en esta tarjeta de usuario y crear ahí, así que toma el índice y también toma a la persona.
now let me go into this user card and create there so it takes the index and it also takes the person
13:29:04
Está bien, así que déjame crear una interfaz para esto, como usuario.
okay so let me just create a interface for this so like user
13:29:08
interfaz de propiedades de tarjeta de usuario
interface user card props
13:29:11
o algo así, proporcionaré un índice que se establecerá en un número y también proporcionaré una persona que se establecerá en una cadena y lo anotaré con la propiedad de tarjeta de usuario y ahora entremos en la interfaz de usuario.
or something like that i'll provide index which will be set to a number and i'm going to also provide a person which will be set to a string and i'll annotate there with the user card prop and now let's get into the UI.
13:29:23
Voy a eliminar esta tarjeta de usuario de aquí y voy a poner un nombre de clase allí.
I'm going to remove this user card from here and I'm going to put a class name to there.
13:29:28
Así que simplemente pongamos un flex y los elementos se establecerán en el centro y la justificación se establecerá entre en este caso.
So let's just put a flex and items will be set to center and justify will be set to between in this case.
13:29:34
Dentro de este div, vamos a crear una sección con una clase de flex y los elementos se establecerán en el centro.
Inside this div, we're going to be creating a section with a class of flex and items will be set to center.
13:29:41
Dentro de ahí, simplemente rendericemos nuestro ícono que es fa user circle.
Inside there, let's just render our icon which is fa user circle
13:29:44
y rendericemos ahí mismo con también estas clases como el texto se establecerá en 3xl, el margen a la derecha se establecerá en un gris total de 500.
and render there right here with also these classes like text will be set to 3xl, margin for the right will be text will be set to totally grey of 500
13:29:55
500 así. Ahora déjame guardar.
500 like so. Now let me just save
13:29:58
mi archivo y aquí puedes ver que ahora estamos obteniendo sus íconos aquí mismo.
my file and here you can see we are now getting their icons right here
13:30:01
lo cual se ve genial, pero ahora debajo de eso también vamos a crear un span y simplemente rendericemos nuestro person.name dentro de ahí y sí, así es como se ve y se ven geniales.
which is looking cool but now underneath there we're going to be also creating a span and let's just render our person.name inside there and yeah this is how it looks like and they are looking cool.
13:30:12
Ahora debajo de este div o esta sección, para ser precisos, vamos a crear nuestro botón y dentro de este botón simplemente diremos como persona SIGUIENDO.
Now underneath this div or this section to be precise we're going to be creating our button and inside this button we will just say like person F OLL OWING
13:30:23
si ese es el caso, vamos a decir como siguiendo, pero
if that's the case we are going to be saying like following but
13:30:26
si ese no es el caso, simplemente diremos como seguir y aquí puedes ver que ahora estamos obteniendo el botón de seguir y también el botón de siguiendo aquí, ahora déjame estilizar eso un poco, pero ese estilo con
if that's not the case so we will just say like follow and here you can see we are now getting the follow button and also the following button right here now let me just style that a bit but that styling with
13:31:21
Ahora déjame ir y crear otro componente con el nombre de
Now let me go ahead and create another component with the name of
13:31:24
lista de tendencias.tsx
trends list.tsx
13:31:27
y voy a usar el rafc dentro, vamos.
and I'm going to use the rafc inside come on
13:31:30
rafc dentro de ahí una vez más y ve a
rafc inside there once again and go to
13:31:33
mi app.tsx y renderiza este componente aquí como tendencias.
my app.tsx and render this component right here like trends
13:31:37
lista sí y renderiza esto allí.
list yeah and render there this
13:31:40
así es como se ve que voy a renderizar todas sus tendencias, ¿verdad?
is how it looks like is that I'm going to render all of their trends right
13:31:43
aquí, así que también puedes copiar eso de mi repositorio de ghab si quisieras, así que básicamente tenemos un arreglo con el nombre de las tendencias, dentro de él tenemos algunos objetos que tendrán. También puedes crear el título y también el autor.
here so you can also copy that from my ghab repository if you wanted to so basically we have array with the name of trends inside there we have a few objects which will have You can also create the title and also the author.
13:31:53
También puedes crear el título tú mismo si lo deseas. Pero si quieres copiar de mi repositorio de GitHub, puedes hacerlo perfectamente.
You can also create the title by yourself if you wanted to. But if you want to copy from my GitHub repository, you can totally do that.
13:31:59
Voy a eliminar esta lista de tendencias de aquí. Voy a proporcionar el nombre de la clase. El fondo se establecerá completamente en blanco.
I'll just remove this trends list from here. I'm going to provide the class name. Background will be set to totally white.
13:32:06
El relleno se establecerá en 4 y será redondeado grande. También se proporcionará sombra y el margen superior se establecerá en 8.
Padding will be on or around set to 4 and rounded large. Shadow will be also provided and margin for the top will be set to 8.
13:32:13
Dentro de este div, vamos a crear un H3 con la clase de fuente, semi negrita. La fuente será completamente grande.
Inside this div, we're going to be creating H3 with the class of font, semi bold. bold and the text will be set to totally large.
13:32:21
El margen inferior se establecerá en 4. Ahora diré algo como las principales tendencias de hoy o algo así.
Margin for the bottom will be set to 4. Now I'll just say like today's top trends or something like that.
13:32:28
Ahora, si guardo mi archivo, así es como se ve, están luciendo rojos.
Now if I save my file so this is how it looks like they are looking red.
13:32:32
Y ahora vamos a usar nuestro ul con la clase de espacio en el eje y que se establecerá en 4.
And now let's just use our ul with the class of space on the y-axis will be set to 4.
13:32:37
Y voy a iterar sobre todas sus tendencias utilizando el método map. Va a tomar la tendencia y también el índice.
And I'm going to iterate over through all of their trends by using the map method. It's going to take the trend and also the index.
13:32:44
Así que dentro de esta función, ¿qué quieres hacer? Solo queremos obtener nuestro li y dentro de ese li primero déjame poner una clave y la clave será ese índice y también voy a poner un nombre de clase.
So inside this function what do you want to We just want to get our li and inside that li first of all let me just put a key and the key will be that index and I'm going to also put a class name.
13:32:54
Vamos a escribir un nombre de clase. El nombre de la clase se establecerá en flex y flex se establecerá en dos puntos.
Let's just write a class name. Class name will be set to flex and flex will be set to colon.
13:32:59
Dentro de ese li vamos a usar nuestro span, span así y poner la fuente en mediana.
Inside that li we are going to be using our span, span like so and put the font of medium to it.
13:33:06
Así que en este caso vamos a usar trend.title y ahora debajo de este span vamos a crear nuestro span una vez más con la clase de texto pequeño y también la clase de texto pequeño y también el texto se establecerá en gris 500.
So in this case we are going to be using trend.title and now underneath this span we are going to be creating our span once again with the class of text small and also class of text small and also the text will be set to gray of 500.
13:33:19
Está bien y ¿por quién? Por la tendencia y luego punto autor.
Okay and by who? By the trend and then dot author.
13:33:25
Vamos, ve a la parte superior, quita ese ícono de allí y cambia este a trend punto autor.
Come on go to the top remove that icon from there and change this one to trend dot author.
13:33:32
Ahora que eso está hecho. Déjame revisar esto. Así que sí, hay otro componente que también se ve genial.
Now that's done. Let me check this out. So yeah there's other component which is also looking cool.
13:33:38
Ahora voy a ir al archivo app.tsx una vez más y crear mi componente de lista de temas.
Now I'm going to go to the app.tsx file once again and create my topic list component.
13:33:43
Así que usaré algo como topics list.tsx y crearé mi componente aquí y registraré ese componente de lista de temas aquí.
So I'll use like topics list.tsx and create my component right here and register that topics list component here.
13:33:54
Voy a guardar mi archivo. Ir allí una vez más. Y lo primero que quiero hacer es que no quiero simplemente colocar estos temas como tenemos tecnología y diseño y pensamiento y así sucesivamente.
I'm going to save my file. Go there once again. And the first thing that I want to do is that I don't want to just place these topics like we have technology and design and thinking and so on and so forth.
13:34:03
Voy a colocar eso aquí. Ahora voy a entrar en mi UI. Así que cambiaré el fondo a completamente blanco. El relleno se establecerá en 4.
I'm going to place that here. Now I'm going to go into my UI. So I'll change the background to totally white. Padding will be set to 4.
13:34:10
Totalmente redondeado. Grande. Y sombra. El margen superior se establecerá en 8 y dentro de este div vamos a crear h3 con un nombre de clase de fuente semi negrita y también el texto se establecerá en completamente grande.
Totally rounded. Large. And shadow. Merger for the top will be set to 8 and inside this div we are going to be creating h3 with a class name of font Semi Bold and also the text will be set to totally large.
13:34:22
El margen inferior se establecerá en 4 que dirá algo como temas para ti.
Merger for the bottom will be set to 4 which will say like topics for you.
13:34:27
Archivo semi una vez más y ahora estamos obteniendo nuestros temas para ti aquí mismo.
Semi file once again and we are now getting our topics for you right here.
13:34:31
Ahora debajo de eso crearé un div con una clase de flex y también flex se establecerá en wrap.
Now underneath that I will create div with a class of flex and also flex will be set to wrap
13:34:36
y WRIP así y el espacio se establecerá en 2 dentro de este div.
and WRIP like so and gap will be set to 2 inside this div.
13:34:42
Vamos a iterar sobre todos sus temas utilizando el método map y proporcionar mi tema.
We are going to be iterating over through all of their topics by using the map method and provide my topic.
13:34:47
Escribamos un tema y también el índice dentro de allí. Y este lápiz tendrá un emparejamiento para el eje x de 3 y un emparejamiento para el eje y de 1.
Let's just write a topic and also the index inside there. And this pen will have pairing for the x-axis of 3 and pairing for the y-axis of 1.
13:34:54
El fondo se establecerá en gris 200 y el texto se establecerá en gris 700.
Background will be set to gray of 200 and the text will be set to gray of 700
13:35:01
así que si presiono tab y también voy a proporcionar un texto
like so if I hit tab and I'm going to also provide a text
13:35:04
de tamaño totalmente pequeño y el cursor redondeado completo también se establecerá en puntero y cuando alguien pase el cursor sobre allí cambiará el fondo a gris 300.
of totally small and rounded full cursor will be also set to pointer and when somebody hover over there change the background to grey of 300
13:35:15
y también especificaré la clave y la clave estará sobre el índice. Dentro de este panel, ¿qué quieres hacer?
and I'll also specify the key and the key will be over index. Inside this pane what do you want to do?
13:35:20
Solo queremos renderizar su tema específico. Y ahora déjame guardar mi archivo y revisar esto.
We just want to render their specific topic And now let me just save my file and check this out.
13:35:25
Así que aquí puedes ver que ahora estamos obteniendo todas las tecnologías y temas aquí mismo. Ahora déjame crear mi contexto.
So here you can see we are now getting all of the technologies and stuff topics right here. Now let me create my context.
13:35:31
Así que lo primero que quiero hacer es crear una carpeta con el nombre de compartido. Y dentro de allí vamos a crear nuestro blog context.tsx.
So the first thing that I want to do is I want to create a folder with the name of shared. And inside there we are going to be creating our blog context.tsx.
13:35:39
Y aquí necesitaremos algunas cosas como crear contexto.
And here we will need a few things like create context.
13:35:42
También necesitarías el uso de hilo y también el uso de contexto. Está bien.
You would also need the use thread and also the use context as well. Okay.
13:35:47
Y ahora debajo de allí, definamos nuestro contexto. Solo usaré como crear contexto.
And now underneath there let's just define our context. I'll just use like create context.
13:35:51
y el valor inicial será indefinido y voy a
and the initial value will be undefined and I'm going
13:35:54
almacenar en algún tipo de variable como contexto de bloque y va a ser igual
to store in some sort of a variable like block context and it's going to be equals
13:35:57
a este contexto, así que ahora déjame también crear una interfaz para eso.
to this context so now let me also create an interface for that
13:36:00
así que vamos a crear nuestra interfaz y aquí va
so let's just create our interface and here it's
13:36:03
a tomar como tipo de contexto de bloque y dentro
going to take like block context type and inside
13:36:07
este primero de todo vamos a crear nuestros bloques este
this one first of all we are going to be creating our blocks this
13:36:10
será un bloque enorme, así que voy a separarlo en un archivo separado, así que voy a proceder a crear mi archivo justo
will be a huge block so I'm going to separate that into a separate file so I'm going to go ahead and create my file right
13:36:16
aquí con el nombre de types.ts y solo voy a colocar
here with the name of types.ts and i'm going to just place
13:36:19
estos tipos aquí, así que tenemos un id que será un número, el
these types right here so we have a id which will be a number the
13:36:22
título será una cadena, la descripción será una cadena, la imagen será una cadena.
title will be string description will be string the image will be string
13:36:25
y el tiempo también será una cadena, está bien, así que lo que
and the time will also be string okay so what
13:36:28
voy a hacer es que voy a agarrar el derecho aquí y debajo
i'm going to do is that i'm going to grab the right here and underneath
13:36:32
de que también vamos a definir nuestro añadir bloque y hay
that we're going to be also defining our add block and there's
13:36:35
va a haber una función que tomará un bloque como perímetro, también vamos a proporcionar los bloques como un tipo y va a devolver el blanco y ahora también proporcionemos nuestra actualización.
going to be a function which will take a block as a perimeter we're going to be also providing the blocks as a type and it's going to return the white and now also let's just provide our update
13:36:44
el blog se va a establecer en el blog una vez más y aquí tenemos que anotar allí con el blog
blog it's going to be set to the blog once again and here we have to annotate there with the blog
13:36:50
y dentro de allí solo vamos a devolver el blanco y también tenemos que eliminar el blog así que solo proporcionemos nuestro id y el id se establecerá en un número y va a devolver el blanco
and inside there we're going to be only returning the white and also we have to delete the blog so let's just provide our id and id will be set to a number and it's going to return the white
13:37:00
bueno, así que ahora eso está totalmente hecho, voy a anotar mi contexto
okay so now that's totally done i'm going to annotate my context
13:37:03
usando este tipo de contexto de blog o indefinido, así que inicialmente estamos proporcionando el valor de indefinido hoy, así que eso es genial ahora
by using this blog context type or undefined so initially we're providing the value of undefined today so that's great now
13:37:11
tenemos que crear nuestro proveedor así que usaré un cons y luego bloque
we have to create our provider so i'll use a cons and then block
13:37:15
proveedor y aquí vamos a anotar
provider and here we are going to be annotating
13:37:18
allí usando reactjs y luego componente funcional, está bien, así que si quieres anotarlos, vamos a proporcionar un children y para este children vamos a usar react.react
there by using reactjs and then functional component okay so if you want to annotate them we're going to be providing a children and for this children we're going to be using react.react
13:37:28
nodo que vendrá de react.js y ahora vamos a crear nuestro contexto justo aquí, así que lo que voy a hacer es que solo voy a proporcionar mis children, ahora déjame decir allí
node which will be coming from the react.js and now let's just create our context right here so what i'm going to do is that i'm going to only provide my children now let me just say over there
13:37:39
lo primero que quiero hacer es que quiero usar mi use tier y
the first thing that i want to do is that i want to just use my use tier and
13:37:42
el valor inicial se establecerá en este array vacío y
the initial value will be set to this empty array and
13:37:45
también voy a anotar allí con el bloque y aquí tenemos
i'm going to also annotate there with the block and here we have
13:37:48
para solo escribir un bloque de array voy a desestructurar
to just write a block of array i'm going to destructure
13:37:51
los bloques y también los bloques de conjunto de allí ahora
the blocks and also the set blocks out of there now
13:37:55
también vamos a crear una función que nos permita agregar un bloque así que
we are going to be also creating a function which allows us to add a block so
13:37:58
usaré como agregar bloque y va a ser igual al bloque y
i'll use like add block and it's going to be equals to the block and
13:38:01
también voy a anotar allí con ese bloque, está bien, y dentro de allí no vamos a hacer nada loco, pero solo escribiré como setBlocks y primero tenemos que clonar nuestros bloques existentes y luego tenemos que agregar uno nuevo.
i'm going to also annotate there with that block okay and inside there we are not going to be doing anything crazy but i'll just write like setBlocks and first of all we have to clone our existing blocks and then we have to add one new one.
13:38:13
Ahora debajo de ellos también vamos a crear uno para actualizar un bloque.
Now underneath them we're going to be also creating one for the updating a block.
13:38:17
Así que solo usaré updateBlock y aquí tenemos que escribir como updateBlock y anotar con o tipo de bloques.
So I'll just use updateBlock and here we have to write like updateBlock and annotate the with or blocks type.
13:38:24
Dentro de allí voy a usar mi setBlocks porque vamos a estar mutándolos y aquí tenemos que iterar sobre todos los bloques.
Inside there I'm going to use my setBlocks because we are going to be mutating them and here we have to iterate over through all of the blocks.
13:38:30
Así que usaré como blocks.map y solo proporcionemos nuestro blog a
So I'll use like blocks.map and let's just provide our blog to
13:38:33
ellos y aquí vamos a estar verificando si blog
them and here we're going to be checking if blog
13:38:36
blog blog.id es triple igual a el
blog blog.id is triple equals to the
13:38:40
blog actualizado.id en esa situación vamos
updated blog.id in that situation we're
13:38:43
a estar renderizando nuestro blog actualizado, vamos, uh
going to be rendering our updated blog come on uh
13:38:46
blog actualizado, pero si ese no es el caso
updated blog but if that's not the case
13:38:49
vamos a renderizar nuestro blog igual que allí, voy a copiar
we're going to be rendering our blog just like there i'm going to copy
13:38:53
este blog actualizado y ahora déjame ponerlo aquí y finalmente déjame crear una función más para eliminar el blog, así que escribiré una función para eliminar el blog que va a
this updated blog and now let me just put there here and finally let me create one more function for the delete blog so i'll write a delete blog it's going to
13:39:01
tomar el id y el id será un número y dentro de ellos
take the id and id will be a number and inside them
13:39:04
vamos a usar nuestros bloques establecidos aquí, tenemos que proporcionar
we're going to be using our set blocks here we have to provide
13:39:07
nuestros bloques y usar un método de filtro y va a tomar el perímetro
our blocks and use a filter method and it's going to take the perimeter
13:39:10
así que vamos a proporcionar el bloque como un perímetro, vamos a eliminar ese bloque específico cuyo id no es igual al id que estamos proporcionando para el perímetro
so we're going to be providing the block as a perimeter we are going to be removing that specific block whose id is not equal to the id which we are providing for the perimeter
13:39:20
bien, así que ahora que hemos creado exitosamente nuestro estado, la función de agregar
okay so now that we successfully created our state the add function
13:39:23
la función de actualización y también la función de eliminar, ahora déjame proporcionar eso usando mi proveedor o proveedor de contexto, así que lo que voy
update function and also the delete function now let me provide that by using my provider or context provider so what i'm going
13:39:30
a hacer es que simplemente voy a devolver y dentro de eso voy a estar usando mi bloque
to do is that I'm going to just return and inside that I'm going to be using my block
13:39:33
contexto que hemos creado arriba y aquí tiene una propiedad más amplia, así que los voy a llamar y
context which we've created up above and here it
13:39:36
tiene una propiedad más amplia, así que los voy a llamar y
has a wider property so I'm going to call them and
13:39:39
ahora para el valor simplemente proporcionaré mi valor aquí como blogs y luego agregaré blog y actualizaré blog y también eliminaré blog así.
now for the value I'll just provide my value right here like blogs and then add blog and update blog and also delete blog like so.
13:39:49
Ahora dentro de ahí también vamos a renderizar nuestros hijos que estarán aquí para el blog. También crearé un hook para mí.
Now inside there we're going to be also rendering our children that's going to be here for the blog. I will also create a hook for myself.
13:39:56
Puedo crear totalmente en el archivo separado, pero supongo que no tengo
I can totally create in the separate file but I guess I don't have
13:40:00
Así que voy a exportar allí porque vamos a estar usando esto en múltiples archivos.
So I'm going to export there because we're going to be using the into multiple file.
13:40:03
Así que usaré como useBlocks y dentro de ahí primero vamos a consumir nuestro contexto.
So I'll use like useBlocks and inside there we're going to be first of all consuming our context.
13:40:08
Así que para eso vamos a usar nuestro useContext y proporcionar mi contexto de bloque dentro de ahí. Y también lo voy a almacenar en la variable de contexto.
So for there we're going to be using our useContext and provide my block context inside there. And I'm going to also store there in the context variable.
13:40:17
Así que solo usaré como contexto. Y ahora debajo de eso voy a estar verificando.
So I'll just use like context. And now underneath there I'm going to be checking.
13:40:20
Si no tenemos el contexto en esta situación, vamos a lanzar un nuevo error
If we don't have the context in this situation we're going to be throwing new error
13:40:25
que dirá que usar blogs debe ser utilizado
which will say like use blogs must be used
13:40:28
dentro de un proveedor de blog y
within a blog provider and
13:40:32
ahora debajo de esta verificación solo vamos a devolver nuestros contactos y
now underneath this check we are going to be just returning our contacts and
13:40:36
eso estará bien, así que ahora hemos terminado completamente con este proveedor
that's going to be fine okay so now we are totally done with this provider
13:40:39
pero también tenemos que exportar allí para que podamos usarlo, así que
but we also have to export there so we can use there so
13:40:42
solo usaré como exportar y luego podremos usarlo, ahora usaré mi proveedor para proporcionar todo ese valor
i'll just use like export and then we would be able to use there now i'll use my provider to provide all of that value
13:40:50
Así que solo usaré como proveedor de bloque y luego voy a cerrar eso aquí mismo así.
So I'll just use like block provider and then I'm going to close that right here like so.
13:40:57
Ahora aquí dentro de esta área principal lo que voy a hacer es que voy a crear una sección con la clase de margen para el eje x que se establecerá en automático y el relleno se establecerá en 6.
Now here inside this main area what I'm going to do is that I'm going to create a section with the class of margin for the x axis will be set to auto and padding will be set to 6.
13:41:07
Y dentro de esta sección vamos a crear nuestro div y luego crear un botón que tendrá algunas clases como, ya sabes, déjame ponerle un poco de clases.
And inside this section we're going to be creating our div and then create a button and which will have a few classes like you know let me just put a bit of classes to it.
13:41:15
a eso como el margen para la izquierda se establecerá en 7 rem el fondo se establecerá en totalmente negro
to it like margin for the left will be set to 7 rem background will be set to totally black
13:41:20
flex y justificar se establecerá en centro y los elementos se
flex and justify will be set to center and items will
13:41:23
también se establecerán en el centro el texto se establecerá en totalmente blanco y
also be set to center text will be set to totally white and
13:41:27
el emparejamiento para el eje x se establecerá en 4 el emparejamiento para el eje y se establecerá
pairing for the x axis will be set to 4 pairing for the y axis will be set
13:41:30
en 2 totalmente redondeado el margen para la parte inferior se establecerá
to 2 totally rounded margin for the bottom will be set
13:41:33
en 4 dentro por lo tanto la etiqueta solo usaré como agregar nuevo bloque y aquí vamos a agregar un nuevo bloque así que solo usaré como iomd agregar círculo
to 4 inside therefore the label i'll just use like add new block and here we're going to be adding a new block so i'll just use like iomd add circle
13:41:43
y presionar enter así que se va a agregar ahí mismo y para la clase estoy
and hit enter so it's going to add there right here and for the class i'm
13:41:46
voy a proporcionar el margen para la izquierda de 0 de
going to provide the margin for the lift of 0 of
13:41:49
0.5 rems está bien así que ahora si guardo mi archivo revisa
0.5 rems okay so now if i save my file check
13:41:53
esto así que aquí puedes ver que ahora estamos obteniendo nuestro botón que se ve genial
this out so here you can see we are now getting our button which is looking cool
13:41:56
pero también vamos a adjuntar un controlador de eventos allí
but we are going to be also attaching an event handler on there
13:41:59
así que cuando alguien haga clic allí vamos a encontrar esta función
so when somebody clicks there we are going to be finding this function
13:42:02
que abrirá el modelo para un nuevo blog está bien
which will be open model for new blog okay
13:42:05
así que vamos a crear esta función en unos segundos pero primero tenemos que crear nuestro estado así que voy a ir a la parte superior y crear mi estado aquí voy a definir estos dos estados como isModelOpen y luego setIsModelOpen.
so we're going to be creating this function in a few seconds but first of all we have to create our stat so i'm going to go to the top and create my stat right here i'm I'm going to define these two states like isModelOpen and then setIsModelOpen.
13:42:17
Y dentro de ahí, también vamos a obtener nuestro estado de uso y también editar bloque y setEditingBlock.
And inside there, we are going to be also getting our use state and also editing block and setEditingBlock.
13:42:24
Y vamos a obtener nuestros tipos de bloque de este archivo de tipos. Debajo de eso, también tenemos que definir dos funciones.
And we are going to be getting our block types from this types file. Underneath there, we also have to define two functions.
13:42:31
Así que para la primera función, vamos a definir como openModelForNewBlock. Dentro de esta función, ¿qué quieres hacer? SetEditingBlock.
So for the first function, we are going to be defining like openModelForNewBlock. Inside this function, what do you want to do? SetEditingBlock.
13:42:39
Quieres establecer eso en nulo. y luego establecer el modelo abierto y quieres establecer eso en verdadero.
You want to set that to null. and then set model open and you want to set that to true.
13:42:44
Ahora debajo de esta función vamos a definir una función más para
Now underneath this function we're going to be defining one more function for
13:42:47
el modelo abierto para editar y
the open model for edit and
13:42:51
aquí dentro de esta función vamos a decir como establecer el blog de edición y el valor inicial se establecerá en blog y también establecer el modelo abierto aquí vamos a establecer eso en verdadero.
here inside this function we're going to be saying like set editing blog and the initial value will be set to blog and also set model open here we're going to be setting that to true.
13:43:01
Ahora eso está hecho con éxito voy a ir a mi UI una vez más ahora debajo de este botón, ¿qué quieres hacer aquí vamos a
Now that's successfully done I'm going to go to my UI once again now underneath this button what do you want to do here we're going to be
13:43:08
también renderizando nuestro componente de lista de artículos que vamos
also rendering our article list component which we're
13:43:11
a crear en unos segundos, pero ahora voy a
going to be creating in a few seconds but now i'm going to
13:43:14
verificar si nuestro modelo está abierto, entonces
check if our model is open then
13:43:17
mostrar esta interfaz, pero si nuestro modelo no está abierto, entonces
show this ui but if our model is not open then
13:43:21
no mostrar nada en absoluto y primero voy a crear mi
don't show anything at all and i'm going to first of all create my
13:43:24
componente de modelo que voy a hacer en unos segundos
model component which i am going to do in a few seconds
13:43:27
así que voy a cerrar allí y va a tomar muchas cosas y debería ser un modelo, así que voy a copiar allí y colocarlo justo aquí y ahora déjame seguir adelante y crear este componente de modelo dentro de mi carpeta de componentes.
so i'm going to close there and it's going to take a lot of things and it should be a model like so i'm going to copy there and place it right here and now let me just go ahead and create this model component inside my components folder.
13:43:39
Así que usaré model.tsx y definiré mi componente de modelo justo aquí.
So I'll use like model.tsx and define my model component right here.
13:43:44
Así que usaré mi otro fce dentro de allí y aquí lo que quiero hacer es usar mi react y luego el componente funcional de react.js y aquí va a tomar un children.
So I'll use my other fce inside there and here what I want to do I want to use my react and then functional component from the react.js and here it's going to take a children.
13:43:54
Así que solo escribiré como children y sus children serán react.react node.
So I'll just write like children and their children will be react.react node.
13:43:59
Solo un nodo de react así y también cerraré eso y ahora lo siguiente que tenemos que hacer es que también tenemos que especificar la prop onClose.
Just a react node like so and I'll also close that and now the next thing that we have to do is that we also have to specify the onClose prop.
13:44:07
Va a ser una función. Simplemente va a devolver el ancho. Está bien, así que eso es todo, has terminado. Voy a cerrar allí así.
It's going to be a function. It's going to just return the wide. Okay, so that's all you're done. I'm going to close there like so.
13:44:14
Ahora para las props reales, solo vamos a devolver los children y luego el onClose justo aquí.
Now for the actual props, we're going to be only returning the children and then the onClose right here.
13:44:19
Así que ahora si guardo mi archivo, así es como se ve. Y ahora para
So now if I save my file, so this is how it looks like. And now for
13:44:22
esta interfaz, primero voy a proporcionar muchas clases como fixed y luego insert se establecerá en cero y el fondo
this UI, I'm going to first of all provide a lot of classes like fixed and then insert will be set to zero and background will
13:44:30
se establecerá en un fondo totalmente negro, la opacidad del fondo se
be set to totally black background opacity will
13:44:33
establecerá en 50 en este caso y también flex
be set to 50 in this case and also flex
13:44:36
los elementos estarán centrados, la justificación será centrada y
items will be center justify will be center and
13:44:39
dentro de este div vamos a crear otro div con una clase
inside this div we are going to be creating yet another div with a class
13:44:42
de fondo totalmente blanco, el padding se establecerá en cuatro, totalmente redondeado, grande y también sombra y este div será relativo así y proporcionaré mis children dentro de allí
of background totally white pairing will be set to four totally rounded large and also shadow and this div will be relative like so and provide my children inside there
13:44:53
ahora debajo de allí también vamos a crear un botón que simplemente dirá x
now underneath there we are going to be also creating a button and which will just say x
13:44:57
como cruz y también vamos a poner clases para
like cross and we're going to be also putting a classes for
13:45:01
este también como absoluto, la parte superior se establecerá en 2 a la derecha
this one as well like absolute top will be set to 2 right
13:45:04
se establecerá en 2 y el texto se establecerá en gris de 500
will be set to 2 and text will be set to gray of 500
13:45:07
100 como maldito 500 allí
100 like god damn 500 there
13:45:11
vamos y cuando alguien haga clic en este botón, así que vamos a
we go and when somebody clicks on this button so we are going
13:45:14
disparar la función de cierre que está verificando como una propiedad, ahora nuestro modelo está totalmente terminado, tenemos que importar ese modelo justo aquí y solo voy a presionar enter. Así que lo va a importar aquí.
to be firing the on close on close function which it is checking as a prop now our model is totally done we have to import that model right here and i'm going to just hit enter So it's going to import that here.
13:45:26
Para este modelo, voy a pasar mi función onClose onClose.
For this model, I'm going to pass my onClose function onClose.
13:45:31
Y esa función será solo una función de flecha, que dirá algo como setModelOpen.
And that function will be just an arrow function, which will just say like setModelOpen.
13:45:36
Y aquí tenemos que especificar el valor falso dentro de ahí. Y dentro de este, también vamos a proporcionar nuestro formulario de bloque,
And here we have to specify the false value inside there. And inside this one, we're going to be also providing our block form,
13:45:42
que vamos a crear en unos segundos. Así que ahora déjame guardar mi archivo y crear este componente de formulario de bloque.
which we are going to be creating in a few seconds. So now let me just save my file and create this block form component.
13:45:48
Así que solo voy a usar como block form.tsx.
So I'm going to just use like block form.tsx.
13:45:52
y voy a usar mi rdfc dentro de ahí e importar mi componente de formulario de bloque justo aquí. Mira esto.
and I'm going to use my rdfc inside there and import my block form component right here. Check this out.
13:45:58
Así que si hago clic ahí, nos va a dar ese formulario de bloque. También nos va a dar ese símbolo de x. Así que si hago clic en esto, va a hacer que desaparezca.
So if I click on there it's going to give us that block form. It's going to also give us that x symbol. So if I click on this it's going to make it disappear.
13:46:05
Ahora comencemos a trabajar en este componente de formulario de bloque. Así que va a tomar dos propiedades. Así que la primera propiedad que tomaremos es el bloque existente.
Now let's start work on this block form component. So it's going to take two props. So the first property we'll take is the existing block.
13:46:11
Eso se va a establecer en el bloque de edición que hemos definido arriba y también voy a poner el on close.
That's going to be set to the editing block which we have defined up above and I'm going to also put the on close.
13:46:16
Así que en el cierre y va a tomar la función de flecha.
So on close and it's going to take the arrow function.
13:46:20
Así que solo usaré como función de flecha proporcionando un set model open y voy a cambiar eso a falso.
So I'll just use like arrow function by providing a set model open and I'm going to change there to false.
13:46:25
Así que ahora déjame guardar mi archivo y vamos a entrar en este componente de formulario de blog.
So now let me just save my file and let's just go into this blog form component.
13:46:29
Y lo primero que tenemos que hacer es agarrar nuestro hook personalizado, que es el use blog.
And the first thing that we have to do is that we have to grab our custom hook, which is the use blog.
13:46:35
Está bien, ya lo encontramos en el contenido. Y lo que quiero hacer es desestructurar el add blog y también el update blog de donde, del use blog.
Okay, we already find that in the content. And what I want to do is that I want to just destructure the add blog and also the update blog from where from the use blog.
13:46:47
y ahora debajo de eso también vamos a definir nuestro título y
and now underneath there we are going to be also defining our title and
13:46:50
luego set title y eso va a ser igual a use state y para
then set title and that is going to be equal to the use state and for
13:46:54
el valor inicial vamos a desestructurar primero
the initial value we are going to be first of all destructuring
13:46:57
nuestro blog existente, sabes qué, déjame
our existing blog, you know what let me just
13:47:00
ir y agarrar el nombre de ellos, así que solo copiaré
go ahead and grab the name of them so I will just copy
13:47:03
el nombre de eso, ponerlo aquí y también voy a obtener esto
the name of that, put there right here and I am going to also get this
13:47:06
en el cierre y ponerlo aquí, así que ahora va a darnos muchos errores, así que voy a usar mi componente funcional de react y anotar
on close and put there right here, so now it is going to give us a lot of errors so I am going to use my react functional component and annotate
13:47:14
ahí con las propiedades del formulario de blog y ahora déjame
there with the blog form props and now let
13:47:17
crear sus tipos aquí mismo, así que no vamos a hacer nada loco, pero vamos a crear nuestra interfaz con el nombre de propiedades del formulario de blog, va a tomar el blog existente y tenemos que anotarlos con nuestro blog.
me just create their types right here so we're not going to be doing anything crazy but we're going to be creating our interface with the name of blog form props it's going to take the existing blog and we have to annotate them with our blog
13:47:28
que vamos a obtener de estos tipos y ahora también
which we're going to be getting from these types and now we also
13:47:32
tenemos que proporcionar el cierre y va a ser solo una función
have to provide the on close and it's going to be just a function
13:47:35
que solo devolverá el blanco que ya está hecho
which will just return the white that's already done
13:47:38
y ahora estamos anotando con éxito allí y ahora tenemos
and we're now successfully annotating there and now we
13:47:41
que usar el interior de nuestro componente, así que lo que voy a hacer es que voy
have to use the inside of our component so what i'm going to do is that I'm
13:47:44
a crear también un hilo para la descripción y
going to also create a thread for the description description and
13:47:47
luego establecer la descripción, va a ser igual a
then set description it's going to be equals to
13:47:50
el uso del hilo y aquí también olvidé el
the use thread and here I also forgot the
13:47:54
valor inicial para este, así que si tenemos el blog existente
initial value for this one so if we have the existing blog
13:47:57
y luego vamos a obtener una descripción de allí
and then we are going to be getting a description out of there
13:48:00
así que si ya lo tenemos, entonces úsalo, pero si no lo tienes, entonces vamos a establecerlo como una cadena vacía y ahora para esta descripción también vamos a proporcionar
so if we already have there so then use there but if you don't have there then we are going to be setting there to empty string and now for this description we are going to be also providing
13:48:09
el blog existente
the existing blog
13:48:12
y de este blog existente vamos a obtener una descripción
and from this existing blog we're going to be getting a description
13:48:15
y para este vamos a obtener un título allí
and for this one we are going to be getting a title there
13:48:19
vamos bien, así que si ya tienes la descripción existente, entonces
we go okay so if you already have the existing description then
13:48:22
úsalas, pero si no, entonces solo proporciona la vacía
use them but if you don't then just provide the empty
13:48:26
cadena aquí y ahora debajo de eso también vamos a crear un
string right here and now underneath there we are going to be also creating a
13:48:29
estado para la imagen y luego establecer la imagen y va a ser igual al uso del estado y vamos a estar usando los datos existentes e-x-i-s-t-e-n-t-e
state for the image and then set image and it's going to be equals to the use state and we are going to be using the existing data e-x-i-s-t-i-n-g
13:48:38
bloque existente, si tienes esto queremos obtener una imagen de
existing block if you have this we want to get an image out
13:48:41
allí, pero si no, solo queremos establecer eso como una cadena vacía
of there but if we don't so we just want to set that to empty string
13:48:44
ahora déjame proporcionar uno para el tiempo y luego establecer el tiempo, va a
now let me just provide one for the time and then set time it's
13:48:48
ser igual al uso del estado y vamos a obtener nuestros datos
going to be equals to the use state and we are going to be getting our data
13:48:51
de este bloque existente, si tenemos esos datos, entonces
from this existing block if we have that data then
13:48:54
usa esos datos, pero si no, entonces vamos a establecer
use that data but if we don't then we are going to be setting
13:48:57
eso como una cadena vacía, ahora vamos a usar un
there to empty string now we are going to be using a
13:49:00
efecto secundario, así que cada vez que nuestro componente se renderiza por primera vez, solo queremos llenar todo ese campo, voy a proporcionar mi
side effect so like whenever our component first renders so we just want to fill all of that field i'm going to be providing my
13:49:07
blog existente, así que cada vez que nuestro componente
existing blog okay so whenever our component
13:49:10
se renderiza por primera vez, tomará todos esos datos y llenará
first rendered so it's going to take all of that data it's going to fill
13:49:13
eso dentro de ese campo de entrada, así que solo voy a escribir, primero que nada, si
that inside that input field so i'm going to just write like first of all if
13:49:17
tenemos el blog existente, vamos, blog existente
we have the existing blog come on existing blog
13:49:20
así que en esta situación vamos a obtener el título establecido
so in this situation we're going to be getting the set title
13:49:23
y tenemos que proporcionar nuestros datos del blog existente
and we have to provide our existing blog data
13:49:26
para esto usaré algo como el aspecto existente, sabes que voy a
to this i'll use like existing look you know i'm going to
13:49:29
tener que copiar allí y voy a usar mi título y ahora
have to copy there and i'm going to use my title and now
13:49:33
vamos a hacer exactamente lo mismo para la descripción, así que
we are going to to be doing exactly the same thing for the description so
13:49:36
bloque existente punto descripción y también
existing block dot description and also
13:49:39
la imagen establecida cada vez que nuestro componente se renderiza
the set image whenever our component renders
13:49:42
así que también vamos a proporcionar la imagen y finalmente para el
so we are going to be also providing the image and finally for the
13:49:45
tiempo, así que solo escribiré como bloque existente punto tiempo
time okay so i'll just write like existing block dot time
13:49:48
y eso va a estar bien, así que dicho esto, ahora déjame volver y ahora entremos en esta interfaz, voy a quitar eso de aquí y proporcionar mi nombre de clase, así que para estos nombres de clase el fondo se establecerá completamente en blanco.
and that's going to be fine okay so that said now let me just go back and now let's get into this ui i'm going to remove that from here and provide my class name so for this class names the background will set to totally white.
13:49:59
El padding por todos lados se establecerá en 6. Redondeado grande y también el ancho se establecerá en 30 rem.
Padding for all around will be set to 6. Rounded large and also width will be set to 30 rem.
13:50:06
Y también el margen para el eje x se establecerá en automático.
And also margin for the x axis will be set to auto.
13:50:09
Y aquí tenemos que usar nuestro h3 con las clases de fuente, semi negrita y el texto se establecerá en extra grande.
And here we have to use our h3 with the classes of font, semi bold and text will be set to extra large.
13:50:15
Y el margen para la parte inferior se establecerá en 2. El texto se establecerá en un gris totalmente 800.
And the margin for the bottom will be set to 2. Text will be set to totally gray of 800.
13:50:21
Está bien, dentro de este, vamos a verificar si tenemos el existente
Okay, inside this one, we are going to be checking if we have the existing
13:50:24
bloques, así que luego diremos como editar bloque, pero
blocks so then we will say like edit block but
13:50:27
si no tenemos eso, entonces vamos a cambiar allí a agregar bloque
if we don't have that then we are going to be changing there to add block
13:50:31
está bien, así que ahora déjame guardar mi archivo y probar esto, así que
okay so now let me just save my file and test this out so
13:50:34
aquí puedes ver que tenemos como agregar nuevos bloques, así que si hago clic allí, eso
here you can see we have like add new blocks so if I click on there that's
13:50:37
nos dará como agregar bloque porque no tenemos ningún dato dentro
going to give us like add block because we don't have any data inside
13:50:40
ahí, así que por eso ahora estamos obteniendo como un bloque de agregar, así que
there so that's why we are now getting like add block so
13:50:43
eso es genial, ahora debajo de este h3 vamos a definir nuestros datos con la clase de espacio en el eje y de 4 y luego
that's cool now underneath this h3 we are going to be defining our data with the class of space on the y-axis of 4 and then
13:50:51
dentro de ahí vamos a definir nuestro campo de entrada con el tipo de texto
inside there we're going to be defining our input field with the type of text
13:50:54
y también el marcador de posición se establecerá en título y
and also the placeholder will be set to title and
13:50:58
aquí también vamos a proporcionar el valor y el valor vendrá
here we are going to be also providing the value and the value will be coming
13:51:02
de este estado, así que solo obtendré ese título y
from this state so i'll just get that title and
13:51:05
pondré eso justo aquí dentro de este título
put that right here inside this title
13:51:08
bien, y luego también vamos a proporcionar
okay and then we are going to be also providing
13:51:11
el evento on change cada vez que alguien escriba algo dentro
the on change event whenever somebody types something inside
13:51:15
de este campo de entrada, vamos a activar este set no time, sino set set title, ahí vamos y vamos a proporcionar ese valor que estamos obteniendo de este campo de entrada.
this input field we're going to be firing this set not time but set set title there we go and we're going to be providing that value which we are getting from this input field.
13:51:24
Ahora lo que voy a hacer es que solo voy a especificar estas clases y eso estará hecho.
Now what I'm going to do is that I'm going to just specify these classes and that's going to be done.
13:51:29
Ahora, si hago clic en eso, aquí puedes ver que ahora estamos obteniendo nuestro campo de entrada con el marcador de posición de título. Así que eso se ve genial.
Now if I click on that so here you can see we are now getting our input field with the placeholder of title. So that's looking great.
13:51:36
A continuación, tenemos que definir nuestra área de texto, así que usaré como área de texto y no vamos a proporcionar ningún ID ni nombres.
Next we have to define our text area so I'll use like text area and we're not going to be providing any IDs and names.
13:51:43
Voy a eliminar eso de aquí y para el marcador de posición diré
I'm going to remove that from here and for the placeholder I will
13:51:46
simplemente como descripción y no queremos
just say like description and we don't want to
13:51:49
cerrar eso por separado, queremos cerrarlo como una sola línea
close that separately we want to close there as a one-liner
13:51:52
y para el valor vamos a pasar nuestra descripción que hemos
and for the value we are going to be passing our description which we've
13:51:56
ya creado arriba y cuando alguien escriba
already created up above and when somebody types
13:51:59
algo dentro de esto, vamos a encontrar esta función y
something inside this we are going to be finding this function and
13:52:02
seleccionaremos set description a e.target.value
we will select set description to e.target.value
13:52:05
y también voy a colocar estas clases
and also i'm going to be placing these classes
13:52:08
para el estilo, así que solo verifiquemos esto si
for the styling so let's just check this out if
13:52:12
hago clic allí y esta va a ser mi área de texto ahora debajo
i click on there and this is going to be my text area now underneath
13:52:15
de esta área de texto, vamos a definir nuestro campo de entrada
this text area we're going to be defining our input field
13:52:18
una vez más y ahora lo que voy a hacer es que solo voy a proporcionar
once again and now what I'm going to do is that I'm going to just provide
13:52:21
mi URL de imagen de marcador de posición y también
my placeholder image URL and also
13:52:24
proporcionar el valor y el valor será ese valor de imagen
provide the value and the value will be that image value
13:52:27
y alguien escribe algo dentro de ahí, así que vamos
and somebody types something inside there so we're going
13:52:30
a estar ejecutando esta función que es una imagen establecida y proporcionar mi
to be firing this function which is a set image and provide my
13:52:33
evento punto objetivo punto valor dentro de ahí y también
event dot target dot value inside there and also
13:52:37
para las clases vamos a colocar estas clases justo aquí ahora
for the classes we're going to be placing these classes right here now
13:52:40
debajo de este campo de entrada vamos a definir o sabes que debajo incluso de este div vamos a crear una sección con la clase de flex y justificar
underneath this input field we're going to be defining or you know what underneath even this div we're going to be creating a section with the class of flex and justify
13:52:51
se establecerá en fin y el margen para la parte superior se establecerá en 6.
will be set to end and margin for the top will be set to 6.
13:52:55
el espacio en el eje x se establecerá en 4 y dentro de esto
space on the x axis will be set to 4 and inside this
13:52:58
sección vamos a crear nuestro botón y para esto
section we're going to be creating our button and for this
13:53:01
botón primero comprobarás si tenemos
button you will first of all check if we have
13:53:05
el bloque existente, entonces simplemente diremos como
the existing block then we will just say like
13:53:08
actualizar, pero si no tenemos el bloque existente, simplemente diremos
update but if we don't have the existing block we will just say
13:53:11
agregar, ahora para este botón vamos a adjuntar el
add now for this button we're going to be attaching the
13:53:14
propio controlador de eventos de clic que nos permite enviar nuestro formulario, así que vamos a
own click event handler which allows us to submit our form so we're going to
13:53:17
proporcionar como manejar el envío y también vamos a crear esto
be providing like handle submit and we're going to be also creating this
13:53:20
función en unos segundos, ahora déjame solo colocar el estilo y
function in a few seconds now let me just place the styling and
13:53:23
eso será todo para este botón, ahora debajo de este botón vamos
that's going to be it for this button now underneath this button we're
13:53:27
a definir un botón más con la clase de
going to be defining one more button with the class of
13:53:30
sabes que no vamos a proporcionar ninguna clase a eso, pero
you know what we're not going to providing any classes to that we are but
13:53:33
voy a copiar y colocar allí y cuando alguien haga clic
i'm going to just copy and place there and when somebody clicks
13:53:36
ahí vamos a estar ejecutando esta función de cerrar, está bien
on there we're going to to be firing this on close function okay
13:53:40
y va a decir como cancelar y ahora déjame solo escribir
and it's going to just say like cancel and now let me just type
13:53:43
eso un poco y eso estará bien ahora
that a bit and that's going to be fine now
13:53:46
tenemos que copiar allí y crear allí arriba, así que lo que
we have to copy there and create there up above so what
13:53:50
lo que voy a hacer es definir mi función de envío
i'm going to do is that i'm going to define my handle submit function and
13:53:53
dentro de esta función de envío, primero vamos a crear un blog
inside this handle submit first of all we're going to be creating a blog
13:53:56
y también voy a anotar allí con mi blog y aquí va a ser igual al id y el id será el blog existente.
and i'm going to also annotate there with my blog and here it's going to be equals to the id and the id will be the existing come on existing blog.
13:54:06
si ese es el caso, vamos a encontrar el blog existente.id
If that's the case, we are going to be finding the existing blog.id
13:54:10
pero si ese no es el caso, vamos a usar eso. ahora para ese nuevo segundo o para ese nuevo tiempo.
but if that's not the case, we are going to be using that.now for that new second or for that new time.
13:54:16
también vamos a poner la descripción del título
We are going to be also putting the title description
13:54:20
d-e-s-c-r-i-p-c-i-ó-n y también la imagen y el tiempo.
t-e-s-c-r-i-p-t-i-o-n and also the image and the time.
13:54:26
así que eso va a ser básicamente mi blog. Ahora tenemos que verificar eso.
So that's going to be basically my blog. Now we have to check that.
13:54:29
si ya tienes el blog existente, así que en esta situación, vamos a usar
If you already have the existing blog, so in this situation, we are going to be using
13:54:34
el blog de actualización y también vamos a proporcionar el blog
the update blog and we are going to be also providing the blog
13:54:37
dentro de allí como todos los datos existentes, pero si no tenemos
inside there like all of the existing data but if we don't have
13:54:40
los datos existentes, entonces vamos a crear un nuevo blog y
the existing data then we are going to be creating a new blog and
13:54:44
proporcionar esos datos recién creados que ya hemos creado
providing that newly created data which we've already created
13:54:47
y todos esos datos provienen de su estado apropiado, así que tú
and all of that data is coming from their appropriate state so you
13:54:50
sabes, déjame mostrarte allí este título proviene de este título
know let me just show you there this title is coming from this title
13:54:53
vamos, este título y luego la descripción, luego la imagen y también el tiempo y ahora estamos proporcionando allí dentro de este blog. Ahora para este blog vamos a proporcionar nuestro blog y también tenemos que cerrar allí usando la función de cierre.
come on this title and then description then image and also the time and we are now providing there inside this blog now for this blog we are going to be providing our blog and also we have to close there by using the on close function.
13:55:07
Está bien, eso fue mucha charla, así que ahora déjame probar esto.
Okay that was a lot of talking so now let me just test this out.
13:55:10
Así que lo que voy a hacer es que voy a hacer clic allí y ahora nos va a dar como el título, la descripción, la imagen y así sucesivamente.
So what I'm going to do is that I'm going to click on there and now it's going to give us like the title, description, image and so on and so forth.
13:55:16
Ahora voy a escribir como no sé. Oh Dios. Vlogs.
Now I'm going to just write like I don't know. Oh my god. Vlogs.
13:55:25
cosas de blog de Wikipedia 50 blogs, voy a elegir ese primero y necesito algún tipo de blog, así que voy a entrar en ese primero
Wikipedia blog stuff 50 blogs I'm going to choose that first one and I need some sort of a blog so I'm going to go into that first one
13:55:33
sí, iré a Reddit y copiaré algunas cosas de allí
yep I'll go to the reddit and copy some stuff from there
13:55:37
está bien, así que tres meses de lo que sea esto, así que
okay so three months of whatever this is so
13:55:41
voy a copiarlos y colocarlos allí y para la descripción solo voy a colocar esta primera porción y para la imagen solo copiaré la imagen de algún lugar, así que iré a unsplash.com
I'm going to copy them and place there and for the description I'm going to only place this first portion and for the image I'll just copy the image from somewhere so I'll just go to the unsplash.com
13:55:51
ir a unsplash y copiar algún tipo de imagen, así que
go to the unsplash and copy some sort of an image so
13:55:54
supongo que no, hay uno malo, soy yo
i guess no there's bad one i'm
13:55:57
voy a tener que elegir algún tipo de imagen gratuita como esta ahora déjame
gonna have to choose some sort of a free image like this one now let
13:56:00
hacer clic derecho allí y copiar la dirección de la imagen
me right click on there and copy the image address place
13:56:03
aquí y hacer clic en agregar, así que se va a agregar aquí pero
there here and click on the add so it's going to add the right here but
13:56:06
no podemos ver allí y la razón por la que no podemos ver allí es porque tenemos que crear nuestro componente de artículo para que podamos renderizar nuestros artículos dentro de allí y vamos a estar renderizando nuestros artículos
we cannot see there and the reason we cannot see there is because we have to create our article component so that we can render our articles inside there and we're going to be rendering our articles
13:56:18
aquí. Ahí vamos. Así que lo que voy a hacer es que voy a crear mi componente article list.tsx y solo pondré mi RAFC dentro de allí.
right here. There we go. So what I'm going to do is that I'm going to create my article list.tsx component and I'll just put my RAFC inside there.
13:56:28
Guardar mi archivo y renderizar ese componente de lista de artículos aquí. Lista de artículos y presionar enter.
Save my file and render that article list component right here. Article list and hit enter.
13:56:35
Así que se va a renderizar allí aquí. Sí, estamos obteniendo nuestra lista de artículos, lo que significa que estamos poniendo algún tipo de datos allí.
So it's going to render there right here. Yep we are getting our article list which means like we are putting some sort of data inside there.
13:56:43
También va a tomar una prop, que será el on edit. Y vamos a proporcionar el modelo abierto para editar aquí.
It's going to also take one prop, which will be the on edit. And we're going to be providing the open model for edit right here.
13:56:51
Ahora déjame entrar en ese componente de artículo y vamos a crear eso aquí.
Now let me go into that article component and let's just create that right here.
13:56:55
Lo primero que queremos hacer es que queremos obtener mis bloques de uso. Y queremos usar eso aquí.
The first thing that we want to do is that we want to grab my use blocks. And we want to use that right here.
13:57:02
Pero primero, tenemos que desestructurar los bloques y también el bloque de eliminar. Así que voy a guardar eso a continuación.
But first of all, we have to destructure the blocks and also the delete block. So I'm going to save that next.
13:57:08
También vamos a anotar este componente. Así que solo crearé una interfaz para allí con el nombre de props de lista de artículos.
We're going to be also annotating this component. So I'll just create an interface for there with the name of article list props.
13:57:19
Y dentro de allí, también vamos a devolver el on edit. Y esto va a ser una función que tomará un blog.
And inside there, we're going to be also returning the on edit. And this is going to be a function which will take a blog.
13:57:25
Y vamos a anotar allí con nuestro tipo de blogs. Y solo vamos a devolver el blanco de allí.
And we're going to be annotating there with our blogs type. And let's just return the white out of there.
13:57:31
Y voy a copiar allí y anotar mi componente usando react.fc para componente funcional.
And I'm going to copy there and annotate my component by using react.fc for functional component.
13:57:39
y anotar mi componente así que también va a tomar
and annotate my component like so it's going to also take
13:57:42
el on edit como una prop que es
the on edit as a prop that's
13:57:45
hecho ahora para esta interfaz de usuario lo que voy a hacer es que simplemente
done now for this ui what i'm going to do is that i'm going to just
13:57:48
quitar eso de aquí, voy a poner el nombre de clase de margen para
remove that from here i'm going to put the class name of margin for
13:57:51
la izquierda se establecerá en fireframes y dentro de este div
the left will be set to fireframes and inside this div
13:57:54
vamos a estar iterando sobre todos sus bloques y voy a poner un bloque como un perímetro y dentro de allí vamos a estar renderizando un componente más que será el componente de tarjeta de artículo
we are going to be iterating over through all of their blocks and i'm going to put a block as a perimeter and inside there we are going to be rendering one more component which will be article card component
13:58:05
y vamos a estar creando este componente de tarjeta de artículo en unos segundos.
and we're going to be creating this article card component in a few seconds.
13:58:08
Va a tomar la clave y vamos a proporcionar un blog.id como clave.
It's going to take the key and we're going to be providing a blog.id as a key.
13:58:13
También vamos a proporcionar un artículo y ese artículo será todo el blog.
We're going to be also providing an article and that article will be that entire blog.
13:58:18
También vamos a proporcionar el on delete para que podamos eliminarlo completamente si así lo deseamos.
We're going to be also providing the on delete so that we can totally delete there if we wanted to.
13:58:23
Así que en esta situación, vamos a encontrar esta función como eliminar blog.
So in this situation, we're going to be finding this function like delete blog.
13:58:28
Y aquí tenemos que especificar nuestro blog.id y también el on edit nos permite editar ese blog.
And here we have to specify our blog.id and also the on edit allows us to edit that blog.
13:58:34
Ahora déjame crear este componente de tarjeta de artículo. Así que solo crearé mi article card.tsx y dentro de ahí voy a usar mi RAFCE, guardar mi archivo y agarrar este componente aquí.
So we are going to be firing this function which allows us to edit our blog. So I'll use like onEdit and we have to specify our blog inside there.
13:58:42
Esto es guardar nuestro archivo y ahora déjame probar esto. Así que si hago clic allí, puedo escribir algún tipo de tontería así.
Now let me go ahead and create this article card component. So I'll just create my article card.tsx and inside there I'm going to be using my RAFCE, save my file and grab this component right here.
13:58:52
Y ahora si hago clic en el botón de agregar, nos dará una tarjeta de artículo, lo que significa que todo está funcionando como esperamos.
This is save our file and now let me test this out. So if I click on there, I can just write some sort of gibberish like so.
13:58:58
Ahora lo que quiero hacer es que primero quiero crear mi interfaz para todas esas propiedades.
And now if I click on the add button, so it's going to give us an article card, which means like everything is working the way we expand work.
13:59:06
Así que usaré como propiedades de tarjeta de artículo.
Now what I want to do is that I want to first of all create my interface for all of that props.
13:59:10
Así que usaré las propiedades de la tarjeta de artículo.
So I'll use like article card props.
13:59:15
Dentro de este primero, vamos a proporcionar nuestro artículo A-R-T-I-C-L-E y eso va a ser nuestros bloques completos.
Inside this one first of all we're going to be providing our article A-R-T-I-C-L-E and that's going to be our entire blocks.
13:59:22
También vamos a proporcionar la función de eliminar para que también podamos eliminarlo allí y para esto vamos a devolver la función vacía y en editar.
We're going to be also providing the on delete so we can also delete it there and for this one we're going to be returning the void function and on edit
13:59:29
también podrás editar nuestra tarjeta así que
you would be also able to edit our card so
13:59:33
simplemente pongamos la palabra dentro de ahí, está bien, así que lo que voy a
let's just put the word inside there okay so what I'm going
13:59:36
hacer es que voy a anotar allí con
to do is that I'm going to annotate there with
13:59:39
el componente funcional de react así y voy a
the react functional component like so and I'll
13:59:42
simplemente poner mi propiedad de tarjeta de artículo dentro de ahí y
just put my article card prop inside there and
13:59:45
de este vamos a desestructurar todas nuestras propiedades así que
from this one we are going to be destructuring all of our props so
13:59:48
pondré mi artículo, la función de eliminar y también la de editar así, está bien, así que eso es. Ahora para este trato, voy a proporcionar mucho estilo. Coloca el estilo y
I'll put my article the on delete and also the on edit like so okay so that's Now for this deal, I'm gonna provide a lot of styling. Place the styling and
14:00:00
esta etiqueta la voy a quitar y renderizar mi imagen.
this label i'm going to remove that and render my image
14:00:03
y para esta imagen simplemente diré como artículo punto
and for this image i'll just say like article dot
14:00:06
no este, sino a r t i c l e artículo.
not this one but a r t i c l e article
14:00:10
punto imagen y también tenemos que especificar algún tipo de alternativa
dot image and we also have to specify some sort of alternative
14:00:13
texto para eso, así que usaré como artículo punto título.
text for that so i'll use like article dot title
14:00:16
y también tenemos que especificar algún tipo de clases para esto. Ahora déjame volver, esto se establecerá en 36 36 así, la altura será de 6 a 24.
and we also have to specify some sort of classes for this now let me just go back this will be set to 36 36 like so height will be 6 to 24
14:00:26
y el objeto se establecerá para cubrir totalmente y ser totalmente redondeado.
and object will be set to totally cover and totally rounded
14:00:29
la sombra grande será media y eso es.
large shadow will be medium and that's
14:00:32
eso va a ser y aquí puedes ver que no estamos obteniendo ninguna imagen que
going to be it and here you can see we're not getting any image that's
14:00:35
porque estamos poniendo algún tipo de tontería a eso déjame refrescar
because we are putting some sort of a gibberish to that let me just refresh
14:00:39
ahí y agregar un nuevo blog y voy a copiar esta imagen de
there and add a new blog and i'm going to copy this image from
14:00:42
ahí y poner esa imagen y si hago clic y si presiono en
there and put that image and if i click and if i hit on
14:00:45
esto agregar ahora nos va a dar esa imagen justo aquí que
this add now it's going to give us that image right here which
14:00:48
es genial ahora debajo de eso también vamos a crear un div con la clase de margen para la izquierda que se establecerá en seis y flex se establecerá en uno
is cool now underneath that we're going to be also creating a div with the class of margin for the left will be set to six and flex will be set to one
14:00:55
flex y luego flex también se establecerá en columna y
flex and then flex will be also set to column and
14:00:58
h3 y simplemente vamos a ver nuestro texto de totalmente extra grande
h3 and let's just pour to our text of totally extra large
14:01:02
y la fuente se establecerá en semi, vamos semi negrita y el texto se establecerá en gris de 800 y el margen para la parte inferior se establecerá en 2 genial y también tenemos que renderizar nuestro artículo
and font will be set to semi come on semi bold and text will be set to gray of 800 and margin for the bottom will be set to 2 cool and we also have to render our article
14:01:14
punto título dentro de ahí así que ahora si guardo mi archivo y aquí puedes ver que ahora estamos obteniendo nuestro artículo
dot title inside there so now if i save my file and here you can see we're now getting our article
14:01:20
título que también se ve horrible porque
title which is also looking awful because
14:01:23
no especificamos nada dentro de ahí y simplemente tomemos
we did not specify nothing inside there and let's just take
14:01:26
cuidado del párrafo así que solo escribiré como artículo
care of the paragraph so i'll just write like article
14:01:29
punto maldita sea r-t-i-c-l-e
dot god damn it r-t-i-c-l-e
14:01:33
artículo punto descripción y proporcionar un estilo a esto así que
article dot description and provide a styling to this so i'll
14:01:36
solo usaré como texto de totalmente pequeño y el texto será
just use like text of totally small and text will
14:01:39
crear 700 y flex se establecerá en
be create 700 and flex will be set to
14:01:42
uno guarda mi archivo y sí, así es como se ve mi descripción debajo de este párrafo vamos a definir un div con la clase de flex
one save my file and yeah this is how my description looks like underneath this paragraph we're going to be defining word div with the class of flex
14:01:49
y los elementos se establecerán en centro justificar se establecerá
and items will be set to center justify will be set
14:01:52
entre el margen para la parte superior se establecerá en cuatro texto
to between margin for the top will be set to four text
14:01:55
se establecerá en gris de 600 y
will be set to gray of 600 and
14:01:59
dentro de este div vamos a crear nuestro span con una clase de texto pequeño
inside this div we're going to be creating our span with a class of text small
14:02:03
y dentro de este vamos a usar artículo
and inside this one we're going to be using article
14:02:06
punto tiempo guarda mi archivo y nosotros
dot time save my file and we
14:02:09
no podemos ver la hora no sé por qué déjame ir y ir a mi formulario de blog maldita sea ve a
cannot see the time i don't know why let me go ahead and go to my blog form god damn go to
14:02:18
el formulario de bloque, así que tenemos un título, luego tenemos una descripción, luego
the block form so we have a title then we have description then
14:02:21
tenemos la imagen, oh sí, tenemos
we have the image we oh yep we
14:02:26
olvidé incluir la hora, así que simplemente vamos a renderizar la hora
forgot to include the time so let's just render the time
14:02:29
también, así que voy a crear un input con un tipo de fecha y
as well so i'm going to create an input with a type of date and
14:02:32
el marcador de posición dirá hora y también proporcionará el valor que ya hemos especificado como una hora, o ¿es que incluso especificamos la hora o no? Olvidé, sí, lo hicimos, sí, totalmente ahí.
placeholder will say time and also provide the value which we've already specified as a time or did we even specify the time or not i forgot yep we did yeah we totally there.
14:02:44
Así que aquí lo que voy a hacer es
So here what I'm going to do is
14:02:48
que voy a proporcionar el onChangeEventHeadler y cuando alguien intente cambiar eso, vamos a activar esta función que tomará como event.target.value y también vamos a proporcionar un poco de clases allí.
that I'm going to provide the onChangeEventHeadler and when somebody tries to change that, we're going to be firing this function which will take like event.target.value and we're going to be also providing a bit of classes to there.
14:02:58
Así que simplemente voy a colocar estas clases y ahora si simplemente actualizo eso, aquí puedes ver que tenemos nuestro temporizador y escribir lo que quiera escribir.
So I'll just go ahead and place these classes and now if I just refresh that, here you can see we have our timer and write whatever I want to write.
14:03:07
Copia la imagen de ese lugar, colócala justo aquí y voy a establecer eso para hoy.
Copy the image of that place the right here and I'm going to set there to today.
14:03:11
Ahora, si añado eso y aquí puedes ver que también estamos obteniendo su hora ahora
Now if I add that and here you can see we are also getting their time now
14:03:14
déjame ir a mi tarjeta de artículo y debajo de esto
let me go to my article card and underneath this
14:03:18
span voy a crear otro div con la clase
span i'm going to be creating yet another div with the class
14:03:21
de flex y el espacio en el eje x se establecerá en tres y dentro de allí esto es renderizar o fa bookmark mark así
of flex and space on the x axis will be set to three and inside there this is render or fa bookmark mark like so
14:03:31
y voy a proporcionar una clase para ello, así que simplemente colocaré estas clases y ahora debajo
and i'm going to be providing a class to it so so i'll just place these classes and now underneath
14:03:36
de este marcador, también vamos a proporcionar el fa
this bookmark we're going to be also providing the fa
14:03:39
editar y también importar eso y clases de producto
edit and also import that and product classes
14:03:42
a este también, así que cuando alguien intente editar
to this one as well like so when somebody tried to edit
14:03:45
esto, vamos a activar esta función y proporcionar nuestra propia
this we're going to be firing this function and provide our own
14:03:49
edición dentro de allí y también simplemente vamos a renderizar nuestro final
edit inside there and also let's just render our final
14:03:52
icono que será fa trash y
icon which will be fa trash and
14:03:55
presiona enter y aquí tenemos que especificar el final
hit enter and here we have to specify the final
14:03:58
icono así y vamos a proporcionar el controlador de evento on click cuando alguien intente hacer clic allí, vamos a eliminar eso en su artículo específico y hemos terminado con ellos.
icon like so and we're going to be providing the on click event handler when somebody tried to click on there we're going to be removing that on their specific article and we are totally done with them.
14:04:10
Probemos esto. Así que si hago clic en este editar, está bien, eso no está funcionando. Si hago clic en el eliminar, eso está funcionando.
Let's just test this out. So if I click on this edit, okay, that's not working. If I click on the delete, that is working.
14:04:16
Así que, ¿qué pasa con ese editar? Déjame probar esto.
So what's up with that edit? Let me just test this out.
14:04:20
Así que simplemente proporcionaré algunos datos, ingresar allí y hacer clic en el editar. Ve a mi elemento de inspección.
So I'll just provide some data, enter there and click on the edit. Go to my inspect element.
14:04:27
Estamos obteniendo algún tipo de error. Blog no está definido. y eso proviene de un 23.
We're getting some sort of error. Blog is not defined. and that is coming from a 23.
14:04:33
déjame entrar en la aplicación
let me go into the app go into
14:04:36
el blog 23 no está definido
the 23 blog is not defined
14:04:40
¿qué quieres decir con eso? oh aquí tenemos que especificar eso
what do you mean by that oh here we have to specify that
14:04:43
blog así que solo escribiré un blog aquí ahora está definido así que
blog so i'll just write a blog in here now it is defined so
14:04:47
también vamos a anotar allí con el blog así ahora está definido así que déjame refrescar allí, agregar un blog aleatorio aquí,
we are going to be also annotating there with the blog like so now it is defined so now let me just refresh there, add a random blog here,
14:04:57
así, entra allí, y ahora si hago clic en editar va a
like so, enter there, and now if I click on the edit it's
14:05:01
darnos todos sus datos, está bien, eso está funcionando
going to give us all of their data okay that's working
14:05:04
si cambio eso a mi propio nombre como hosan webdev
if i change that to my own name like hosan webdev
14:05:07
y cambio esta descripción a hola
and change this description to hello
14:05:10
soy hosan webdev, un increíble youtuber y para la imagen voy a entrar en mi
i am hosan webdev amazing youtuber and for the image i'm going to go into my
14:05:21
github.com y
github.com and
14:05:24
buscar mi propia imagen que es hosan webdev, ir allí, copiar la imagen y colocarla aquí y ahora solo voy a actualizar allí a 14.
search for my own image which is hosan webdev go there copy the image and place there here and now i'm gonna just update there to 14.
14:05:36
haz clic en actualizar, está bien, la actualización girando es incorrecta
click on the update okay the update spinning is incorrect
14:05:39
bien, déjame arreglar eso, estoy
up okay let me just fix that i'm
14:05:42
yendo a la tarjeta y ¿dónde está mi actualización?
gonna go into the card and where is my update
14:05:45
¿dónde en el mundo está ese botón de actualización? voy a buscar
where in in the world is that update button i'm going to search
14:05:49
por updtl dtl
for updtl dtl
14:05:52
updte
updte
14:05:56
buscar eso y
updte search for that and
14:05:59
aquí tenemos que cambiar eso a actualizar, así que ahora
here we have to change that to update like so now
14:06:03
esto se ve mejor, está bien, así que así es como vamos
this is looking better okay so this is how we're
14:06:06
a agregar un blog de agua, así es como vamos a editar allí, como déjame solo editarlo con algún tipo de palabrería aleatoria y hacer clic en actualizar, así que también se actualizará allí
going to be adding water blog this is how we're going to be editing there like let me just edit it with some random uh gibberish and click on the update so it's going to also update there
14:06:16
y también puedo eliminarlo totalmente. Eso fue mucha charla y ese fue nuestro proyecto de blogs.
and I can also totally delete there. That was a lot of talking and that was our blogs project.
14:06:23
Así que ahora hagamos un conjunto de cuatro proyectos. Así que lo primero que quiero hacer es instalar ReactJS en nuestra máquina.
So now let's make a set of four or projects. So the first thing that I want to do is that I want to install ReactJS in our machine.
14:06:28
Así que voy a usar npm read o npm create read en la última versión.
So I'm going to be using like npm read or npm create read at latest.
14:06:32
Voy a usar el nombre de proyectos y voy a elegir ReactJS y Timescript.
I'm going to go with the name of like projects and I'm going to choose ReactJS and Timescript.
14:06:37
Así que ahora déjame ir a mi carpeta de proyectos y voy a instalar cada uno
So now let me go into my projects folder and I'm going to install every single
14:06:41
de los elementos allí, ahora que está hecho con éxito, voy a
thing inside there now then successfully done i'm
14:06:44
abrir eso en mi vs code así y primero
going to open that in my vs code like so and first of
14:06:48
todo tenemos que eliminar esta carpeta pública porque no la necesitamos, estamos
all we have to remove this public folder because we don't need that we're
14:06:51
también eliminando estos assets y ab.css y
going to be also removing these assets and ab.css and
14:06:54
index.css, pero tenemos que eliminar cada cosa
index.css but we have to remove every single thing
14:06:57
de allí y también eliminar cada cosa de la aplicación y simplemente proporcionar como rafc dentro de allí, ve al hombre y eso estará bien, así que ahora déjame instalar tailwind css en mi proyecto, así que voy a copiar allí
from there and also remove every single thing from the app and just provide like rafc inside there go to the man and that's going to be fine okay so now let me install 10-win css in my project so i'm going to copy there
14:07:09
abrir mi terminal y colocar este comando aquí, presionar
open my terminal and place this command here hit
14:07:12
enter para inicializar mi term y css y ahora estoy
enter to initialize my term and css and now i'm
14:07:15
a copiar este contenido, ir a mi tailwind
going to copy this content go to my tailwind
14:07:18
archivo de configuración, eliminar allí y reemplazarlo con este nuevo
config file remove there and replace it with this new one
14:07:22
bueno, así que eso está totalmente hecho y también tenemos que proporcionar estas
okay so that's totally done and we also have to provide these
14:07:25
directivas dentro de nuestro index.css, así que ahora déjame
directives inside our index.css so now let
14:07:28
adelante y proporcionar allí, guardar mi archivo y eso es
me go ahead and provide there save my file and that's
14:07:31
totalmente hecho, así que sabes qué, déjame solo comprobar esto, así que voy a usar npm run
totally done so you know what let me just check this out so i'm going to be using npm run
14:07:34
dev para ejecutar mi proyecto, así que aquí puedes ver que ahora estamos obteniendo una aplicación, pero voy a copiar este h1 e ir a mi app.ts una vez más y colocarlo justo aquí.
dev to run my project so here Here you can see we are now getting an app, but I'm going to copy this h1 and go to my app.ts one more time and place it right here.
14:07:44
Y ahora estamos obteniendo nuestro hello world con el estilo, lo que significa que todo está funcionando correctamente.
And we are now getting our hello world with the styling, which means like everything is now successfully working.
14:07:49
A continuación, voy a crear mi carpeta utils y dentro de allí voy a definir mi archivo data.ts.
Next, I'm going to create my utils folder and inside there I'm going to define my data.ts file.
14:07:55
Está bien, así que ahora voy a colocar muchos datos y puedes encontrar todos sus datos en mi repositorio de GitHub.
Okay, so now I'm going to place a lot of data and you can find all of their data in my GitHub repository.
14:07:59
Así que aquí puedes ver, primero que todo, tenemos nuestros datos y ahora los estamos exportando para que podamos usarlos en otro archivo.
So here you can see, first of all, we have our data and we are now exporting there so that we can use the in other file.
14:08:06
Está bien, así que tenemos un array, dentro de este array tenemos un objeto y dentro de este objeto tenemos un cliente, país, correo electrónico, proyecto, progreso, estado, fecha y también diferentes imágenes para cada uno de los clientes aquí.
okay so we have an array inside this array we have an object and inside this object we have a client country email project progress status date and also different images for each of the client right here
14:08:18
Está bien, así que sí, tenemos muchos datos y si estás interesado en todos
okay so yeah we have a lot of data and if you're interested in all
14:08:21
esos datos, puedes ir a mi repositorio de GitHub y
of that data you can totally go ahead and go to my ghab repository and
14:08:24
agarrar todos sus datos de allí, pero si quieres ponerlo como propio, puedes hacerlo tú mismo, está bien, así que eso está hecho, ahora déjame ir
grab all of their data from there but if you want to just put it like your own you can totally do that by yourself okay so that's done now let me just go
14:08:32
adelante y crear mi carpeta de componentes y dentro de allí
ahead and create my components folder and inside there
14:08:35
primero voy a definir mi dashboard.tsx
first of all i'm going to be defining my dashboard.tsx
14:08:38
y voy a usar mi raf, vamos, rafce
and i'm going to use my raf come on rafce
14:08:41
guardar mi archivo, ir a mi aplicación y registrarme allí, ¿verdad?
save my file go to my app and register there right
14:08:45
aquí, así que solo voy a eliminar eso y voy a reemplazarlo con dev y
here so i'll just remove that and i'm going to replace that with dev and
14:08:48
dentro de este dev, déjame renderizar mi componente de dashboard, está bien
inside this dev let me just render my dashboard component okay
14:08:51
así que solo guardemos nuestro archivo y aquí puedes ver que ahora estamos obteniendo nuestro dashboard
so let's just save our file and here you can see we are now getting our dashboard
14:08:54
que se ve increíble, a continuación déjame ir a este dashboard
which is looking amazing next let me just go to this dashboard
14:08:57
y lo primero que quiero hacer es que quiero hacer un
and the first thing that i want to do is that i want to just make a
14:09:01
poco de ui, así que solo escribiré como nombre de clase de flex
bit of ui so i'll just write like class name of flex
14:09:04
y también la altura se establecerá en pantalla y dentro de allí
and also the height will be set to screen and inside there
14:09:07
vamos a renderizar primero la barra lateral que vamos a
we are going to be rendering first of all the sidebar which we are going to be
14:09:10
crear en unos segundos y también vamos a proporcionar un div con
creating in a few seconds and we are going to be also providing a div with
14:09:13
la clase de flex uno y un fondo totalmente gris de
the class of flex one and background of totally gray of
14:09:16
900 y dentro de este vamos a
900 and inside this one we are going to
14:09:19
renderizar nuestra tabla de proyectos como la tabla principal en
be rendering our project table like the main table in
14:09:22
la que vamos a renderizar todo nuestro contenido, así que ahora eso está totalmente hecho, así que
which we are going to be rendering all of our content so now that's totally done so
14:09:26
voy a seguir adelante y trabajar con esta barra lateral, así que lo que estoy
i'm going to go ahead and work with this sidebar so what i'm
14:09:29
a hacer es que voy a crear mi sidebar.tsx
going to do is that i'm going to create my sidebar dot tsx
14:09:33
archivo aquí y solo usaré el rfc dentro de allí y voy a seguir adelante e ir a mi dashboard y eliminar esta barra lateral y reemplazarla con este componente de barra lateral real.
file right here and I'll just use the rfc inside there and I'm going to go ahead and go to my dashboard and remove this sidebar and replace it with this actual sidebar component.
14:09:43
Ahora déjame seguir adelante y simplemente estilizar esta barra lateral aquí, así que voy a eliminar eso y proporcionar mucho estilo a ello.
Now let me go ahead and just style this sidebar right here so I'm going to remove that and provide a lot of styling to it.
14:09:49
Así que primero vamos a proporcionar un ancho de 16 para ello y también vamos a proporcionar un borde y el color del borde será este color como 24 24 24.
So first of all we are going to be providing the width of 16 to it and we are going to be also providing a border and border color will be this color like 24 24 24.
14:09:58
Esto es para un poco de emparejamiento de 4 píxeles y también
This is for a bit of pairing of 4 pixel and also
14:10:01
flex flex se establecerá en columna y los elementos se establecerán
flex flex will be set to column and items will be set
14:10:05
para centrar y el espacio en el eje y se establecerá en agregar y eso es
to center and space on the y-axis will be set to add and that's
14:10:08
va a ser agregar y ahora dentro de este div vamos a definir primero
going to be add and now inside this div we're going to be defining first
14:10:11
todo nuestro texto de logo totalmente blanco así que
of all our text of totally white logo so
14:10:14
simplemente escribiré un logo aquí y ahora debajo de eso estoy
i'll just write a logo right here and now underneath that i'm
14:10:17
simplemente creando texto de totalmente vamos, texto de totalmente gris de 400 va a tomar este icono
going to just create like text of totally come on text of totally gray of 400 is going to take this icon
14:10:24
como un icono de carpeta o algo así, así que voy a colocar esto
like folder icon or something so i'm going to just place this
14:10:27
icono de carpeta y ahora déjame duplicar allí y cambiar el
folder icon and now let me just duplicate there and change the
14:10:30
icono a uno como una persona, básicamente aquí puedes especificar cualquier
icon to like a person like basically here you can just specify any
14:10:34
tipo de icono que prefieras, pero esto es solo una barra lateral y
kind of icon that you prefer but this is just a sidebar and
14:10:38
no vamos a proporcionar ninguna funcionalidad, así que por eso estoy proporcionando
we're not going to be providing any functionality to it so that's why i'm just providing
14:10:41
estos iconos, así que simplemente escribiré como configuraciones configuraciones o
these icons so i'll just write like settings settings or
14:10:44
engranaje, engranaje estaría bien, ahora déjame guardar allí y revisar esto, así que aquí puedes ver que ahora estamos obteniendo nuestra barra lateral y que se ve increíble, así que eso fue alrededor de cuatro o barra lateral y ahora entremos en la tabla principal.
gear gear would be fine now let me just save there and check this out so here you can see we are now getting our sidebar and which is looking amazing so that was at about four or sidebar and now let's get into the main table.
14:10:56
Ahora déjame encargarme de esta tabla temporalmente. Así que voy a ir y ocultar allí e iterar sobre todos mis datos.
Now let me take care of this table temporarily. So I'm going to go ahead and hide there and iterate over through all of my data.
14:11:03
Así que para el tbody voy a cortar cada cosa de allí y voy a usar un proyecto que es ese estado en el que estamos definiendo todos sus datos.
So for the tbody I'm going to just like cut every single thing from there and I'm going to be using a project which is that state in which we are defining all of their data.
14:11:13
Está bien, así que vamos a iterar sobre ellos usando nuestro método de mapa. Así que usaré como mapa.
Okay so we are going to be iterating over through them by using our map method. So I'll use like map.
14:11:18
Va a tomar el proyecto y también va a tomar
It's going to take the project and also it's going to take
14:11:21
el índice como un perímetro y ahora dentro de allí
the index as a perimeter and now inside there we
14:11:24
vamos a definir todos nuestros datos, como tenemos nuestro tr y
are going to be defining all of our data like we have our tr and
14:11:28
también nuestros tds, voy a seleccionar estos proyectos y simplemente
also our tds i'm going to select these projects and just
14:11:31
seleccionar todos ellos presionando ctrl d y eliminar
select all of them by hitting ctrl d and remove
14:11:34
esto de allí, así que ahora nos va a dar su proyecto y
this s out of there so now it's going to give us their project and
14:11:37
ahora dentro de su proyecto tenemos nuestra imagen, cliente, país, correo electrónico y proyecto y ahora si guardo mi archivo y pruebo esto, así que aquí puedes ver que ahora estamos obteniendo todos
now inside their project we have our image client country email and project and now if i save my file and test this out so here you can see we are now getting all of
14:11:45
nuestros datos que se ven geniales, pero tenemos que encargarnos de esto
our data which is looking cool but we have to take care of this
14:11:48
imagen y también esta interfaz de usuario, así que ahora hagamos eso, así que
image and also this ui so now let's just do that so
14:11:51
lo que voy a hacer es que voy a encargarme de la imagen, primero proporcionaré
what i'm going to do is that i'm going to take care of the image first of all i'll provide
14:11:54
un nombre de clase que se establecerá en tres rim y
a class name of which will be set to three rim and
14:11:57
también vamos a proporcionar una altura que
also we're going to be providing a height which
14:12:00
también se establecerá en tres rim, está bien, y para
will be also set to three rims okay and for
14:12:04
el objeto que se establecerá para cubrir totalmente para que nuestra imagen contenga todos los datos, está bien, así que también vamos a proporcionar un archivo semirredondeado y ahora estamos obteniendo esta increíble interfaz de usuario que se ve genial.
the object which will be set to totally cover so that our image will contain all of the data okay so we're going to be also providing a rounded full semi file and now we are getting this amazing UI which is looking cool.
14:12:16
Y sabes qué, debajo de este TD también vamos a proporcionar nuestros proyectos.
And you know what, underneath this TD we are going to be also providing our projects.
14:12:20
Así que hoy vamos a crear nuestro TD con la clase de emparejamiento para el eje x que se establecerá en 4 y también emparejamiento para el eje y que se establecerá en 2.
So for today we are going to be creating our TD with the class of pairing for the x axis will be set to 4 and also pairing for the y axis will be set to 2.
14:12:28
Dentro de ahí vamos a definir nuestro ancho con la clase de 24
Inside there we are going to be defining our width with the class of 24
14:12:33
y la altura se establecerá en totalmente 2. Solo la altura se establecerá en 2.
and height will be set to totally 2. Just height will be set to 2.
14:12:39
y también vamos a proporcionar un color de fondo de totalmente gris de 700 y totalmente redondeado.
and we're going to be also providing a background color of totally gray of 700 and totally rounded.
14:12:45
Así que ahora dentro de este div, ¿qué quieres hacer? Solo queremos crear
So now inside this div, what do you want to do? We just want to create
14:12:48
nuestro div una vez más y tomará la altura de 2 y también vamos a proporcionar el fondo de totalmente verde 500 y totalmente redondeado.
our div once again and it's going to take the height of 2 and we're going to be also providing the background of totally green 500 and totally rounded.
14:12:57
Así que ahora si voy y guardo mi archivo y reviso esto, aquí puedes ver que ahora estamos obteniendo nuestro progreso que se ve genial.
So now if I go ahead and save my file and check this out so here you can see we're now getting our progress which is looking cool.
14:13:04
Ahora debajo de este TD, vamos a definir otro TD con la clase de emparejamiento para el eje x de 4 y
Now underneath this TD, we're going to be defining yet another TD with the class of pairing for the x axis of 4 and
14:13:12
vamos, emparejamiento para el eje x de 4 y emparejamiento para el eje y de 2
come on, pairing for the x axis of 4 and pairing for the y axis of 2
14:13:15
el ancho se establecerá en este radio arbitrario, así que solo voy a
width will be set to this arbitrary radius so I'll just
14:13:18
escribir un ancho y eso será igual a 10
write a width and that's going to be equals to 10
14:13:21
rems dentro de este td vamos a definir nuestro span
rems inside this td we're going to be defining our span
14:13:24
y aquí solo tenemos que escribir nuestro project.status y ahora estamos obteniendo todos esos estados de proyecto, también voy a renderizar mi fecha, así que solo usaré como td
and here we just have to write our project.status and now we are getting like all of that project statuses I'm going to also render my date so I'll just use like td
14:13:34
emparejamiento para el eje x de 4, emparejamiento para el eje y de 2 y renderizar mi project.date
pairing for the x axis of 4, pairing for the y axis of 2 and render my project.date
14:13:40
project.date así y estamos obteniendo la fecha y finalmente tenemos que encargarnos de ese botón de acción y eso será todo.
project.date like so and we are getting the date and finally we have to take care of that action button and that's going to be it.
14:13:48
Está bien, así que lo que voy a hacer es definir mi td con la clase de emparejamiento para el eje x de 4 y emparejamiento para el eje y de 2.
Okay so what I'm going to do is that I'm going to define my td with the class of pairing for the x axis of 4 and pairing for the y axis of 2.
14:13:54
Dentro de ahí vamos a definir nuestro div con la clase de relativo, así que usaré como relativo, voy a
Inside there we are going to be defining our div with the class of relative so I'll use like relative I'm going to
14:14:01
proporcionar mi ícono de tres puntos, así que usaré como bs3 dots
provide my three dots icon so i'll use like bs3 dots
14:14:05
los vamos a renderizar, también voy a proporcionar el nombre de la clase
we're going to be rendering them i'm going to also provide the class name
14:14:08
de cursor y ahora estamos obteniendo estos tres puntos
of cursor and we are now getting these three dots
14:14:11
lo cual no está haciendo nada, pero ya hemos terminado totalmente con esta interfaz
which is not doing anything but we are now totally done with this ui
14:14:14
sé que esto no se ve tan bien, pero nos ocuparemos del resto de estas cosas, ahora déjame quitar la barra lateral
i know this is not looking that great ui but we will
14:14:17
desde aquí vamos a definir nuestro componente de tabla justo aquí, así que solo usaré el rfc dentro de ahí, vamos
take care of the rest of these stuff now let me just remove the sidebar
14:14:20
registrado allí dentro de nuestro panel, así que en lugar de proporcionar esto
from here and we're going to be defining our table component right here so i'll just use the rfc inside there let's
14:14:27
comentario, así que voy a escribir como, uh, tabla
just registered there inside our dashboard so instead of providing this
14:14:30
componente así, así que si guardo mi archivo
comment so i'm going to write like uh table
14:14:33
aquí puedes ver que ahora estamos obteniendo nuestra tabla, pero
component like so so if i save my file
14:14:37
no se ve tan bien, así que vamos a
here you can see we are now getting our table but which
14:14:40
ocuparnos del estilo, ahora voy a continuar y proporcionar
is not looking that great so we are going to be
14:14:43
un poco de estado y también el estilo para ello, así que solo quitaré lo primero que quiero hacer es que quiero agarrar mis datos, como todos estos datos que hemos especificado aquí.
taking care of the styling right now i'm going to go ahead and provide
14:14:46
Está bien, así que vamos a agarrarlos dentro de nuestros componentes de tabla.
a bit of stat and also the styling to it so i'll just remove there the first thing that i want to do is that i want to grab my data like this entire data that we've specified right here.
14:14:55
Así que usaré como importar datos de donde queremos obtener esos datos.
Okay, so we're going to be grabbing them inside our table components.
14:14:59
Vamos a continuar e ir a la carpeta de utilidades y queremos seleccionar estos datos. Eso ya está hecho.
So I'll use like import data from where we want to get that data from.
14:15:05
Ahora tenemos que almacenar los datos dentro de nuestro estado. Así que voy a usar como use state para eso y aquí queremos proporcionar todos sus datos.
Let's just go ahead and go to the utils folder and we want to select this data. That's already done.
14:15:12
Está bien, y aquí solo tenemos que desestructurar los proyectos y también establecer proyectos
Now we have to store the data inside our state. So I'm going to be using like use state for that and here we want to provide all of their data.
14:15:18
de donde de este usado, ahora déjame volver porque
Okay, and here we just have to destructure the projects and also set projects
14:15:23
de donde de este anuncio usado y ahora déjame volver porque nosotros
from where from this used ad now let me go back because we
14:15:26
vamos a estar escribiendo mucho jsx y muchas clases, así que voy a seleccionar esta y las clases de producto para allí, así que el emparejamiento para todo alrededor se establecerá en cuatro, el ancho se establecerá en 93
are going to be writing a lot of jsx and a lot of classes so i'm going to just uh select this one and product classes to there so pairing for all around will be set to four width will be set to 93
14:15:38
93 por ciento y también el margen para el
93 percent and also margin for the
14:15:41
izquierda se establecerá en cinco rams, está bien y ahora dentro
left will be set to five rams okay and now inside
14:15:44
de este div vamos a estar primero definiendo o ordenando y luego vamos a definir nuestra tabla principal y después de eso vamos a definir nuestra paginación.
this div we're going to be first of all defining or sorting and then we're going to be defining our main table and after that we're going to be defining our pagination.
14:15:54
Así que comencemos con este ordenamiento. Lo que voy a hacer es crear un div con una clase de flex y también los elementos se centrarán totalmente y el margen para la parte inferior se establecerá en 5.
So let's start from this sorting. So what I'm going to do is that I'm going to create a div with a class of flex and also the items will be set to totally center and margin for the bottom will be set to 5.
14:16:04
Dentro de allí vamos a crear nuestro botón con una clase de borde y el borde se establecerá en gris de 700.
Inside there we're going to be creating our button with a class of border and border will be set to gray of 700.
14:16:12
Esto se disparó sobre 700 y también vamos a proporcionar un flex y los elementos se centrarán
This is fired over 700 and we're going to be also providing a flex and items will be set to center
14:16:19
justificar, justificar se establecerá en el centro y el texto será
justify justify will be set to center and text will
14:16:22
se establecerá un relleno totalmente amplio por todas partes
be set to totally wide padding for all around will be
14:16:25
se establecerá en dos y redondeado y dentro de ahí
set to two and rounded and inside there
14:16:28
vamos a renderizar nuestro ícono que será de tipo bi
we are going to be rendering our icon which will be bi sort
14:16:31
y eso va a venir del ícono de react así que tenemos que
and that's going to be coming from the react icon so we have to
14:16:34
también instalar esto, voy a usar npm i y luego react
also install this i'm going to be using npm i and then react
14:16:38
íconos, ahora están listos así que voy a usar el npm
icons now they're successfully done so i'm going to use the npm
14:16:41
ejecutar dev para iniciar mi servidor y ahora tenemos que obtener este ícono de esos íconos de react, está bien, así y también voy a proporcionar el nombre de clase de margen para la derecha que se establecerá en 0.3 rem.
run dev to start my server and now we have to grab this icon from that react icons okay like so and I'm going to also provide the class name of margin for the right will be set to 0.3 rem.
14:16:53
Está bien, ahora déjame guardar y también vamos a proporcionar un tipo como etiqueta para ello y ahora déjame renderizar mi contorno de ai hacia abajo.
Okay now let me just save my and we're going to be also providing a sort as a label to it and now let me also render my ai outline ai outline down.
14:17:02
También tenemos que obtener este ícono y voy a proporcionar un nombre de clase de margen para la izquierda que ahora se establecerá en 2.
We also have to get this icon and I'm going to provide a class name of margin for the left will be now set to 2.
14:17:07
Déjame quitar este espacio vacío de aquí y así es como se ve mi ícono justo aquí.
Let me remove this empty space from here and this is how my icon looks like right here.
14:17:12
Por supuesto, no estamos proporcionando ninguna funcionalidad, pero esto es solo para la interfaz de usuario. Ahora déjame encargarme de esta tabla principal.
Of course we're not providing any functionality to it but this is just for the UI. Now let me go ahead and take care of this main table.
14:17:19
Así que lo que voy a hacer es que voy a crear mi tabla con una clase de
So what I'm going to do is that I'm going to create my table with a class of
14:17:22
ancho mínimo totalmente completo y también la tabla se establecerá en automático por todas partes y vamos a proporcionar alrededor de ella y también el borde de 700 el texto se establecerá totalmente ancho.
minimum width of totally full and also the table will be set to auto like all around and we're going to be providing around it and also border ray of 700 text will be set to totally wide.
14:17:35
Dentro de ahí vamos a definir nuestro T head no thread sino T head así y luego definamos nuestro TR
Inside there we're going to be defining our T head not thread but T head like so and then let's just define our TR
14:17:42
y dentro de cada uno de estos tr vamos a definir nuestro th con
and inside each of these tr we are going to be defining our th with
14:17:45
la clase de emparejamiento para el eje x de 5 y emparejamiento para
the class of pairing for the x-axis of 5 and pairing for
14:17:48
el eje y de 3 y el texto se establecerá a la izquierda y
the y-axis of 3 and text will be set to left and
14:17:52
vamos a poner una imagen justo aquí para el primer nivel y voy a duplicar eso
let's just put an image right here for the first level and I'm going to duplicate that
14:17:55
como muchas veces, está bien, voy a quitar esta imagen y reemplazarla con nombre y también reemplazar esta con país ery por c ou
like a lot of time okay I'm going to remove this image and replace that with name and also replace this one with country ery by c ou
14:18:03
y prueba, ahí vamos y correo electrónico, luego tenemos un nombre de proyecto, también tenemos nuestro progreso de tarea
and try there we go and email then we have a project name we also have our task progress
14:18:17
estado, fecha y finalmente tenemos
status date and finally we have
14:18:20
nuestras acciones, así que voy a eliminar la última semi-archivo
our actions okay so i'm going to remove the last one semi-file
14:18:24
y así es como se ve justo aquí, así que eso será todo para el encabezado básico, ahora también vamos a proporcionar una filtración para este, pero nos encargaremos de eso en unos segundos.
and this is how it looks like right here so that's going to be it for the basic header now we are going to be also providing a filtration for this one but we are going to be taking care of that in a few seconds.
14:18:34
Está bien, así que lo que voy a hacer es que debajo de este T head también vamos a definir nuestro T body.
Okay so what I'm going to do is that underneath this T head we're going to be also defining our T body.
14:18:40
Así que nos permitirá darnos todo ese cuerpo. Así que voy a escribir como
So it's going to allow us to give us all of that body. So I'm going to write like
14:18:43
Cuerpo T y dentro de este cuerpo T vamos a estar
T body and inside this T body we're going to be
14:18:46
usando nuestro TR y eso va a tener el borde y también
using our TR and that's going to have the border and also
14:18:49
el borde se establecerá en una tasa total de 700 así y dentro de este TR vamos a estar definiendo nuestro TD con el nombre de clase de emparejamiento para el eje x de 4 y emparejamiento para el eje y de 2.
border will be set to total rate of 700 like so and inside this TR we're going to be defining our TD with the class name of pairing for the x-axis of 4 and pairing for the y-axis of 2.
14:19:00
También voy a renderizar mi imagen, pero sabes qué, sí, solo voy a renderizar algún tipo de imagen aquí y esa imagen tendrá el valor de proyecto y luego imagen
I'm going to also render my image but you know what yeah I'm going to just render some sort of an image right here and that image will have the value of project and then image
14:19:12
IMAGEN y también vamos a proporcionar nuestra alternativa
IMAGE and we are going to be also providing our alternative
14:19:15
texto así que usaré como proyecto punto cliente
text so I'll use like project dot client
14:19:18
así que ahora podrías estar preguntándote de dónde viene esta imagen
so now you might be wondering like where in the world is this image coming
14:19:21
y de dónde viene este cliente así que si mantengo ctrl
from and where in the world is this client coming from so if I hold ctrl
14:19:24
y hago clic en este proyecto, así que nos llevará a este estado
and click on this project so it's going to bring us to this state
14:19:27
y ahora si mantengo ctrl y hago clic en estos datos, así que va a
and now if i hold ctrl and click on this data so it's going
14:19:30
llevarnos a estos datos, está bien, así que ahora estamos obteniendo esta imagen
to bring us to this data okay so we are now grabbing this image
14:19:34
y también este nombre del cliente y
and also this name of the client and
14:19:37
ahora estamos poniendo eso dentro de este
we are now putting that inside this
14:19:40
imagen aquí así que nos dará la imagen de esa persona específica
image right here so it's going to give us the image of that specific person
14:19:43
también nos dará el cliente aquí, no va a
it's going to also gives us the client right here it's not going
14:19:46
darnos ningún dato porque no estamos iterando sobre nuestro cliente, así que por eso o ya para ser precisos, no un cliente, pero sabes qué, solo voy a completar la interfaz de usuario y luego nos ocuparemos de la funcionalidad.
to give us any data because we are not iterating over through our client so that's why or or already to be precise not a client but you know what i'm going to just complete the ui and then we will take care of the functionality.
14:19:57
Así que debajo de este TD, vamos a estar definiendo aún
So underneath this TD, we're going to be defining yet
14:20:00
con la clase de emparejamiento para el eje x de 4 y el emparejamiento para el eje y se establecerá en 2.
with the class of pairing for the x axis of 4 and pairing for the y axis will be set to 2.
14:20:06
Y aquí tenemos que definir nuestro proyecto.cliente como un nombre. Y solo voy a duplicar eso unas cuantas veces.
And here we have to define our project.client as a name. And I'm going to just duplicate that a few times.
14:20:12
Sé que estamos obteniendo muchos errores, pero esto es solo un error de TypeScript. Así que ahora déjame definir un país y también el correo electrónico.
I know we are getting a lot of errors, but this is just a TypeScript error. So now let me just define a country and also the email.
14:20:19
Y finalmente tenemos que escribir el proyecto aquí así.
And finally we have to just write the project right here like so.
14:20:23
Ahora si envío mi archivo y reviso esto, aún no estamos obteniendo ningún dato porque no estamos iterando sobre nada.
Now if I send my file and check this out, still we are not getting any data because we are not iterating over through nothing.
14:20:30
Así que sabes qué? Me encargaré del resto de la interfaz de usuario en unos segundos porque no puedes ver nada.
So you know what? I'm going to take care of the rest of the UI in a few seconds because you are not able to see anything.
14:20:36
Pero sí, me encargaré de eso en unos segundos. Así que sabes qué? Solo voy a ocultar todo este cuerpo principal.
But yeah, I'm going to take care of that in a few seconds. So you know what? I'm going to just hide this entire main body.
14:20:41
Y también nos ocuparemos de la paginación. Así que déjame crear una interfaz de usuario para esta paginación aquí.
And we're going to be also taking care of the pagination. So let me just create a UI for this pagination right here.
14:20:47
Así que voy a crear un div con la clase de flex. Y la justificación se establecerá en fin.
So I'm going to create a div with the class of flex. And justify will be set to end.
14:20:52
Y también el margen para la parte superior se establecerá en 4.
And also pairing for the top, not pairing but margin for the top will be set to 4.
14:20:56
Y dentro de ahí vamos a definir nuestro botón con la clase de margen para el eje x que será 4 y el margen para el eje y se establecerá en 2.
and inside there we're going to be defining our button with the class of pairing for the x axis will be 4 and pairing for the y axis will be set to 2.
14:21:03
El color de fondo se establecerá en gris 700 y también vamos a proporcionar el texto en blanco total, totalmente redondeado y el margen derecho se establecerá en 2 y deshabilitado.
Background color will be set to gray of 700 and we're going to be also providing the text of totally white to it, totally rounded and margin for the right will be set to 2 and disabled.
14:21:14
D-I-S-A-B-L-E-D se establecerá en opacidad cuando esté deshabilitado, así que vamos a cambiar la opacidad a 50.
D-I-S-A-B-L-E-D will be set to opacity when it is disabled so we're going to be changing the opacity to 50.
14:21:22
Ahí vamos. Bien, así que ahora dentro de este botón, ¿qué quieres hacer? Solo queremos escribir un anterior. P-R-E-V-I-O-U-S. Ahí vamos.
There we go. Okay so now inside this button what do you want to do? We just want to write a previous. P-R-E-V-I-O-U-S. There we go.
14:21:29
Y sí, eso estará bien. Así que ahora debajo de este botón, sabes, déjame volver para que ustedes puedan ver todo un poco mejor.
And yeah, that's going to be fine. So now underneath this button, you know, let me just go back so you guys can see everything a bit better.
14:21:36
Y también vamos a crear un span con la clase de margen para el eje x que se establecerá en 4.
And we are going to be also creating a span with the class of pairing for the x-axis will be set to 4.
14:21:41
Y el margen para el eje y se establecerá en 2. El texto se establecerá en blanco total. Y dentro de ahí, escribamos en nuestra página.
And pairing for the y-axis will be set to 2. Text will be set to totally white. And inside there, let's just write to our page.
14:21:47
Está bien, así que básicamente nos dará como página 1 de 2 o página 2 de 3 o algo así.
Okay, so it's going to basically gives us like page 1 out of 2 or page 2 out of 3 or something like that.
14:21:54
Así que en este caso, solo voy a proporcionar como página uno de cuatro, estaría bien. Vamos a comprobar esto.
So in this case, I'm going to only provide like page one of four would be fine. Let's just check this out.
14:22:01
Así que aquí puedes ver que ahora estamos obteniendo nuestro botón anterior. Y también estamos obteniendo, esto no debería ser un proyecto, debería ser una página.
So here you can see we are now getting our previous button. And we are also getting, this shouldn't be a project, it should be a page.
14:22:08
Está bien, así que sí, ahora estamos obteniendo una página uno de cuatro. Ahora déjame copiar todo este botón.
Okay, so yeah, we are now getting a page one of four. Now let me just copy this entire button.
14:22:13
Y déjame colocar eso justo aquí. En lugar de proporcionar un anterior, voy a cambiar eso a siguiente.
And let me just place that right here. Instead of providing a previous, I'm going to change that to next.
14:22:19
Envía mi archivo y ahora estamos obteniendo este botón siguiente, que se ve genial. Así que ahora déjame encargarme de estos menús desplegables.
Send my file and now we are getting this next button, which is looking cool. So now let me take care of these drop down menus.
14:22:25
Así que solo voy a definir un estado con el nombre de menú desplegable visible
So I'll just define a state with the name of drop down visible
14:22:28
y luego establecer menú desplegable visible o sabes lo que dije menú desplegable V I S I B L E.
and then set drop down visible or you know what I said drop down V I S I B L E.
14:22:37
Esto puede ser igual al usuario y el valor inicial se establecerá en falso. F A L S E. Ahí vamos.
This can be equals to the user and initial value will be set to false. F A L S E. There we go.
14:22:43
Ahora déjame ir a mi interfaz de usuario, que es la clasificación. Así que voy a ir allí.
Now let me go ahead and go to my UI, which is the sorting. So I'm going to go ahead and go there.
14:22:48
y cuando alguien haga clic en este botón, ¿qué quieres hacer? Solo queremos
and when somebody clicks on this button so what do you want to do we just want
14:22:51
disparar esta función, así que escribamos como un controlador de evento on click y
to fire this function so let's just write like on click event handler and
14:22:55
queremos disparar esta función que solo establecerá el menú desplegable en
we want to fire this function which will just set the drop down menu to
14:22:58
no falso, así que solo usaré como menú desplegable
not false okay so i'll just use like drop down menu
14:23:01
así que si nuestro menú desplegable está establecido en verdadero
like so so so if our drop down menu is set to true
14:23:04
esto lo hará falso, así que si nuestro menú desplegable está establecido en falso, lo hará verdadero, lo que significa que si está oculto, se mostrará y si no está oculto, simplemente se ocultará.
this will make it false so if our drop down menu is set to false it's going to make it true so which means like if it is hidden it's going to unhide there And if it's not hidden, so it's going to just hide there.
14:23:16
Está bien, así que ahora eso es todo lo que has hecho. A continuación, tenemos que mostrar nuestro contenido basado en nuestro estado verdadero o falso.
Okay, so now that's all you're done. Next, we have to show our content based on our true or false state.
14:23:21
Así que lo que voy a hacer es que aquí vamos a definir si nuestro menú desplegable es visible,
So what I'm going to do is that here, we're going to be defining like if our drop down menu is visible,
14:23:27
entonces vamos a mostrar esta interfaz de usuario. Pero si nuestro menú desplegable está configurado como falso, entonces no vamos a mostrar nada en absoluto.
then we're going to be showing this UI. But if our drop down menu is set to false, then we're not going to be showing anything at all.
14:23:35
Está bien, así que solo crearé un div con una clase de absoluto. Y también la parte superior se establecerá en totalmente llena.
Okay, so I'll just create a div with a class of absolute. And also top will be set to totally full.
14:23:40
y el lado izquierdo, vamos, el lado izquierdo se establecerá en totalmente
and the left side come on the left side will be set to totally
14:23:43
cero margen para la parte superior, vamos, margen para el
zero margin for the top come on margin for the
14:23:46
la parte superior se establecerá en dos y el fondo
top will be set to two and background
14:23:49
se establecerá en totalmente gris de 800 y el borde
will be set to totally gray of 800 and border
14:23:52
borde gris de 700 totalmente
border gray of 700 totally
14:23:56
redondeado y la sombra se establecerá en grande
rounded and shadow will be set to large
14:23:59
y dentro de esto vamos a definir nuestro botón y aquí solo vamos a escribir un nombre, voy a duplicar, oh, ya sabes, vamos a duplicar allí en unos segundos, pero también voy a proporcionar un poco de cláusulas para ello.
and inside this we're going to be defining our button and here we're going to be just writing a name i'm going to duplicate oh you know we're going to be duplicating there in a few seconds but i'm going also provide a bit of clauses to it.
14:24:11
Así que como bloque y el emparejamiento para el eje x se establecerá en cuatro. El emparejamiento para el eje y se establecerá en dos. El texto se establecerá en totalmente blanco.
So like block and pairing for the x axis will be set to four. Pairing for the y axis will be set to two. Text will be set to totally white.
14:24:17
El ancho se establecerá en totalmente lleno. Y cuando alguien pase el mouse por allí, vamos a cambiar el color de fondo a 700 de totalmente gris.
Width will be set to totally full. And when somebody hover over there, we're going to be changing the background color to 700 of totally gray.
14:24:25
Y también cuando alguien haga clic en este botón, vamos a encontrar esta función que será manejar el clic de opción de orden.
And also when somebody clicks on this button, we're going to be finding this function which will be handle sort option click.
14:24:34
Y aquí también vamos a proporcionar un cliente allí. Vamos a crear esta función en unos segundos, pero ahora déjame guardar mi archivo.
And here we're going to be also providing a client to there. We are going to be creating this function in a few seconds, but now let me just save my file.
14:24:41
Y también voy a tener que duplicar este una pocas veces.
And also I'm going to have to duplicate this one a few times.
14:24:43
Así que solo voy a duplicar el de país y una vez más para la fecha.
So I'm going to just duplicate the one for the country and one more time for the date.
14:24:48
Voy a cambiar los valores de ellos. En lugar de proporcionar un clic, debería haber proporcionado como cliente, no clic. Está bien.
I'm going to change the values of them. Instead of providing a click, I should have to provide like client, not click. Okay.
14:24:56
Y aquí también tenemos que especificar el país y también el país aquí.
And here we also have to specify the country and also country here.
14:24:59
Cambia este a fecha y esta etiqueta a fecha también.
Change this one to date and this label to date as well.
14:25:04
Así que nos va a dar un error, obviamente, porque tenemos que crear esta función. Así que voy a ir y subir y crear esta función.
So it's going to give us an error obviously because we have to create this function. So I'm going to go ahead and go to the top and create this function.
14:25:11
Así que lo que voy a hacer es que solo voy a escribir como const manejar clic de opción.
So what I'm going to do is that I'm going to just write like const handle option click.
14:25:16
Va a tomar una clave y esa clave será una cadena. Y dentro de esta función, vamos a definir nuestro conjunto de menú desplegable visible.
It's going to take a key and that key will be a string. And inside this function, we're going to be defining our set dropdown visible.
14:25:23
Y tenemos que establecer allí como falso. También tenemos que hacer muchas más cosas dentro de allí. Pero sabes qué, vamos a revisar esto.
And we have to set there to false. We also have to do a lot more things inside there. But you know what? Let's just check this out.
14:25:29
Así que si hago clic allí, no estamos obteniendo nada. Así que sabes qué, déjame encargarme de los proyectos de orden.
So if I click on there, we are not getting anything. So you know what? Let me just take care of the set sort projects.
14:25:35
Así que vamos a estar usando proyectos de tipo sort. Y aquí tenemos que definir nuestra clave.
So we're going to be using like sort projects. And here we have to define our key.
14:25:40
y ahora déjame crear los proyectos de ordenación arriba aquí. La primera cosa que quiero hacer es que quiero escribir como proyecto de ordenación.
and now let me just create the sort projects up above right here. The first thing that I want to do is that I want to just write like sort project.
14:25:47
Va a tomar una clave y esa clave será del tipo cadena y aquí lo que voy a hacer es que primero voy a hacer un clon de todos sus proyectos aquí.
It's going to take a key and that key will be the type of string and here what I'm going to do is that first of all I'm going to just make a clone of all of their projects right here.
14:25:56
No este, sino este para hacer un clon de todos sus proyectos.
Not this one but this one to make a clone of all of their projects.
14:25:59
Así que básicamente lo que vamos a hacer es que vamos a usar este operador de propagación.
So basically what we are going to be doing is that we're going to be using this spread operator.
14:26:04
Así que voy a usar como tres puntos y clonar todos los proyectos aquí y también
So I'm going to use like dot dot dot and clone all of the projects right here and we also
14:26:08
tenemos que almacenar en algún tipo de variable así que usaré como let sorted
have to store in some sort of a variable so i'll use like let sorted
14:26:12
proyectos y eso va a ser igual a este clon
projects and that's going to be equals to this clone
14:26:15
de estos datos ahora fuera de ellos también
of this data now outside from them we also
14:26:18
tenemos que definir un estado más para la configuración de ordenación así que escribiré
have to define one more state for the sort configuration so i'll
14:26:21
como configuración de ordenación y también tenemos que escribir como establecer configuración de ordenación que va a ser igual a use state y el valor inicial se establecerá en ahora
just write like sort config and also we have to write like set sort config that's going to be equals to the use state and the initial value will be set to now
14:26:30
pero también voy a anotar allí con este objeto y este objeto tendrá la clave y la clave
but i'm going to also annotate there with this object and this object will have the key and key
14:26:35
se establecerá en cadena y también vamos a proporcionar una dirección
will be set to string and we are going to be also providing a direction
14:26:38
así que usaré como dirección y la dirección se establecerá en cadena
so i'll use like direction and direction will be set to string
14:26:41
de lo contrario, si ese no es el caso, solo vamos a proporcionar
otherwise if that's not the case we are going to be only providing
14:26:44
un ahora que esto está aquí como inicialmente el
a now which this is right here like initially the
14:26:47
valor se establece ahora en ahora y ahora tenemos que usar esta configuración de ordenación
value is now set to now and now we have to use this sort configuration
14:26:51
dentro de esta función así que ya hicimos
inside this function so we already made
14:26:54
una copia de estos proyectos la siguiente cosa que tenemos que hacer es que tenemos
a copy of this projects the next thing that we have to do is that we have
14:26:57
que proporcionar nuestras verificaciones voy a proporcionar una verificación aquí así que si o configuración de ordenación como si tenemos algún tipo de configuración de ordenación en esta situación vamos a definir otra verificación.
to provide our checks i'm going to provide a check right here so if or sort config like if we have some sort of a sort config in this situation we are going to be defining yet another check.
14:27:07
Así que si la configuración de ordenación.clave es triple igual a la clave que ahora estamos tomando como un perímetro.
So if we are sort configuration.key is triple equals to the key which we are now taking as a perimeter.
14:27:14
Así que si esa sort.clave es igual a esa clave. Así que en esta situación vamos a proporcionar la sort.config.dirección que se establecerá en ascendente.
So if that sort.key is equal to that key. So in this situation we are going to be providing the sort.config.direction that's going to be set to ascending.
14:27:24
A-S-C-E-N-D-I-N-G así. Y voy a tener que usar el operador de igualdad triple aquí.
A-S-C-E-N-D-I-N-G like so. And I'm going to have to use triple equality operator right here.
14:27:30
Si esta expresión es verdadera, así que en esta situación vamos a estar ordenando
If this expression is true, so in this situation we are going to be sorting
14:27:34
nuestro ítem usando como proyectos de ordenación que es
our item by using like sort projects which is
14:27:37
va a ser el clon de nuestros proyectos y luego vamos a usar el javascript
going to be the clone of our projects and then we are going to be using the javascript
14:27:40
método de ordenación allí aquí toma dos parámetros como a
sort method on there here it takes two parameters like a
14:27:44
coma b y qué quieres hacer con eso solo queremos
comma b and what do you want to do with that we just
14:27:47
disparar una función y aquí voy a hacer un poco de magia y
want to fire a function and here i'm going to be doing a bit of magic and
14:27:50
luego voy a explicar esa magia así que usaré como a y clave y también si eso es mayor que b y punto b no punto clave sino solo una clave así que en esta situación vamos a devolver menos uno.
then i'm going to explain that magic so i'll use like a and key and also if that is greater than b and dot b not dot key but just a key so in this situation we we are going to be returning minus one.
14:28:02
Pero si ese no es el caso, vamos a devolver solo uno. Así que ahora déjame explicar qué significa esta línea en el mundo.
But if that's not the case, we are going to be returning only one. So now let me explain like what in the world does this line even mean?
14:28:08
Ya sabes que esto va a ser el clon de nuestro proyecto. Y luego podemos usar este método de ordenación allí porque esto es un arreglo.
You already know like this is going to be the clone of our project. And then we can use this sort method on there because this is array.
14:28:14
Dentro del arreglo tenemos muchos objetos lo que significa que podemos usar el método de ordenación allí.
Inside the array we have a lot of objects which means like we can use the sort method on there.
14:28:18
Esta es una función de flecha que toma dos parámetros como A y B que representan dos elementos dentro del arreglo del proyecto a comparar.
This is an arrow function that takes two parameters like A and B which represent two elements inside the project's array to be compared.
14:28:26
Como primero va a comparar, ya sabes lo que te estoy mostrando allí. Primero va a comparar este elemento con este otro como el segundo.
Like it will first of all compare, you know what I'm just showing you there. It's going to first of all compare this element with this another one like the second one.
14:28:34
Así que esto es lo que va a pasar en el primer paso. Y ahora déjame explicar esta línea de código.
So this is what's going to happen for the first step. And now let me explain this line of code.
14:28:38
Así que esta es la expresión que compara los valores de A y B en la propiedad de clave, que ya hemos especificado aquí.
So this is the expression that compare the values of A and B at the property of key, which we've already specified right here.
14:28:45
Así que si la clave A es mayor que la clave B, entonces la función devolverá 1, lo que significa que A debería compararse con B en el orden ordenado.
So if the A key is greater than the B key, then the function will return 1, which means like A should compare with B in the sorted order.
14:28:55
así que si la clave a no es mayor que la clave b por ejemplo
so if the a key is not greater than the b key for example
14:28:58
como si es a menor o igual a o algo así
like if it is a less than or equal to or something like that it
14:29:01
devolverá uno significando que b debería venir antes que a
will return one meaning the b should come before a
14:29:04
ok así que espero que tenga sentido pero si no
okay so i hope it makes sense but if it didn't
14:29:07
así que puedes simplemente hacer clic en buscar en google o algo así vamos a
so you can just click google search or something like that we're going to
14:29:11
también usar nuestra configuración de ordenación y aquí tenemos que definir nuestra clave primero y también tenemos que darle la dirección así que solo escribiré como dirección vamos qué demonios d-i-r-e-c-t-i-o-n
be also using our set sort config and here we have to define our key first of all and also we have to give it the direction so i'll just write like direction come on what the hell d-i-r-e-c-t-i-o-n
14:29:22
y la dirección se establecerá en descendente. D-E-S-C-E-N-D-I-N-G así.
and the direction will be set to descending. D-E-S-C-E-N-D-I-N-G like so.
14:29:28
Así que eso va a ser todo para el primer caso. ¿Y qué pasa con el siguiente caso como para la clase else?
So that's going to be it for the first case. And what about the next case like for the else class?
14:29:32
Como si ese no es el caso, entonces vamos
Like if that is not the case, then we're
14:29:35
a saltar a esta clase else y para esta clase else, vamos
going to be jumping into this else class and for this else class, we're
14:29:39
a copiar y colocar ambos códigos y aquí solo tenemos que cambiar ese menos uno a uno y también tenemos que proporcionar un menos para este segundo aquí.
going to be copying and placing both of these code and here we only have to change that minus one to one and also we have to provide a minus for this second one right here.
14:29:49
Como básicamente solo estamos invirtiendo nuestra expresión. Eso es todo. y también tenemos que cambiar este de descendente a ascendente
Like basically we're just reverting our expression. That's it. and we also have to change this one from descending to ascending
14:29:56
A, A, S, C, N, D, I, N, G así y finalmente
A, A, S, C, N, D, I, N, G like so and finally
14:29:59
tenemos que llevar eso a nuestros proyectos que vamos a estar usando como
we have to push that to our projects we are going to be using like
14:30:02
proyectos establecidos y tenemos que llevar nuestros proyectos ordenados en
set projects and we have to push our sorted projects in
14:30:05
ahí está bien, así debería ser un ordenado
there okay like so it should be a sorted
14:30:08
está bien, así que voy a copiar ahí y colocarlo justo aquí y
okay so i'm going to copy there and place it right here and
14:30:11
ahora que el error ha desaparecido con éxito, déjame refrescar ahí y verificar
now that error is successfully gone let me just refresh there and check
14:30:14
la interfaz de usuario, así que si hago clic ahí no sé por qué no estamos obteniendo el menú desplegable, así que déjame encargarme de eso y olvidé
out the ui so if i click on there i don't know why we are not getting the drop down menu so let me just take care of there and i forgot
14:30:20
incluir el div relativo justo aquí, así que solo voy a crear un div con la clase de relativo y voy a cortar ese div y tenemos que cerrar eso justo aquí.
to include the relative div right here so I'll just create a div with the class of relative and I'm going to cut that div and we have to close that right here.
14:30:30
Así que ahora si guardo mi archivo y ahora si hago clic en este menú desplegable, nos va a dar ese nombre, país y div.
So now if I save my file and now if I click on this drop down menu so it's going to give us that name, country and div.
14:30:35
Así que si hago clic en el nombre, va a ordenar mis datos, pero no puedo ver esos datos ordenados.
So if I click on the name it's going to sort my data but I cannot see that sorted data.
14:30:40
Lo veremos en unos segundos, pero también tenemos que encargarnos de los filtros.
We will see that in a few seconds but we also have to take care of the filters.
14:30:44
Así que lo que voy a hacer es que voy a definir mis filtros justo aquí debajo de este div. Vamos a estar definiendo nuestros filtros.
So what I'm going to do is that I'm going to define my filters right here underneath this div We are going to be defining our filters.
14:30:50
Así que solo lo crearé con una clase de relativo. Y también el margen para la izquierda se establecerá en 4. Esto se establecerá completamente lleno.
So I will just create it with a class of like relative. And also margin for the left will be set to 4. This will be set to totally full.
14:30:57
Y dentro de ahí vamos a estar definiendo una vez más nuestro botón. Con una clase de borde y el borde se establecerá completamente gris de 700.
And inside there we are going to be once again defining our button. With a class of border and border will be set to totally grey of 700.
14:31:05
Y también vamos a estar proporcionando una clase flex para ello. Y los elementos se establecerán en el centro. Justificar también se establecerá en el centro.
And also we are going to be providing a flex class to it. And items will be set to center. Justify will be also set to center.
14:31:12
Y el texto se establecerá completamente ancho. El emparejamiento para todo alrededor se establecerá en 2 y totalmente redondeado.
And text will be set to totally wide. pairing for all around will be set to 2 and totally rounded.
14:31:18
Dentro de este botón vamos a estar definiendo lo que MDs ordena como el ícono, así que solo vamos a agarrar eso y también voy a proporcionar un nombre de clase de margen para la derecha y eso será igual a 0.3 rems.
Inside this button we're going to be defining what MDs sort as the icon so let's just grab there and also I'm going to provide a class name of margin for the right and that's going to be equal to 0.3 rems.
14:31:29
Fuera de ahí, solo voy a refinar mis filtros y también proporcionar mi contorno de IA y ahí vamos.
Outside from there I'll just refine my filters and also provide my AI outline and down there we go.
14:31:36
Proporcionar un nombre de clase de margen para la izquierda se establecerá en 2, así que va a
Provide a class name of margin for the left will be set to 2 so it's going to
14:31:40
darnos ese botón justo aquí y esto no es algo que
gives us that button right here and this is not something that
14:31:43
queremos, así que tenemos que cortar este div y tenemos
we want so we have to cut this div and we have
14:31:46
que poner eso dentro de ese div y ahora déjame probar esto
to put that inside that div and now let me test this
14:31:49
así que aquí puedes ver que ahora estamos obteniendo nuestros filtros y también nuestro
out so here you can see we're now getting our filters and also our
14:31:52
fuente, así que ahora déjame también encargarme de este menú desplegable aquí, así que
source so now let me also take care of this drop down menu here so
14:31:55
lo que voy a hacer es que voy a definir mi menú desplegable y cuando alguien haga clic en este botón, vamos a estar disparando esta función, está bien, así que esta función tendrá como establecer
what i'm going to do is that i'm going to just define my drop down menu and when somebody clicks on this button so we're going to be firing this function okay so this function will have like set
14:32:06
los filtros vienen en conjunto, no
filters come on set filters not
14:32:09
filtro visible así que vamos a definir
filter visible like so so we are going to be defining
14:32:12
este filtro visible y también establecer no filtro visible, ¿verdad?
this filter visible and also set not filter visible right
14:32:16
aquí como un comienzo, así que ahora debajo de eso voy a simplemente
here as a start so now underneath that i'm going to just
14:32:19
crear mi filtro visible y también establecer
create my filter visible and also set
14:32:22
filtro visible así que eso va a ser igual al uso inicial y el valor inicial se establecerá en falso y esto debería ser establecer filtros visibles
filter visible like so that's going to be equals to the use start and the initial value will be set to false and this should be set filters visible
14:32:33
Ahora déjame guardar mi archivo y continuar con el resto de estas cosas.
Now let me just save my file and go ahead and take care of the rest of this stuff.
14:32:38
Así que ahora nuestro filtro aparecerá en la interfaz de usuario, pero también tenemos que crear nuestra interfaz de usuario para verlo allí.
So now our filter will show up over UI but we also have to create our UI to see there.
14:32:43
Así que para ver nuestra interfaz de usuario, primero que nada vamos a renderizar nuestra interfaz de usuario totalmente de manera condicional. Así que solo usaré como filtro visible.
So to see our UI, first of all we are going to be rendering our UI totally conditionally. So I'll just use like filter visible.
14:32:51
Si ese es el caso, vamos a estar renderizando esta interfaz de usuario.
If that is the case, we are going to be rendering this UI.
14:32:54
Pero si ese no es el caso, lo que significa que si esto no está establecido en verdadero, no vamos a mostrar nada.
But if that's not the case, which means like if this is not set to true, so we are not going to be showing nothing.
14:33:00
Si es verdadero, vamos a estar creando un div con la clase de absoluto.
If it is true, we are going to be creating a div with the class of absolute.
14:33:04
La parte superior se establecerá en 4 y la izquierda se establecerá en 0. También voy a proporcionar el margen para la parte superior que se establecerá en 2.
Top will be set to 4 and left will be set to 0. I am also going to provide the margin for the top will be set to 2.
14:33:11
El color de fondo se establecerá en 800 así. El borde y también el borde se establecerán totalmente en gris de 700.
Background color will be set to 800 like so. Border and also border will be set to totally gray of 700.
14:33:20
Voy a proporcionar el borde redondeado. La sombra se establecerá en totalmente grande y el relleno para el eje y será
I am going to provide the rounded border. Shadow will be set to totally large and padding for the y axis will be
14:33:27
y el relleno mod por todas partes se establecerá en 4. Dentro de eso vamos a estar creando nuestro div con la clase de margen para la parte inferior que se establecerá en 2.
and the mod padding all around will be set to 4. Inside there we are going to be creating our div with the class of margin for the bottom will be set to 2.
14:33:34
Y la etiqueta será así, sabes que no vamos a proporcionar ningún HTML para, pero voy a proporcionar algún tipo de nombre de clase para ello.
And label will be just like, you know we are not going to provide any HTML for, but I am going to provide some sort of a class name to it.
14:33:41
Así que el bloque y el texto se establecerán totalmente en blanco.
So block and text will be set to totally white.
14:33:44
Aquí tenemos que definir nuestro filtro por y luego el nombre así.
Here we have to define our filter by and then name like so.
14:33:49
Así que ahora debajo de eso vamos a estar creando nuestro campo de entrada con el tipo de texto y también el nombre se establecerá en nombre.
So now underneath there we are going to be creating our input field with the type of text and also the name will be set to name.
14:33:56
y no vamos a proporcionar ninguna ID hoy. Así que para el valor, el valor vendrá de filters.name
and we are not going to be providing any ID today. So for the value, the value will be coming from the filters.name
14:34:03
para filtros y luego el punto nombre y también vamos a proporcionar el onChangeEventHandler
for filters and then the dot name and we are also going to be providing the onChangeEventHandler
14:34:10
así que sabes que vamos a encargarnos de todas esas cosas en unos segundos, pero solo queremos ver la interfaz de usuario.
so you know what we are going to be taking care of all of that stuff in a few seconds but we only want to see the UI.
14:34:15
Así que voy a proporcionar un nombre de clase y el color de fondo se establecerá totalmente en 900 y el texto se establecerá totalmente en blanco
So I am going to provide a class name and background color will be set to totally 900 and text will be set to totally white
14:34:22
y voy a poner el redondeado, el relleno para el eje y o el relleno por todas partes se establecerá en 2 y el ancho se establecerá en 4.
and I'm going to put the rounded, pairing for the y axis or pairing for all around will be set to 2 and width will be set to 4.
14:34:31
Ahora, si guardo mi archivo y reviso esto, si hago clic allí, no estamos obteniendo nada.
Now if I save my file and check this out, so if I click on there, we are not getting anything.
14:34:36
No sé por qué y no está funcionando porque tenemos que cortar este código y tenemos que ponerlo debajo de este botón aquí.
I don't know why and it is not working because we have to cut this code and we have to put that underneath this button right here.
14:34:43
Así que ahora, si pongo eso aquí, ahora estamos obteniendo nuestro filtro por nombre y podemos simplemente poner nuestro filtro como algún tipo de nombre aquí.
So now if I put that here and now we are getting our filter by name and we can just put our filter like some sort of a name right here.
14:34:49
Ahora puedo hacer clic en esto y se va a mostrar. Y ahora, si hago clic allí una vez más, se va a ocultar.
Now I can click on this and it's going to unhide there. And now if I click on there once again, it's going to hide there.
14:34:56
O al revés, acabo de decirlo mal. Ahora
Or the other way around, I just said there wrong. Now
14:35:00
debajo de este div, ¿qué tenemos que hacer? Tenemos que definir otro div más, así que supongo que tendré que copiar y colocar este, así que simplemente lo copiaré.
underneath this div what do we have to do we have to define yet another div so I guess I'm gonna have to copy and place this one so I'm going to just copy therefore
14:35:10
el filtro por país, filtro por correo electrónico
the filter by country filter by email filter
14:35:13
por proyecto y filtro por estado, está bien, así que ahora déjame cambiar este video, así que tenemos como filtros, voy a quitar eso de aquí, tenemos un filtro por nombre.
by project and filter by status okay so now let me just change this video so we have like filters I'm going to just remove that from here we have a filter by name
14:35:23
También tenemos un filtro por correo electrónico o, ya sabes, déjame cambiar eso a filtro por país.
We also have a filter by email or you know what let me just change that to filter by country.
14:35:28
El nombre se establecerá en país y también tenemos un filtro por correo electrónico.
Name will be set to country and also we have a filter by email.
14:35:32
Así que escribiré como correo electrónico y el nombre se establecerá en correo electrónico así.
So I'll write like email and the name will be set to email like so.
14:35:38
Voy a hacer el E mayúscula filtro por proyecto.
I'm going to make the uppercase E filter by project.
14:35:41
Así que solo usaré como proyecto y también proporcionaré un proyecto aquí para el nombre.
So I'll just use like project and also provide a project right here for the name.
14:35:46
Está bien, entonces tenemos un estado, así que solo cambiaré eso a estado.
Okay then we have a status so I'll just change that to status.
14:35:51
y finalmente también tenemos que cambiar este nombre a estado
and finally we also have to change this name to status
14:35:54
aquí ahora déjame guardar mi archivo y revisar esto, así que
right here now let me just save my file and check this out so
14:35:57
tenemos un filtro por nombre, por país, correo electrónico, proyecto y
we have a filter by name by country email project and
14:36:00
estado, así que se ve genial, ahora déjame continuar y
status so which is looking cool now let me go ahead and
14:36:03
ocuparme de la filtración, así que voy a ir a la parte superior y primero
take care of the filtration so i'm going to go to the top and first
14:36:06
de todo, voy a definir mi estado de filtración aquí
of all i'm going to define my filtration state right here
14:36:09
así que voy a crear filtros o sí, los filtros estarán bien, luego tenemos un conjunto de filtros que será igual a la utilización
so i'm going to just create a filters or yeah filters will be fine then we have a set filters that's going to be equals to the use
14:36:17
y el valor inicial se establecerá en este objeto, el objeto tendrá
and the initial value will be set to this object object will
14:36:20