<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ android - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Descubre miles de cursos de programación escritos por expertos. Aprende Desarrollo Web, Ciencia de Datos, DevOps, Seguridad y obtén asesoramiento profesional para desarrolladores. ]]>
        </description>
        <link>https://www.freecodecamp.org/espanol/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ android - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/espanol/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 24 May 2026 19:37:31 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/espanol/news/tag/android/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Cómo crear una aplicación Android de noticias usando React Native y Native Base ]]>
                </title>
                <description>
                    <![CDATA[ Vivimos es un mundo donde las cosas están en constante cambio. Así que si quieres mantenerte al día con todo lo que sucede, querrás también contar con una buena aplicación de noticias. Para ayudarte a crear tecnología "cool" y mantenerte al día, en esta publicación construiremos una aplicación de noticias ]]>
                </description>
                <link>https://www.freecodecamp.org/espanol/news/como-crear-una-aplicacion-android-de-noticias-usando-react-native-y-native-base/</link>
                <guid isPermaLink="false">62ca0635771a97081f0e2a51</guid>
                
                    <category>
                        <![CDATA[ android ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Israel Palma ]]>
                </dc:creator>
                <pubDate>Thu, 18 May 2023 00:14:42 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/espanol/news/content/images/2023/05/How-to-Build-a-Weather-Application-using-React--66-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p data-test-label="translation-intro">
        <strong>Artículo original:</strong> <a href="https://www.freecodecamp.org/news/build-an-android-news-app-with-react-native-and-native-base/" target="_blank" rel="noopener noreferrer" data-test-label="original-article-link">How to Build an Android News App with React Native and Native Base</a>
      </p><p>Vivimos es un mundo donde las cosas están en constante cambio. Así que si quieres mantenerte al día con todo lo que sucede, querrás también contar con una buena aplicación de noticias.</p><p>Para ayudarte a crear tecnología "cool" y mantenerte al día, en esta publicación construiremos una aplicación de noticias para Android usando React Native. Esta "traerá" los titulares desde distintos canales de noticias y los mostrará por categoría.</p><figure class="kg-card kg-image-card kg-width-wide"><img src="https://www.freecodecamp.org/news/content/images/2021/08/Screenshot-2021-08-21-210544.png" class="kg-image" alt="Screenshot-2021-08-21-210544" width="600" height="400" loading="lazy"></figure><p>Así es como lucirá nuestra aplicación cuando hayamos terminado. Entonces pongámos manos a la obra.</p><h2 id="c-mo-instalar-expo">Cómo instalar Expo</h2><p>Entonces, ¿Qué es Expo? Expo es un framework (marco de trabajo) que te ayuda a crear y desplegar una aplicación React Native con rapidez y facilidad. </p><p>¡Instalemos Expo!</p><figure class="kg-card kg-code-card"><pre><code>npm install --global expo-cli</code></pre><figcaption>Instalando Expo</figcaption></figure><p>Ejecuta este comando en tu terminal para instalar Expo CLI (Interfaz de Línea de Comandos). Aquí estamos usando el parámetro <code>--global</code> para asegurarnos que esté disponible desde cualquier directorio en nuestro ordenador.</p><p>Luego de haberlo instalado, necesitamos crear un proyecto Expo.</p><figure class="kg-card kg-code-card"><pre><code>expo init News-Application</code></pre><figcaption>Creando un proyecto Expo</figcaption></figure><p>Usa el comando anterior para inicializar el proyecto. También hará algunas preguntas, como el nombre de tu aplicación, cómo; si quieres agregar Typescript a tu proyecto o iniciar en blanco. Solo selecciona "blank" (iniciar en blanco) y presiona enter.</p><p>Después descargará todos los paquetes y dependencias en el folder.</p><p>Ahora, luego de haber terminado la descarga, entra al folder. Para empezar la aplicación escribe <strong><code>expo start</code></strong>. Esto abrirá las herramientas de desarrollo en el navegador.</p><figure class="kg-card kg-image-card kg-width-wide kg-card-hascaption"><img src="https://www.freecodecamp.org/news/content/images/2021/08/Screenshot-2021-08-21-174505.png" class="kg-image" alt="Screenshot-2021-08-21-174505" width="600" height="400" loading="lazy"><figcaption>Expo developer tools</figcaption></figure><p>Aquí verás varias opciones como, correr la app en un dispositivo Android/emulador, o en un simulador iOS. Ejecutaremos al aplicación en el navegador web, así que dale click a la opción "Run in Web Browser" (correr en navegador web).</p><figure class="kg-card kg-code-card"><pre><code>import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';

