Aprenda React.js mediante la creación de proyectos: cree una aplicación de recordatorio de cumpleaños

Cuando está aprendiendo una nueva habilidad, los videos tutoriales solo pueden llevarlo hasta cierto punto. Mucha gente está de acuerdo en que ensuciarse las manos construyendo un proyecto es el camino a seguir.

Entonces, en esta serie de artículos prácticos, crearemos no una o dos, sino cinco pequeñas aplicaciones React.

Estas aplicaciones variarán de pequeñas a medianas y requerirán que las construya usted mismo. Como si realmente codificara la aplicación, pasara los casos de prueba y se asegurara de aprender cada habilidad.

¿Listo para empezar?

¿Cómo funcionará esto?

Este artículo está muy inspirado en el propio video de freeCodeCamp aquí. Pero en lugar de simplemente ver el video, tendrá que completar los proyectos con sus propias manos.

A lo largo del curso de esta serie de mini blogs, creará cinco proyectos pequeños. Y para cada proyecto, hay algunas reglas básicas:

  1. Tienes que codificar ciertos (o todos) aspectos de una característica.
  2. Tienes que pasar las pruebas dadas para los desafíos.
  3. Puede buscar ayuda externa. Pero recomendaría pasar algo de tiempo con la interfaz y las instrucciones primero. Esto se debe a que la interfaz está diseñada en función de cómo probablemente pasará su tiempo como desarrollador en herramientas basadas en desarrolladores.

Solo una nota: codedamn genera una instancia de servidor para cada usuario, por lo que para poder usar el aula debe registrarse / iniciar sesión.

Si solo desea verificar el código y trabajar en el proyecto por su cuenta, no en el aula, puede verlo en GitHub. He vinculado a GitHub en cada sección a continuación para que pueda saltar a la parte relevante del código.

Así que comencemos con el primer proyecto. Si recibo buenos comentarios, continuaré con las redacciones y los proyectos.

Cómo crear una aplicación de recordatorio de cumpleaños (proyecto n. ° 1)

Como este es nuestro primer proyecto, mantendré la complejidad muy baja. En este proyecto, utilizaremos React para generar una lista de elementos de datos, es decir, los cumpleaños de algunas personas.

Estos datos se procesarán a partir de una fuente de datos estática y deberían ayudarlo a comprender cómo importar y usar / borrar datos dentro de un estado. Trabajaremos dentro de un aula que he creado con mi proyecto Codedamn. Puedes comenzar este salón de clases aquí.

Recomiendo encarecidamente completar esta y otras aulas tanto como pueda usted mismo. Puede (y debe) utilizar esta publicación de blog como guía.

Esto es lo que aprenderá en esta clase:

  1. Cómo se ve un proyecto básico de React
  2. Cómo cargar datos desde un archivo JS estático
  3. Cómo usar useState para almacenar datos
  4. Cómo borrar la variable de estado y ver eso reflejado en la interfaz de usuario

Lab 1 - Introducción al proyecto

Aquí está el enlace a este laboratorio.

Este primer desafío le presenta el proyecto y su estructura. Dedique un tiempo a localizar todas las partes relevantes en este, y una vez que haya terminado, simplemente presione "Ejecutar pruebas" para aprobar este desafío. Nada lujoso aquí :)

Laboratorio 2: Cómo crear el contenedor de la vista de cumpleaños

Aquí está el enlace a este laboratorio de práctica.

También puede encontrar los archivos de configuración del laboratorio en GitHub aquí.

Ahora que ha visto cómo se organizan la estructura del proyecto y los archivos, es hora de crear algunas vistas estáticas.

Recuerde que siempre puede crear contenedores de datos estáticos primero y luego completarlos con datos dinámicos más adelante.

Este es un enfoque muy limpio para construir componentes dinámicos, ya que le permite preparar el componente antes de llenarlo dinámicamente con datos.

En este laboratorio, debe completar los siguientes desafíos:

  • Dentro de su archivo App.jsx, cree la siguiente jerarquía HTML:
main > section.container > h3 + List
  • Sugerencia: la abreviatura anterior significa que su estructura debe verse como la siguiente:

  • Su h3debe contener el texto:
0 birthdays today
  • Su componente debe ser el List.jsxcomponente que se importa en la parte superior.

