Open Source @ UNA

Repositorio Open Source de documentación en nuevas tecnologías


Project maintained by tfg2021-escinf-una Hosted on GitHub Pages — Theme by mattgraham

Regresar

Setup

En el siguiente link encontrará el repositorio creado para este ejemplo práctico: https://github.com/tfg2021-escinf-una/eg.tfg.react/tree/integration. En caso de tener alguna duda con el código, puede revisar directamente en el repositorio, o bien, clonarlo y modificarlo.

  1. Abrir el repositorio microservices-tutorial/react-ui en el editor de texto

  2. En este momento la lista de archivos en el proyecto es la siguiente:

microservices-tutorial
│
└─── react-ui
│   │   README.md
│   │   .gitignore
  1. (Opcional) Para inicializar este proyecto de React junto con TypeScript, utilizamos el paquete CRA.
    • Para crear la estructura puede utilizar el siguiente comando npx create-react-app my-app --template typescript
    • La consola va a ir indicando las opciones a seleccionar para crear la solucion necesaria.
  2. Para la ejecucion de este proyecto, recomendamos descargar el repositorio adentro de la estructura anteriormente descrita.
    • Esto lo puede realizar mediante la utilización de git
    • Link al repo
  3. Una vez clonado, debe proceder a la instalación de las dependencias. Esto se logra mediante el siguiente comando:
     npm install
    

Análisis de la estructura del repositorio.

microservices-tutorial
│
└─── react-ui
│   │   config
│   │   deployment
│   │   public
│   │   src
│   │   README.md
│   │   .gitignore

Análisis de la estructura dentro de src.

react-ui
└─── src
│   │   api
│   │   components
│   │   interfaces
│   │   pages
│   │   redux
│   │   router

Ejemplo de un componente

import styled, { FlattenSimpleInterpolation } from 'styled-components'
import { IDeviceBreakpointsDefsProps } from '../../themes'

export const Container = styled.div<IDeviceBreakpointsDefsProps & {
  flex?: boolean,
  direction?: 'row' | 'column', 
  callback?: () => FlattenSimpleInterpolation
}>`
  ${({ theme, mobileS, mobileM, mobileL, laptop, laptopL, tablet, desktop, callback }) => 
    theme.breakpoints.create({
      mobileS: mobileS,
      mobileM: mobileM,
      mobileL: mobileL,
      laptop: laptop,
      laptopL: laptopL,
      tablet: tablet,
      desktop: desktop 
    })(callback)
  };

  ${({ flex, direction }) => flex && `
    display: flex;
    flex-direction: ${direction} !important;
  `};
`

Ejemplo de una página (Covid-19)

import { useNewsQuery, useVaccinesQuery } from '../../api'
import { Grid, GridItem, Typography, withAuthentication } from '../../components'
import { DataTable } from './composites/DataTable'
import { StyledCarousel, StyledCarouselContainer, StyledImg, StyledMainContainer, StyledVaccinesInfoContainer } from './CovidNews.styles'

const CovidNews = () => {
  const { data: newsData, isLoading: isLoadingNews } = useNewsQuery({})
  const { data: vaccinesData } = useVaccinesQuery({})
  return (
    <StyledMainContainer>
      { newsData && !isLoadingNews && 
        <StyledCarouselContainer xs={12}
                                 sm={11}
                                 md={10}
                                 lg={8}
                                 xl={8}>
          <StyledCarousel>
            {
              newsData.news.map((news, i) => (       
                <Grid key={i}>
                  <GridItem xs={12}
                            sm={12}
                            md={6}
                            lg={6}>
                    <StyledImg src={news.urlToImage} 
                              alt={news.title} />
                  </GridItem>
                  <GridItem xs={12}
                            sm={12}
                            md={6}
                            lg={6}>
                    <Typography as="h2"
                                weight='bolder'
                                size="xl">
                      {news.title}
                    </Typography>
                    <Typography as="h2"
                                size="md">
                      {news.content.split('[')[0]}
                    </Typography>
                  </GridItem>
                </Grid>)
              )
            }
          </StyledCarousel>
        </StyledCarouselContainer>
      } 
      {
        vaccinesData && 
          <StyledVaccinesInfoContainer xs={12}
                                       sm={11}
                                       md={10}
                                       lg={7}
                                       xl={7}>
            <Typography as="h2"
                        size='xl'
                        weight='bolder'
                        textAlign="center">
              Vaccines Research Info
            </Typography>
            <DataTable vaccines={vaccinesData} />
          </StyledVaccinesInfoContainer>
      } 
    </StyledMainContainer>
  )
}

export const AuthCovidNews = withAuthentication(CovidNews)

Definicion de las rutas

import React from "react"
import { 
  AuthCovidNews,
  AuthHome,
  Login,
  Informative,
  Register,
  AuthCities,
  AuthProfile,
  AuthMail
} from "../pages"

/**
 * Here we are going to define all the routes of the application.
 * Also, if there are pages that need to be decorated with our authentication hoc,
 * this is the place to do it.
 */

export const routeConfig = [
  {
    path: '/',
    element : React.createElement(Informative),
    exact: true
  },
  {
    path: '/home',
    element : React.createElement(AuthHome),
    exact: true
  },
  ...
]
import { BrowserRouter, Route, Routes } from "react-router-dom";
import { withBaseWrapper } from "../components";
import { routeConfig } from "./routes";

const AppWrapper = withBaseWrapper(
  ({ children } : any) => (<>{ children }</>)
);

export const ApplicationRouter = () => {
  return (
    <BrowserRouter>
      <AppWrapper>
        <Routes>
          { routeConfig.map((route, index) => <Route key={index} {...route} /> ) }
        </Routes>
      </AppWrapper>
    </BrowserRouter>
  )
};
  1. Manejo de los Estados
    • Como se mencionó con anterioridad, redux se utilizó para el manejo del estado de sesion.
    • Por otro lado en las páginas, dado a que el estado no tenía mucha complejidad se utilizó el hook useReducer, el cual es muy similar al manejo que redux ofrece.
  2. Ejecución del servidor
    • Esto se logra mediante la ejecución del siguiente comando:
    npm run start

Una vez realizados todos estos pasos, el servidor está listo para recibir peticiones HTTP en el puerto 3000.

AnteriorSiguiente