export default function App() {
  return (
    &lt;View style={styles.container}&gt;
      &lt;Text&gt;Open up App.js to start working on your app!&lt;/Text&gt;
      &lt;StatusBar style="auto" /&gt;
    &lt;/View&gt;
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});
</code></pre><figcaption>Nuestro archivo App.js</figcaption></figure><p>Este es nuestro archivo App.js, que contiene la plantilla predeterminada.</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://www.freecodecamp.org/espanol/news/content/images/2023/04/Abrel-el-archivo-App.ljs-para-empezar-a-trabajar-en-tu-app--1.jpg" class="kg-image" alt="Abrel-el-archivo-App.ljs-para-empezar-a-trabajar-en-tu-app--1" width="414" height="675" loading="lazy"><figcaption>Este es nuestro resultado.</figcaption></figure><p>Ahora nuestra aplicación se está ejecutando.</p><h2 id="c-mo-crear-varias-vistas-usando-react-navigation">Cómo crear varias vistas usando React Navigation</h2><p>Ahora vamos a crear varias pantallas para nuestra aplicación. Para eso, usaremos "React Navigation". Así que vamos a instalarla.</p><p>Dirígete a <a href="https://reactnavigation.org/">https://reactnavigation.org/</a> &nbsp;y da click a "Read Docs" (leer documentación). Este enlace te llevará a la página de la documentación.</p><p>Instalemos "React Navigation" usando el siguiente comando:</p><figure class="kg-card kg-code-card"><pre><code>npm install @react-navigation/native

expo install react-native-screens react-native-safe-area-context</code></pre><figcaption>Instalando React Navigation</figcaption></figure><p>Ahora "React Navigation" ha sido instalado.</p><p>Usaremos &nbsp;<code>bottomTabNavigator</code>. Así que, desde el menú izquierdo, selecciona "API Reference", luego "Navigators" y finalmente "Bottom Tabs".</p><figure class="kg-card kg-image-card kg-width-wide kg-card-hascaption"><img src="https://www.freecodecamp.org/news/content/images/2021/08/Screenshot-2021-08-21-175641.png" class="kg-image" alt="Screenshot-2021-08-21-175641" width="600" height="400" loading="lazy"><figcaption>Selecciona Bottom Tabs</figcaption></figure><p>Instalemos "Bottom Tabs" usando el siguiente comando:</p><figure class="kg-card kg-code-card"><pre><code>npm install @react-navigation/bottom-tabs</code></pre><figcaption>Instalando Bottom Tabs</figcaption></figure><p>Ahora en nuestro archivo App.js, necesitamos importar Bottom Tabs para poder utilizarlo.</p><p>Lo importas así:</p><figure class="kg-card kg-code-card"><pre><code>import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
</code></pre><figcaption>Importando Bottom Tabs</figcaption></figure><p>Ahora importemos el "Tab Screens".</p><figure class="kg-card kg-code-card"><pre><code>import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { NavigationContainer } from '@react-navigation/native';
const Tab = createBottomTabNavigator();

function MyTabs() {
  return (
    &lt;Tab.Navigator&gt;
      &lt;Tab.Screen name="Home" component={HomeScreen} /&gt;
      &lt;Tab.Screen name="Settings" component={SettingsScreen} /&gt;
    &lt;/Tab.Navigator&gt;
  );
}</code></pre><figcaption>Importando el "navegador de pantallas por pestañas" - Tab Navigator Screens</figcaption></figure><p>De esta forma es que creamos las pestañas y botones de la navegación de la parte inferior de la pantalla, usando Bottom Tabs.</p><p>En nuestro caso, necesitamos hacer algo como esto:</p><pre><code>&lt;Tab.Navigator&gt;
  &lt;Tab.Screen name="All" component={All} /&gt;
  &lt;Tab.Screen name="Business" component={Business} /&gt;
  &lt;Tab.Screen name="Health" component={HealthScreen} /&gt;
  &lt;Tab.Screen name="Sports" component={SportsScreen} /&gt;
  &lt;Tab.Screen name="Tech" component={TechScreen} /&gt;
&lt;/Tab.Navigator&gt;</code></pre><p>Necesitamos crear estas pantallas para las siguientes pestañas: All news, Business News, Sports News, Health News y Tech News. También vamos a crear un componente en el proyecto para cada pantalla.</p><p>Necesitamos envolver &nbsp;<code>TabNavigtor</code> en un <code>NavigationContainer</code> así:</p><pre><code>&lt;NavigationContainer&gt;
  &lt;Tab.Navigator&gt;
    &lt;Tab.Screen name="All" component={All} /&gt;
    &lt;Tab.Screen name="Business" component={Business} /&gt;
    &lt;Tab.Screen name="Health" component={HealthScreen} /&gt;
    &lt;Tab.Screen name="Sports" component={SportsScreen} /&gt;
    &lt;Tab.Screen name="Tech" component={TechScreen} /&gt;
  &lt;/Tab.Navigator&gt;
&lt;/NavigationContainer&gt;</code></pre><p>También necesitamos importar todos estos componentes, así que los importamos en la parte superior de nuestro archivo.</p><pre><code>import All from './screens/All';
import Business from './screens/Business';
import HealthScreen from './screens/Health';
import SportsScreen from './screens/Sports';
import TechScreen from './screens/Tech';</code></pre><p>Ahora bien, si juntamos lo que hemos escrito, obtendremos el código siguiente:</p><figure class="kg-card kg-code-card"><pre><code>import React from 'react';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { NavigationContainer } from '@react-navigation/native';
import All from './screens/All';
import Business from './screens/Business';
import HealthScreen from './screens/Health';
import SportsScreen from './screens/Sports';
import TechScreen from './screens/Tech';
const Tab = createBottomTabNavigator();