Para aprobar todas las pruebas, asegúrese de hacer lo siguiente:

  • Un elemento 'h3' debe estar presente en su archivo App.jsx
  • Tu etiqueta "h3" debe contener "0 cumpleaños hoy" (sin comillas)
  • Su componente 'Lista' debe ser renderizado

Aquí está la solución a este desafío:

import React, { useState } from 'react' import data from './data' import List from './List' function App() { // Edit your return statement here to match the instructions return (   

0 birthdays today

) } export default App

Laboratorio 3: Cómo completar datos de listas estáticas

Here's the link to this lab.

You can also find the setup files of the lab on GitHub here.

We have the basic UI available to us. Let's now populate the static data from the data.js file.

This file has already been opened for you on the right side of the editor. Check out this file and see how the JSON data looks.

In this lab, you have to do the following things:

  • Inside your App.jsx file, you should now replace 0 Birthdays Today with Birthdays Today. Therefore, initially, it should show 5 Birthdays Today. Remember, the comes from the number of elements inside your data variable imported at the top.
  • Hint: You can use data.length
  • Pass the imported data variable as a prop to the List component. This prop should be called people
  • Hint:
  • In the List component, use this passed data to render just the names of the people for now. You can map over these people and display their names.

Here are 3 tests you have to pass:

  • Your App.jsx should now show "5 Birthdays Today" where "5" comes from the length of items imported at top
  • Your screen should show the names of all people in the list
  • You should use the "people" prop in the List component to pass the data and it should display the names

And here's the solution for the challenge.

App.jsx file:

import React, { useState } from 'react' import data from './data' import List from './List' function App() { return (   {/* Make change to "0" here */} 

{data.length} birthdays today

{/* pass data to list component */} ) } export default App

List.jsx file:

import React from 'react' // accept props here const List = (props) => { const { people } = props // Map over prop "people" and display only the names in any way you like return people.map((item) => { return 

{item.name}

}) } export default List

Lab 4 - How to display the new UI

Here's a link to this lab

You can also find the setup files of the lab on GitHub here.

Now that we have the names of people from the static data, let's make the UI a little bit better. You can look through all the CSS in the css files first, and then we will simply start using the CSS classes directly.

In this challenge, you only have to build up from the last challenge and create a UI inside List component.

In this lab, you have to do the following things:

  • Inside your List.jsx file, iterate over the people prop and display the following HTML structure:

NAME_OF_USER

AGE_OF_USER years

  • Make sure you replace the placeholders appropriately. Also, CSS classes in React JSX are named className, just a reminder!

Here are 4 tests you have to pass:

  • Your List component should render the "article" tag as parent
  • Your List component should render the "img" tag inside "article" tag with the correct src and alt tag
  • Your List component should render the "div > h4" inside the "article" tag with the name of the person
  • Your List component should render the "div > p" inside the "article" tag with the age of the person

And here's the solution (List.jsx file):

import React from 'react' // accept props here const List = (props) => { const { people } = props // Map over prop "people" and code the right structure return people.map((person) => { const { id, name, age, image } = person return (  

{name}

{age} years

) }) } export default List

Lab 5 - How to add a Clear All button

Here's a link to this lab

You can also find the setup files of the lab on GitHub here.

In this final lab, let's now add a “Clear” button which will clear the records and reset it to 0 birthdays. The button is already available for you, you just have to make sure it functions properly.

In this lab, you have to do the following things:

  • Create a new state variable called people
  • The initial value of this state variable should be the imported data from the top.
  • Pass this state variable now in the List component.
  • When the Clear button is pressed, empty the state variable so that no record is displayed (Hint: set it to an empty array)

And these are the tests you have to pass:

  • There should be a "Clear All" button on the screen (already done for you)
  • Initially, all records should be visible
  • When the "Clear All" button is pressed, it should remove all records from the screen

Here's the App.jsx solution file for this lab:

import React, { useState } from 'react' import data from './data' import List from './List' function App() { // create a state variable here const [people, setPeople] = useState(data) // this should clear all records function clearAllRecords() { setPeople([]) } return (   

{people.length} birthdays today

Clear All ) } export default App

And you're done! Congrats on completing a small project in React. Way to go :)

Conclusion

I hope you enjoyed this codedamn classroom. You can find many others in the React Mastery learning path on codedamn.

There are a lot of gaps to fill yet, but there's a good chance that it will get you started pretty smoothly if you're new.

Make sure you tell me how your experience was on my Twitter handle, as this will help me frame the next practice classrooms.