export default function App() {
  return (
    &lt;NavigationContainer&gt;
      &lt;Tab.Navigator&gt;
        &lt;Tab.Screen name="All" component={All} /&gt;
        &lt;Tab.Screen name="Business" component={Business} /&gt;
        &lt;Tab.Screen name="Health" component={HealthScreen} /&gt;
        &lt;Tab.Screen name="Sports" component={SportsScreen} /&gt;
        &lt;Tab.Screen name="Tech" component={TechScreen} /&gt;
      &lt;/Tab.Navigator&gt;
    &lt;/NavigationContainer&gt;
  );
} </code></pre><figcaption>El código para las pantallas.</figcaption></figure><p>Y este sería el resultado:</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://www.freecodecamp.org/news/content/images/2021/08/Screenshot-2021-08-21-181356.png" class="kg-image" alt="Screenshot-2021-08-21-181356" width="600" height="400" loading="lazy"><figcaption>Nuestras cinco pantallas, a saber: All (Todo), Business (Negocios), Health (Salud), Sports (Deportes) y Tech (Tecnología)</figcaption></figure><p>Tenemos aquí cinco pantallas: All (Todo), Business (Negocios), Health (Salud), Sports (Deportes) y Tech (Tecnología).</p><p>Ahora hagamos algunos ajustes. Necesitamos cambiar los íconos para las pestañas de la parte inferior.</p><p>Para hacer esto necesitaremos recurrir al uso de una librería de íconos. También utilizaremos <em>react-native-elements.</em></p><p>Para instalar <em>react-native-elements, escribe el comando de abajo:</em></p><figure class="kg-card kg-code-card"><pre><code>npm install react-native-elements</code></pre><figcaption>Instalar React Native Elements</figcaption></figure><p>Este paquete de íconos tiene muchas opciones para elegir.</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://www.freecodecamp.org/news/content/images/2021/08/Screenshot-2021-08-21-193917.png" class="kg-image" alt="Screenshot-2021-08-21-193917" width="600" height="400" loading="lazy"><figcaption>Íconos disponibles en React Native Elements</figcaption></figure><p>Ahora agreguemos nuestros íconos en la navegación por pestañas inferior (Bottom Tab Navigator).</p><figure class="kg-card kg-code-card"><pre><code>&lt;Tab.Screen name="All" component={All}
          options={{
            tabBarIcon: (props) =&gt; (
              &lt;Icon type='feather' name='home' color={props.color} /&gt;
            ),
          }} /&gt;</code></pre><figcaption>Agregando un ícono para la pagina de inicio (home)</figcaption></figure><p>Aquí hemos agregado el ícono llamado "home" para la página de inicio y el tipo feather cómo valor para el atributo type.</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://www.freecodecamp.org/news/content/images/2021/08/Screenshot-2021-08-21-194136.png" class="kg-image" alt="Screenshot-2021-08-21-194136" width="600" height="400" loading="lazy"><figcaption>Navegación inferior por pestañas (Bottom Tab Navigator) con el ícono "Home".</figcaption></figure><p>Lo anterior resultará en la pantalla anterior. Y similarmente, repitamos el mismo proceso para todas las pestañas de la navegación.</p><figure class="kg-card kg-code-card"><pre><code>&lt;Tab.Navigator&gt;
        &lt;Tab.Screen name="All" component={All}
          options={{
            tabBarIcon: (props) =&gt; (
              &lt;Icon type='feather' name='home' color={props.color} /&gt;
            ),
          }} /&gt;

        &lt;Tab.Screen name="Business" component={Business}
          options={{
            tabBarIcon: (props) =&gt; (
              &lt;Icon type='feather' name='dollar-sign' color={props.color} /&gt;
            ),
          }} /&gt;

        &lt;Tab.Screen name="Health" component={HealthScreen}
          options={{
            tabBarIcon: (props) =&gt; (
              &lt;Icon type='feather' name='heart' color={props.color} /&gt;
            ),
          }} /&gt;

        &lt;Tab.Screen name="Sports" component={SportsScreen}
          options={{
            tabBarIcon: (props) =&gt; (
              &lt;Icon type='ionicon' name="tennisball-outline" color={props.color} /&gt;
            ),
          }} /&gt;

        &lt;Tab.Screen name="Tech" component={TechScreen}
          options={{
            tabBarIcon: (props) =&gt; (
              &lt;Icon type='ionicon' name="hardware-chip-outline" color={props.color} /&gt;
            ),
          }} /&gt;
      &lt;/Tab.Navigator&gt;</code></pre><figcaption>Todas las pestañas (Bottom Tabs) con Íconos</figcaption></figure><figure class="kg-card kg-image-card kg-width-wide"><img src="https://www.freecodecamp.org/news/content/images/2021/08/Screenshot-2021-08-21-194525.png" class="kg-image" alt="Screenshot-2021-08-21-194525" width="600" height="400" loading="lazy"></figure><p>Ahora cada una de las diferentes pestañas o pantallas esta lista y tienen su propio ícono distintivo.</p><h2 id="c-mo-llamar-al-api-de-noticias-news-api-">Cómo llamar al API de noticias (News API)</h2><p>Enseguida vamos a llamar al News API desde <a href="https://newsapi.org/">https://newsapi.org/</a></p><figure class="kg-card kg-image-card kg-width-wide"><img src="https://www.freecodecamp.org/news/content/images/2021/08/Screenshot-2021-08-21-194845.png" class="kg-image" alt="Screenshot-2021-08-21-194845" width="600" height="400" loading="lazy"></figure><p>Dirígete a este sitio web y date de alta. Ahí tendrás acceso a una clave API (API key).</p><p>Necesitaremos un archivo de configuración (config.js) para guardar todas las constantes con noticias (News), vamos a crearlo.</p><figure class="kg-card kg-code-card"><pre><code>export const API_KEY = ``;
export const endpoint = `https://newsapi.org/v2/top-headlines`;
export const country = 'in'</code></pre><figcaption>Nuestro archivo config.js</figcaption></figure><p>Necesitamos el API_KEY, el endpoint (url) y la clave de país.</p><p>Ahora necesitamos crear un servicio para realizar nuestra <strong>Solicitud GET </strong>al endpoint del API.</p><p>Crea un archivo con el nombre de <em>services.js.</em></p><p>Aquí importaremos el API_KEY, el endpoint (url) y la clave de país al inicio.</p><figure class="kg-card kg-code-card"><pre><code>import { API_KEY, endpoint, country } from '../config/config';</code></pre><figcaption>Services.js</figcaption></figure><p>Luego escribiremos el cuerpo de nuestro archivo services.js</p><figure class="kg-card kg-code-card"><pre><code>export async function services(category = 'general') {
    let articles = await fetch(`${endpoint}?country=${country}&amp;category=${category}`, {
        headers: {
            'X-API-KEY': API_KEY
        }
    });

    let result = await articles.json();
    articles = null;

    return result.articles;
}</code></pre><figcaption>Nuestro servicio GET API&nbsp;</figcaption></figure><p>Así que estamos solicitando los datos de las noticias usando nuestro "endpoint" url y concatenando el código de país además de la categoría. En la función pasamos la categoría "general" ya que es la categoría por defecto. También pasamos el API_key en la propiedad "headers".</p><p>Luego convertimos la respuesta, es decir los datos entrantes, al formato JSON y los almacenamos en la variable "result".</p><p>Y finalmente, los retornamos usando la palabra clave <code>return</code>.</p><p>Aquí está el contenido completo de este archivo para tu referencia:</p><pre><code>import { API_KEY, endpoint, country } from '../config/config';

export async function services(category = 'general') {
    let articles = await fetch(`${endpoint}?country=${country}&amp;category=${category}`, {
        headers: {
            'X-API-KEY': API_KEY
        }
    });

    let result = await articles.json();
    articles = null;

    return result.articles;
}</code></pre><p>Ahora necesitamos importar este servicio en nuestro archivo All.js.</p><figure class="kg-card kg-code-card"><pre><code>import { services } from '../services/services';</code></pre><figcaption>Importar services en All.js</figcaption></figure><p>Necesitaremos usar los "hooks" &nbsp;<code>useState</code> y <code>useEffect</code> , useEffect llamará a este servicio desde el archivo All.js y useState creará el estado que almacenará la respuesta que viene desde la API.</p><figure class="kg-card kg-code-card"><pre><code>import React, { useEffect, useState } from 'react'
import { View } from 'react-native';
import { services } from '../services/services';
export default function All() {
    const [newsData, setNewsData] = useState([])
    useEffect(() =&gt; {
        services('general')
            .then(data =&gt; {
                setNewsData(data)
            })
            .catch(error =&gt; {
                alert(error)
            })
    }, [])
    return (
        &lt;View&gt;

        &lt;/View&gt;
    )
}
</code></pre><figcaption>Usando los hooks useState y useEffect&nbsp;</figcaption></figure><p>En este archivo llamaremos a los servicios que se encuentran en nuestro useEffect "hook". Después almacenaremos la respuesta en el estado (state) de newsData que es un arreglo (array). También pasaremos un parámetro para la categoría que en este caso será "general".</p><p>En esta pantalla traeremos todas las noticias por lo que usaremos la categoría "general". La categoría cambiará para cada pantalla. Será health (salud) para la pantalla Health, sports (deportes) para la pantalla Sports y así sucesivamente.</p><p>Ahora necesitamos mostrar estos datos en nuestra interfaz. Y para ello, necesitamos incluso otro paquete llamado Native Base. Así que vayamos a instalarla.</p><p>Escribe y ejecuta los siguientes comandos para instalar "Native Base":</p><figure class="kg-card kg-code-card"><pre><code>yarn add native-base styled-components styled-system
expo install react-native-svg react-native-safe-area-context</code></pre><figcaption>Instalando Native Base</figcaption></figure><p>En el archivo All.js importaremos unas cuantas cosas de Native Base:</p><figure class="kg-card kg-code-card"><pre><code>import React, { useEffect, useState } from 'react'
import { View, Text } from 'react-native';
import { NativeBaseProvider, FlatList, ScrollView, Divider, Image, Spinner } from 'native-base';
import { services } from '../services/services';</code></pre><figcaption>Importando desde Native Base</figcaption></figure><p>Luego devolveremos el componente <code>NativeBaseProvider</code>.</p><figure class="kg-card kg-code-card"><pre><code>return (
        &lt;NativeBaseProvider&gt;
            
        &lt;/NativeBaseProvider&gt;
    )</code></pre><figcaption>Agregamos NativeBaseProvider en el return</figcaption></figure><p>Ahora agreguemos el Scroll View. Este habilitará a los usuarios para deslizar (scroll) la página hacia abajo en caso de que las noticias ocupen mayor espacio que el disponible para la altura de la pantalla.</p><figure class="kg-card kg-code-card"><pre><code>&lt;NativeBaseProvider&gt;
            &lt;ScrollView height={850}&gt;

            &lt;/ScrollView&gt;
        &lt;/NativeBaseProvider&gt;</code></pre><figcaption>Agregando el ScrollView</figcaption></figure><p>Ahora agreguemos al componente <code>FlatList</code> para mostrar las noticias.</p><figure class="kg-card kg-code-card"><pre><code>&lt;NativeBaseProvider&gt;
            &lt;ScrollView height={850}&gt;
                &lt;FlatList
                    data={newsData}
                    renderItem={({ item }) =&gt; (
                       &lt;View&gt;

                       &lt;/View&gt; 
                    )}
                    keyExtractor={(item) =&gt; item.id}
                /&gt;
            &lt;/ScrollView&gt;
        &lt;/NativeBaseProvider&gt;</code></pre><figcaption>Usando el componente FlatList</figcaption></figure><p>El componente FlatList recibe una propiedad o prop "data" a la cual pasaremos nuestro estado (state) creado anteriormente <code>newsData</code> y devolverá un <code>item</code> de los <code>renderItems</code>.</p><p>Esto es similar a un <code>map</code> en JavaScript, que recorre un arreglo y retorna un elemento. También cuenta con un <code>keyExtractor</code> que usaremos para hacer cada elemento único.</p><p>Ahora, mostremos nuestros datos usando el componente View.</p><p>Crea otro componente View dentro del ya existente componente View, así:</p><pre><code>&lt;NativeBaseProvider&gt;
            &lt;ScrollView height={850}&gt;
                &lt;FlatList
                    data={newsData}
                    renderItem={({ item }) =&gt; (
                       &lt;View&gt;
                           &lt;View&gt;
                               
                           &lt;/View&gt;
                       &lt;/View&gt; 
                    )}
                    keyExtractor={(item) =&gt; item.id}
                /&gt;
            &lt;/ScrollView&gt;
        &lt;/NativeBaseProvider&gt;</code></pre><p>Ahora vamos a agregar algo de texto dentro del componente View hijo.</p><pre><code>&lt;NativeBaseProvider&gt;
            &lt;ScrollView height={850}&gt;
                &lt;FlatList
                    data={newsData}
                    renderItem={({ item }) =&gt; (
                        &lt;View&gt;
                            &lt;View&gt;
                                &lt;Text&gt;
                                    {item.title}
                                &lt;/Text&gt;
                                &lt;Text&gt;
                                    {item.publishedAt}
                                &lt;/Text&gt;
                                &lt;Text&gt;
                                    {item.description}
                                &lt;/Text&gt;
                            &lt;/View&gt;
                        &lt;/View&gt;
                    )}
                    keyExtractor={(item) =&gt; item.id}
                /&gt;
            &lt;/ScrollView&gt;
        &lt;/NativeBaseProvider&gt;</code></pre><p>Este contiene nuestro titular de noticias, la descripción y la fecha de publicación.</p><figure class="kg-card kg-image-card kg-width-wide"><img src="https://www.freecodecamp.org/news/content/images/2021/08/Screenshot-2021-08-21-203253.png" class="kg-image" alt="Screenshot-2021-08-21-203253" width="600" height="400" loading="lazy"></figure><p></p><h2 id="c-mo-estilizar-nuestra-app-de-noticias">Cómo estilizar nuestra app de noticias </h2><p>Ya vimos la apariencia que tiene nuestra app hasta ahora, con el título de las noticias, la descripción y la fecha. Para hacerlo verse un poco mejor necesitamos darle algo de estilo.</p><p>Importa <code>StyleSheet</code> desde Reac Native al principio del archivo para poder usarlo para estilizar nuestra app.</p><figure class="kg-card kg-code-card"><pre><code>import { View, Text, StyleSheet } from 'react-native';</code></pre><figcaption>Importando StyleSheet desde react-native</figcaption></figure><p>Luego, agrega los estilos de la siguiente manera.</p><pre><code>&lt;View&gt;
                            &lt;View style={styles.newsContainer}&gt;
                                &lt;Text style={styles.title}&gt;
                                    {item.title}
                                &lt;/Text&gt;
                                &lt;Text style={styles.date}&gt;
                                    {item.publishedAt}
                                &lt;/Text&gt;
                                &lt;Text style={styles.newsDescription}&gt;
                                    {item.description}
                                &lt;/Text&gt;
                            &lt;/View&gt;
                        &lt;/View&gt;</code></pre><p> Y al final del archivo necesitamos crear esos estilos.</p><figure class="kg-card kg-code-card"><pre><code>const styles = StyleSheet.create({
    newsContainer: {
        padding: 10
    },
    title: {
        fontSize: 18,
        marginTop: 10,
        fontWeight: "600"
    },
    newsDescription: {
        fontSize: 16,
        marginTop: 10
    },
    date: {
        fontSize: 14
    },
});</code></pre><figcaption>Nuestra hoja de estilos StyleSheet en All.js</figcaption></figure><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2021/08/Screenshot-2021-08-21-203824.png" class="kg-image" alt="Screenshot-2021-08-21-203824" width="600" height="400" loading="lazy"></figure><p>Y así es cómo queda la aplicación luego de haber agregado algunas reglas de estilo css. También puedes deslizar la página hacia abajo.</p><p>Ahora necesitamos cambiar el formato de la fecha a uno que mejore su legibilidad, es decir que haga más fácil su lectura, ya que es díficil para una persona entender una fecha cómo <strong>'2021-08-21T11:00:40Z'.</strong></p><p>Para este fin usaremos el útil paquete moment.js, así que instalemos moment usando el siguiente comando:</p><figure class="kg-card kg-code-card"><pre><code>npm install moment --save</code></pre><figcaption>Instalemos Moment.js para darle formato a las fechas.</figcaption></figure><p>Luego lo importamos en nuestro archivo All.js para poder utilizarlo.</p><figure class="kg-card kg-code-card"><pre><code>&lt;Text style={styles.date}&gt;
  {moment(item.publishedAt).format('LLL')}
&lt;/Text&gt;</code></pre><figcaption>Aplicando un formato para fecha y hora usando moment.js</figcaption></figure><p>Podemos usar los siguientes formatos:</p><figure class="kg-card kg-image-card kg-width-wide kg-card-hascaption"><img src="https://www.freecodecamp.org/news/content/images/2021/08/Screenshot-2021-08-21-204311.png" class="kg-image" alt="Screenshot-2021-08-21-204311" width="600" height="400" loading="lazy"><figcaption>Distintos formatos de Moment.js para fechas y horas.</figcaption></figure><p>En la documentación de moment se nos brindan muchos formatos distintos de los cuáles elegir. Para este caso he elegido el formato 'LLL'.</p><figure class="kg-card kg-image-card kg-width-wide"><img src="https://www.freecodecamp.org/news/content/images/2021/08/Screenshot-2021-08-21-204439.png" class="kg-image" alt="Screenshot-2021-08-21-204439" width="600" height="400" loading="lazy"></figure><p>Y ahora nuestras fechas son mucho más fáciles de leer y entender.</p><p>También necesitamos un separador para dividir unos artículos de noticias de otros en la lista y así mejorar tanto su apariencia cómo su legibilidad.</p><figure class="kg-card kg-code-card"><pre><code>&lt;View&gt;
                            &lt;View style={styles.newsContainer}&gt;
                                &lt;Text style={styles.title}&gt;
                                    {item.title}
                                &lt;/Text&gt;
                                &lt;Text style={styles.date}&gt;
                                    {moment(item.publishedAt).format('LLL')}
                                &lt;/Text&gt;
                                &lt;Text style={styles.newsDescription}&gt;
                                    {item.description}
                                &lt;/Text&gt;
                            &lt;/View&gt;
                            &lt;Divider my={2} bg="#e0e0e0" /&gt;
                        &lt;/View&gt;</code></pre><figcaption>Agregando un separador</figcaption></figure><p>Luego de haber dividido cada View hijo nuestra aplicación se verá así:</p><figure class="kg-card kg-image-card kg-width-wide"><img src="https://www.freecodecamp.org/news/content/images/2021/08/Screenshot-2021-08-21-204707.png" class="kg-image" alt="Screenshot-2021-08-21-204707" width="600" height="400" loading="lazy"></figure><p>Ahora los titulares y noticias estarán separados, lo que hace que se vean muy bien.</p><p>Esta API de noticias nos da acceso a una imágen también, así que vamos a agregarla.</p><pre><code>&lt;View&gt;
                            &lt;View style={styles.newsContainer}&gt;
                                &lt;Image
                                    width={550}
                                    height={250}
                                    resizeMode={"cover"}
                                    source={{
                                        uri: item.urlToImage,
                                    }}
                                    alt="Alternate Text"
                                /&gt;
                                &lt;Text style={styles.title}&gt;
                                    {item.title}
                                &lt;/Text&gt;
                                &lt;Text style={styles.date}&gt;
                                    {moment(item.publishedAt).format('LLL')}
                                &lt;/Text&gt;
                                &lt;Text style={styles.newsDescription}&gt;
                                    {item.description}
                                &lt;/Text&gt;
                            &lt;/View&gt;
                            &lt;Divider my={2} bg="#e0e0e0" /&gt;
                        &lt;/View&gt;</code></pre><p>Ya hemos agregado la imágen usando la "key" (clave) llamada <code>urlToImage</code> para esta finalidad.</p><figure class="kg-card kg-image-card kg-width-wide"><img src="https://www.freecodecamp.org/news/content/images/2021/08/Screenshot-2021-08-21-204945.png" class="kg-image" alt="Screenshot-2021-08-21-204945" width="600" height="400" loading="lazy"></figure><p>Ahora ya podemos ver las imágenes que corresponden a cada noticia.</p><h2 id="c-mo-agregar-un-spinner-para-mostrar-cu-ndo-las-noticias-se-est-n-cargando">Cómo agregar un Spinner para mostrar cuándo las noticias se estén cargando</h2><p>Agreguemos un spinner que mostrará cuando las noticias se estén cargando.</p><p>Primero crearemos una condición. Si el tamaño del estado (state) de <code>newsData</code> es mayor a uno, mostraremos nuestro componente <code>FlatList</code> , que contiene los datos de nuestras noticias. Sino, entonces mostraremos el spinner cargando.</p><p>En otras palabras si el tamaño del estado (state) <code>newsData</code> es menor a uno, quiere decir que el arreglo está vació y que la llamada al API aún se esté ejecutando. Una vez que la llamada al API concluya, almacenará los datos en el estado <code>newsData</code> y el tamaño de este arreglo aumentará de cero a uno o mayor.</p><figure class="kg-card kg-code-card"><pre><code>{newsData.length &gt; 1 ? (
                    &lt;FlatList
                        data={newsData}
                        renderItem={({ item }) =&gt; (
                            &lt;View&gt;
                                &lt;View style={styles.newsContainer}&gt;
                                    &lt;Image
                                        width={550}
                                        height={250}
                                        resizeMode={"cover"}
                                        source={{
                                            uri: item.urlToImage,
                                        }}
                                        alt="Alternate Text"
                                    /&gt;
                                    &lt;Text style={styles.title}&gt;
                                        {item.title}
                                    &lt;/Text&gt;
                                    &lt;Text style={styles.date}&gt;
                                        {moment(item.publishedAt).format('LLL')}
                                    &lt;/Text&gt;
                                    &lt;Text style={styles.newsDescription}&gt;
                                        {item.description}
                                    &lt;/Text&gt;
                                &lt;/View&gt;
                                &lt;Divider my={2} bg="#e0e0e0" /&gt;
                            &lt;/View&gt;
                        )}
                        keyExtractor={(item) =&gt; item.id}
                    /&gt;
                ) : (
                    &lt;View style={styles.spinner}&gt;
                        &lt;Spinner color="danger.400" /&gt;
                    &lt;/View&gt;
                )}</code></pre><figcaption>Agregando un Spinner</figcaption></figure><p>Y en nuestros estilos agregaremos el siguiente código para el spinner.</p><figure class="kg-card kg-code-card"><pre><code>spinner: {
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: 400
}</code></pre><figcaption>Estilos para el Spinner</figcaption></figure><p>Aquí abajo está el código de referencia:</p><pre><code>import React, { useEffect, useState } from 'react'
import { View, Text, StyleSheet } from 'react-native';
import { NativeBaseProvider, FlatList, ScrollView, Divider, Image, Spinner } from 'native-base';
import { services } from '../services/services';
import moment from 'moment'
export default function All() {
    const [newsData, setNewsData] = useState([])
    useEffect(() =&gt; {
        services('general')
            .then(data =&gt; {
                setNewsData(data)
            })
            .catch(error =&gt; {
                alert(error)
            })
    }, [])
    return (
        &lt;NativeBaseProvider&gt;
            &lt;ScrollView height={850}&gt;
                {newsData.length &gt; 1 ? (
                    &lt;FlatList
                        data={newsData}
                        renderItem={({ item }) =&gt; (
                            &lt;View&gt;
                                &lt;View style={styles.newsContainer}&gt;
                                    &lt;Image
                                        width={550}
                                        height={250}
                                        resizeMode={"cover"}
                                        source={{
                                            uri: item.urlToImage,
                                        }}
                                        alt="Alternate Text"
                                    /&gt;
                                    &lt;Text style={styles.title}&gt;
                                        {item.title}
                                    &lt;/Text&gt;
                                    &lt;Text style={styles.date}&gt;
                                        {moment(item.publishedAt).format('LLL')}
                                    &lt;/Text&gt;
                                    &lt;Text style={styles.newsDescription}&gt;
                                        {item.description}
                                    &lt;/Text&gt;
                                &lt;/View&gt;
                                &lt;Divider my={2} bg="#e0e0e0" /&gt;
                            &lt;/View&gt;
                        )}
                        keyExtractor={(item) =&gt; item.id}
                    /&gt;
                ) : (
                    &lt;View style={styles.spinner}&gt;
                        &lt;Spinner color="danger.400" /&gt;
                    &lt;/View&gt;
                )}
            &lt;/ScrollView&gt;
        &lt;/NativeBaseProvider&gt;
    )
}

const styles = StyleSheet.create({
    newsContainer: {
        padding: 10
    },
    title: {
        fontSize: 18,
        marginTop: 10,
        fontWeight: "600"
    },
    newsDescription: {
        fontSize: 16,
        marginTop: 10
    },
    date: {
        fontSize: 14
    },
    spinner: {
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: 400
    }
});</code></pre><p>Nuestra vista All.js está ahora completa.</p><p>Y ahora podemos usar el mismo código en todas nuestras otras vistas también. Sólo necesitamos cambiar el parámetro que estamos pasando en los servicios del <code>useEffect</code> Hook.</p><p>Así que para la vista "Business" (negocios) usaremos la palabra "business", para Health usaremos "health", etc.</p><figure class="kg-card kg-code-card"><pre><code>import React, { useEffect, useState } from 'react'
import { View, Text, StyleSheet } from 'react-native';
import { NativeBaseProvider, FlatList, ScrollView, Divider, Image, Spinner } from 'native-base';
import { services } from '../services/services';
import moment from 'moment'
export default function Business() {
    const [newsData, setNewsData] = useState([])
    useEffect(() =&gt; {
        services('business')
            .then(data =&gt; {
                setNewsData(data)
            })
            .catch(error =&gt; {
                alert(error)
            })
    }, [])
    return (
        &lt;NativeBaseProvider&gt;
            &lt;ScrollView height={850}&gt;
                {newsData.length &gt; 1 ? (
                    &lt;FlatList
                        data={newsData}
                        renderItem={({ item }) =&gt; (
                            &lt;View&gt;
                                &lt;View style={styles.newsContainer}&gt;
                                    &lt;Image
                                        width={550}
                                        height={250}
                                        resizeMode={"cover"}
                                        source={{
                                            uri: item.urlToImage,
                                        }}
                                        alt="Alternate Text"
                                    /&gt;
                                    &lt;Text style={styles.title}&gt;
                                        {item.title}
                                    &lt;/Text&gt;
                                    &lt;Text style={styles.date}&gt;
                                        {moment(item.publishedAt).format('LLL')}
                                    &lt;/Text&gt;
                                    &lt;Text style={styles.newsDescription}&gt;
                                        {item.description}
                                    &lt;/Text&gt;
                                &lt;/View&gt;
                                &lt;Divider my={2} bg="#e0e0e0" /&gt;
                            &lt;/View&gt;
                        )}
                        keyExtractor={(item) =&gt; item.id}
                    /&gt;
                ) : (
                    &lt;View style={styles.spinner}&gt;
                        &lt;Spinner color="danger.400" /&gt;
                    &lt;/View&gt;
                )}
            &lt;/ScrollView&gt;
        &lt;/NativeBaseProvider&gt;
    )
}

const styles = StyleSheet.create({
    newsContainer: {
        padding: 10
    },
    title: {
        fontSize: 18,
        marginTop: 10,
        fontWeight: "600"
    },
    newsDescription: {
        fontSize: 16,
        marginTop: 10
    },
    date: {
        fontSize: 14
    },
    spinner: {
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: 400
    }
});</code></pre><figcaption>La vista o pantalla para la categoría Business</figcaption></figure><figure class="kg-card kg-image-card kg-width-wide"><img src="https://www.freecodecamp.org/news/content/images/2021/08/Screenshot-2021-08-21-210200.png" class="kg-image" alt="Screenshot-2021-08-21-210200" width="600" height="400" loading="lazy"></figure><p>Recorrete hacia abajo en la vista Business y verás noticias relacionadas a esta categoría.</p><p>Y podrás hacer lo mismo para todas las pantallas:</p><figure class="kg-card kg-code-card"><pre><code>useEffect(() =&gt; {
        services('business')
            .then(data =&gt; {
                setNewsData(data)
            })
            .catch(error =&gt; {
                alert(error)
            })
}, [])</code></pre><figcaption>Para Business</figcaption></figure><figure class="kg-card kg-code-card"><pre><code>useEffect(() =&gt; {
        services('health')
            .then(data =&gt; {
                setNewsData(data)
            })
            .catch(error =&gt; {
                alert(error)
            })
    }, [])</code></pre><figcaption>Para Health</figcaption></figure><figure class="kg-card kg-code-card"><pre><code>useEffect(() =&gt; {
        services('sports')
            .then(data =&gt; {
                setNewsData(data)
            })
            .catch(error =&gt; {
                alert(error)
            })
    }, [])</code></pre><figcaption>Para Sports</figcaption></figure><figure class="kg-card kg-code-card"><pre><code>useEffect(() =&gt; {
        services('technology')
            .then(data =&gt; {
                setNewsData(data)
            })
            .catch(error =&gt; {
                alert(error)
            })
    }, [])</code></pre><figcaption>Para Tech</figcaption></figure><h2 id="conclusi-n">Conclusión</h2><p>Felicidades! </p><p>Ahora nuetra aplicación de noticias está completa.</p><p>Así que adelante! Crea y experiumenta con esta aplicación. Hay muchas cosas que puedes hacer.</p><p>Se bienvenido a descargar el código fuente en: <a href="https://github.com/nishant-666/React-Native-News">https://github.com/nishant-666/React-Native-News</a></p><blockquote>Feliz Aprendizaje.</blockquote> ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
