13. Componente Text

 

Tutorial: Componente Text en React Native

📱 Parte 13: Componente Text - Mostrando Contenido Escrito

🎯 Objetivo:

Aprender a usar el componente Text para mostrar contenido escrito en React Native, aplicar estilos de texto y crear interfaces ricas en texto.


📸 Analizando el Ejemplo de la Imagen

Observando el código de la imagen:

javascript

import React from 'react';

import { View, Text } from 'react-native'; // ✅ Text importado correctamente


const App = () => {

  return (

    <View>

      <View style={{backgroundColor: 'green', width: 150, height: 150}} />

      <View style={{backgroundColor: 'black', width: 150, height: 150}} />

      <View style={{backgroundColor: 'gray', width: 150, height: 150}} />

      <Text>Hola Mundo!</Text> {/* ✅ Componente Text agregado */}

    </View>

  );

};


export default App;

Resultado visual esperado:

text

┌─────────────────────────────────┐

│    ┌─────────────┐              │

│    │    VERDE    │              │

│    │             │              │

│    └─────────────┘              │

│    ┌─────────────┐              │

│    │    NEGRO    │              │

│    │             │              │

│    └─────────────┘              │

│    ┌─────────────┐              │

│    │    GRIS     │              │

│    │             │              │

│    └─────────────┘              │

│    Hola Mundo!                  │ ← ¡TEXTO AQUÍ!

└─────────────────────────────────┘


🚀 Paso 1: ¿Qué es el Componente Text?

Text es el componente para mostrar texto en React Native. Es equivalente a las etiquetas <p>, <span>, <h1>, etc., en HTML.

1.1 Importación Básica

javascript

import React from 'react';

import { Text } from 'react-native'; // ¡IMPORTANTE importar Text!


📝 Paso 2: Texto Básico

2.1 Texto Simple

javascript

const TextoBasico = () => {

  return (

    <View style={styles.container}>

      <Text>¡Hola React Native!</Text>

    </View>

  );

};

2.2 Texto con Estilos Inline

javascript

const TextoConEstilos = () => {

  return (

    <View style={styles.container}>

      <Text style={{ 

        fontSize: 30,          // Tamaño de fuente grande

        fontWeight: 'bold',    // Texto en negrita

        color: 'blue',         // Color del texto

        textAlign: 'center',   // Alineación centrada

      }}>

        Texto con Estilos

      </Text>

    </View>

  );

};

2.3 DEMOSTRACIÓN: Comparación Con/Sin Estilos

javascript

const ComparacionTexto = () => {

  return (

    <View style={styles.container}>

      {/* Texto sin estilos */}

      <Text style={styles.label}>Sin estilos:</Text>

      <Text>Este es un texto normal</Text>

      

      {/* Texto con estilos básicos */}

      <Text style={styles.label}>Con estilos básicos:</Text>

      <Text style={{ fontSize: 20, color: 'red' }}>

        Texto rojo tamaño 20

      </Text>

      

      {/* Texto con múltiples estilos */}

      <Text style={styles.label}>Con múltiples estilos:</Text>

      <Text style={{

        fontSize: 30,

        fontWeight: 'bold',

        color: 'green',

        fontStyle: 'italic',

        textAlign: 'center',

        backgroundColor: '#f0f0f0',

        padding: 10,

      }}>

        ¡Texto avanzado!

      </Text>

    </View>

  );

};


const styles = StyleSheet.create({

  container: {

    flex: 1,

    padding: 20,

  },

  label: {

    marginTop: 20,

    marginBottom: 5,

    color: '#666',

    fontSize: 16,

  },

});


🎨 Paso 3: Propiedades de Estilo de Texto

3.1 Propiedades Principales de Texto

javascript

<Text

  style={{

    // TAMAÑO Y PESO

    fontSize: 16,           // Tamaño en puntos

    fontWeight: 'bold',     // 'normal', 'bold', '100'-'900'

    fontStyle: 'italic',    // 'normal', 'italic'

    

    // COLOR Y FONDO

    color: '#333',          // Color del texto

    backgroundColor: '#f0f0f0', // Fondo del texto

    

    // ALINEACIÓN

    textAlign: 'center',    // 'auto', 'left', 'right', 'center', 'justify'

    textAlignVertical: 'center', // 'auto', 'top', 'bottom', 'center'

    

    // ESPACIADO

    lineHeight: 24,         // Altura de línea

    letterSpacing: 1,       // Espacio entre letras

    textTransform: 'uppercase', // 'none', 'uppercase', 'lowercase', 'capitalize'

    

    // DECORACIÓN

    textDecorationLine: 'underline', // 'none', 'underline', 'line-through', 'underline line-through'

    textDecorationColor: 'red',      // Color de la decoración

    textDecorationStyle: 'solid',    // 'solid', 'double', 'dotted', 'dashed'

    

    // SOMBRA

    textShadowColor: 'rgba(0, 0, 0, 0.5)',

    textShadowOffset: { width: 1, height: 1 },

    textShadowRadius: 2,

    

    // FAMILIA DE FUENTE

    fontFamily: 'System',   // Fuente específica

    includeFontPadding: true, // Android: incluir padding de fuente

    

    // OTROS

    writingDirection: 'ltr', // 'auto', 'ltr', 'rtl'

  }}

>

  Texto con todas las propiedades

</Text>

3.2 Ejemplo Práctico con Todas las Propiedades

javascript

const TextoCompleto = () => {

  return (

    <View style={styles.container}>

      {/* Texto con sombra */}

      <Text style={styles.textoConSombra}>

        Texto con Sombra

      </Text>

      

      {/* Texto con decoraciones */}

      <Text style={styles.textoSubrayado}>

        Texto Subrayado

      </Text>

      <Text style={styles.textoTachado}>

        Texto Tachado

      </Text>

      

      {/* Texto con transformaciones */}

      <Text style={styles.textoNormal}>

        texto en minúsculas

      </Text>

      <Text style={styles.textoMayusculas}>

        Convertido a mayúsculas

      </Text>

      

      {/* Texto con espaciado */}

      <Text style={styles.textoEspaciado}>

        Texto con espacio entre letras

      </Text>

    </View>

  );

};


const styles = StyleSheet.create({

  container: {

    flex: 1,

    padding: 20,

    backgroundColor: '#fff',

  },

  textoConSombra: {

    fontSize: 28,

    fontWeight: 'bold',

    color: '#fff',

    textShadowColor: 'rgba(0, 0, 0, 0.75)',

    textShadowOffset: { width: 2, height: 2 },

    textShadowRadius: 5,

    marginVertical: 10,

  },

  textoSubrayado: {

    fontSize: 20,

    textDecorationLine: 'underline',

    textDecorationColor: 'blue',

    textDecorationStyle: 'solid',

    marginVertical: 10,

  },

  textoTachado: {

    fontSize: 20,

    textDecorationLine: 'line-through',

    textDecorationColor: 'red',

    marginVertical: 10,

  },

  textoNormal: {

    fontSize: 18,

    marginVertical: 10,

  },

  textoMayusculas: {

    fontSize: 18,

    textTransform: 'uppercase',

    marginVertical: 10,

  },

  textoEspaciado: {

    fontSize: 18,

    letterSpacing: 3,

    marginVertical: 10,

  },

});


🔤 Paso 4: Jerarquía de Texto (Text Anidados)

4.1 Texto con Diferentes Estilos en una Línea

javascript

const TextoAnidado = () => {

  return (

    <Text style={styles.parrafo}>

      Este es un texto{' '}

      <Text style={styles.negrita}>en negrita</Text>

      {' '}y este está{' '}

      <Text style={styles.cursiva}>en cursiva</Text>

      . También podemos tener{' '}

      <Text style={styles.resaltado}>texto resaltado</Text>

      {' '}y{' '}

      <Text style={styles.enlace}>enlaces simulados</Text>

      {' '}en el mismo párrafo.

    </Text>

  );

};


const styles = StyleSheet.create({

  parrafo: {

    fontSize: 16,

    lineHeight: 24,

    margin: 20,

  },

  negrita: {

    fontWeight: 'bold',

    color: '#000',

  },

  cursiva: {

    fontStyle: 'italic',

    color: '#555',

  },

  resaltado: {

    backgroundColor: '#fffacd',

    paddingHorizontal: 4,

    borderRadius: 3,

  },

  enlace: {

    color: '#007AFF',

    textDecorationLine: 'underline',

  },

});

4.2 Ejemplo: Títulos y Párrafos

javascript

const TitulosYParrafos = () => {

  return (

    <View style={styles.container}>

      {/* Título principal */}

      <Text style={styles.h1}>

        Título Principal

      </Text>

      

      {/* Subtítulo */}

      <Text style={styles.h2}>

        Subtítulo Importante

      </Text>

      

      {/* Párrafo */}

      <Text style={styles.parrafo}>

        Este es un párrafo de ejemplo que muestra cómo podemos crear texto con diferentes estilos en React Native. Los párrafos pueden contener {' '}

        <Text style={styles.resaltado}>texto resaltado</Text>

        {' '}o incluso{' '}

        <Text style={styles.codigo}>código inline</Text>.

      </Text>

      

      {/* Lista usando Text */}

      <Text style={styles.h3}>Lista de Elementos:</Text>

      <Text style={styles.lista}>

        {'\u2022'} Primer elemento de la lista{'\n'}

        {'\u2022'} Segundo elemento con {' '}

        <Text style={styles.negrita}>texto en negrita</Text>{'\n'}

        {'\u2022'} Tercer elemento

      </Text>

    </View>

  );

};


const styles = StyleSheet.create({

  container: {

    flex: 1,

    padding: 20,

    backgroundColor: '#fff',

  },

  h1: {

    fontSize: 32,

    fontWeight: 'bold',

    marginBottom: 10,

    color: '#000',

  },

  h2: {

    fontSize: 24,

    fontWeight: '600',

    marginBottom: 15,

    color: '#333',

  },

  h3: {

    fontSize: 20,

    fontWeight: '600',

    marginTop: 20,

    marginBottom: 10,

    color: '#555',

  },

  parrafo: {

    fontSize: 16,

    lineHeight: 24,

    marginBottom: 15,

    color: '#444',

  },

  lista: {

    fontSize: 16,

    lineHeight: 28,

    color: '#444',

  },

  resaltado: {

    backgroundColor: '#fffacd',

    paddingHorizontal: 4,

    borderRadius: 3,

  },

  codigo: {

    fontFamily: Platform.OS === 'ios' ? 'Courier New' : 'monospace',

    backgroundColor: '#f5f5f5',

    paddingHorizontal: 4,

    borderRadius: 3,

  },

  negrita: {

    fontWeight: 'bold',

  },

});


📱 Paso 5: Texto Responsivo y Dinámico

5.1 Texto que se Ajusta al Tamaño

javascript

import { useWindowDimensions } from 'react-native';


const TextoResponsivo = () => {

  const { width, height } = useWindowDimensions();

  

  // Tamaño de fuente basado en el ancho de pantalla

  const fontSizeResponsive = width * 0.05; // 5% del ancho de pantalla

  

  return (

    <View style={styles.container}>

      <Text style={[styles.titulo, { fontSize: fontSizeResponsive }]}>

        Título Responsivo

      </Text>

      

      <Text style={styles.info}>

        Ancho: {width.toFixed(0)}px{'\n'}

        Alto: {height.toFixed(0)}px{'\n'}

        Tamaño fuente: {fontSizeResponsive.toFixed(1)}px

      </Text>

    </View>

  );

};

5.2 Texto con Número Máximo de Líneas

javascript

const TextoConLimite = () => {

  const textoLargo = "Este es un texto muy largo que probablemente no quepa en una sola línea de la pantalla. Por eso necesitamos limitar el número de líneas y agregar puntos suspensivos al final.";

  

  return (

    <View style={styles.container}>

      <Text style={styles.label}>Texto completo:</Text>

      <Text style={styles.textoCompleto}>{textoLargo}</Text>

      

      <Text style={styles.label}>Limitado a 2 líneas:</Text>

      <Text 

        style={styles.textoLimitado}

        numberOfLines={2}        // Máximo 2 líneas

        ellipsizeMode="tail"     // "tail", "head", "middle", "clip"

      >

        {textoLargo}

      </Text>

      

      <Text style={styles.label}>Limitado a 1 línea:</Text>

      <Text 

        style={styles.textoLimitado}

        numberOfLines={1}

        ellipsizeMode="middle"   // "Texto...final"

      >

        {textoLargo}

      </Text>

    </View>

  );

};


🎯 Paso 6: Propiedades de Texto (no style)

6.1 Propiedades Funcionales de Texto

javascript

const TextoConPropiedades = () => {

  const [pulsado, setPulsado] = useState(false);

  const textoSeleccionable = "Este texto puede ser seleccionado y copiado por el usuario.";

  

  return (

    <View style={styles.container}>

      {/* Texto seleccionable */}

      <Text 

        style={styles.texto}

        selectable={true}           // Permite seleccionar texto

        selectionColor="#ff6b6b"    // Color de selección

      >

        {textoSeleccionable}

      </Text>

      

      {/* Texto con eventos */}

      <Text 

        style={[styles.botonTexto, pulsado && styles.botonTextoPulsado]}

        onPress={() => {

          setPulsado(!pulsado);

          alert('¡Texto presionado!');

        }}

        onLongPress={() => alert('Presión larga en texto')}

      >

        {pulsado ? '✅ Texto presionado' : '👆 Tócame'}

      </Text>

      

      {/* Texto ajustable */}

      <Text 

        style={styles.textoAjustable}

        adjustsFontSizeToFit={true}    // Ajusta tamaño automáticamente

        numberOfLines={1}               // Mantiene en 1 línea

        minimumFontScale={0.5}         // Escala mínima

      >

        Texto que se ajusta automáticamente

      </Text>

      

      {/* Texto para pruebas */}

      <Text 

        style={styles.textoPrueba}

        testID="texto-prueba"         // ID para pruebas

        accessibilityLabel="Texto de ejemplo" // Accesibilidad

        accessible={true}              // Habilitar accesibilidad

      >

        Texto accesible para pruebas

      </Text>

    </View>

  );

};


📊 Paso 7: Ejercicio Práctico - Tarjeta de Producto con Texto

Objetivo: Crear una tarjeta de producto usando Text de diferentes maneras

javascript

const ProductCard = () => {

  return (

    <View style={styles.card}>

      {/* Título del producto */}

      <Text style={styles.productTitle}>

        iPhone 14 Pro Max

      </Text>

      

      {/* Descripción */}

      <Text style={styles.productDescription}>

        El iPhone 14 Pro Max cuenta con una pantalla Super Retina XDR de 6.7 pulgadas, el chip A16 Bionic y un sistema de cámaras profesional.{' '}

        <Text style={styles.highlight}>Novedad:</Text>{' '}

        <Text style={styles.newFeature}>Dynamic Island</Text>

        {' '}para una nueva forma de interactuar.

      </Text>

      

      {/* Especificaciones */}

      <Text style={styles.sectionTitle}>Especificaciones:</Text>

      <Text style={styles.specs}>

        • Pantalla: 6.7" Super Retina XDR{'\n'}

        • Procesador: A16 Bionic{'\n'}

        • Memoria: 256GB/512GB/1TB{'\n'}

        • Cámara: Sistema Pro de 48MP{'\n'}

        • Batería: Hasta 29 horas de video

      </Text>

      

      {/* Precio y disponibilidad */}

      <View style={styles.priceContainer}>

        <Text style={styles.price}>$1,099.00</Text>

        <Text style={styles.oldPrice}>$1,199.00</Text>

        <Text style={styles.discount}>-8%</Text>

      </View>

      

      {/* Disponibilidad */}

      <Text style={styles.availability}>

        <Text style={styles.inStock}>✓ En stock</Text>

        {' • Entrega en 24h'}

      </Text>

      

      {/* Etiquetas */}

      <View style={styles.tagsContainer}>

        <Text style={styles.tag}>🎯 Popular</Text>

        <Text style={styles.tag}>⚡ Nuevo</Text>

        <Text style={styles.tag}>🔥 Oferta</Text>

      </View>

    </View>

  );

};


const styles = StyleSheet.create({

  card: {

    backgroundColor: 'white',

    borderRadius: 12,

    padding: 20,

    margin: 15,

    shadowColor: '#000',

    shadowOffset: { width: 0, height: 2 },

    shadowOpacity: 0.1,

    shadowRadius: 4,

    elevation: 3,

  },

  productTitle: {

    fontSize: 24,

    fontWeight: 'bold',

    color: '#000',

    marginBottom: 10,

  },

  productDescription: {

    fontSize: 16,

    lineHeight: 24,

    color: '#444',

    marginBottom: 15,

  },

  highlight: {

    fontWeight: 'bold',

    color: '#000',

  },

  newFeature: {

    backgroundColor: '#007AFF',

    color: 'white',

    paddingHorizontal: 6,

    paddingVertical: 2,

    borderRadius: 4,

    overflow: 'hidden',

  },

  sectionTitle: {

    fontSize: 18,

    fontWeight: '600',

    marginTop: 15,

    marginBottom: 8,

    color: '#333',

  },

  specs: {

    fontSize: 14,

    lineHeight: 22,

    color: '#555',

    marginBottom: 15,

  },

  priceContainer: {

    flexDirection: 'row',

    alignItems: 'center',

    marginVertical: 10,

  },

  price: {

    fontSize: 28,

    fontWeight: 'bold',

    color: '#000',

    marginRight: 10,

  },

  oldPrice: {

    fontSize: 18,

    color: '#999',

    textDecorationLine: 'line-through',

    marginRight: 10,

  },

  discount: {

    backgroundColor: '#ff3b30',

    color: 'white',

    paddingHorizontal: 8,

    paddingVertical: 2,

    borderRadius: 4,

    fontSize: 14,

    fontWeight: 'bold',

  },

  availability: {

    fontSize: 14,

    color: '#666',

    marginBottom: 15,

  },

  inStock: {

    color: '#34c759',

    fontWeight: '600',

  },

  tagsContainer: {

    flexDirection: 'row',

    flexWrap: 'wrap',

    marginTop: 10,

  },

  tag: {

    backgroundColor: '#f0f0f0',

    paddingHorizontal: 10,

    paddingVertical: 4,

    borderRadius: 12,

    marginRight: 8,

    marginBottom: 8,

    fontSize: 12,

    color: '#666',

  },

});


⚠️ Paso 8: Errores Comunes y Soluciones

❌ Error: "Text strings must be rendered within a <Text> component"

javascript

// ❌ MAL: Texto fuera de Text

<View>

  Texto fuera de componente

  <Text>Texto correcto</Text>

</View>


// ✅ BIEN: Todo texto dentro de Text

<View>

  <Text>Texto correcto</Text>

</View>

❌ Error: "Text no se muestra"

javascript

// SOLUCIÓN: Asegurar color contrastante

<Text style={{ color: 'black', fontSize: 16 }}>

  Texto visible

</Text>

❌ Error: "Fuente no carga"

javascript

// SOLUCIÓN: Usar fuentes del sistema o cargar custom

<Text style={{ fontFamily: 'System' }}>

  Texto con fuente del sistema

</Text>


📋 Paso 9: Mejores Prácticas con Texto

9.1 Consejos Profesionales

  1. Usa StyleSheet.create() para estilos de texto reutilizables

  2. Define una paleta de estilos (h1, h2, body, caption)

  3. Considera la accesibilidad con contrastes adecuados

  4. Usa numberOfLines para controlar texto largo

  5. Prueba en diferentes tamaños de pantalla

9.2 Sistema de Estilos Tipográficos

javascript

const typography = StyleSheet.create({

  h1: {

    fontSize: 32,

    fontWeight: 'bold',

    lineHeight: 40,

  },

  h2: {

    fontSize: 24,

    fontWeight: '600',

    lineHeight: 32,

  },

  body: {

    fontSize: 16,

    lineHeight: 24,

  },

  caption: {

    fontSize: 14,

    color: '#666',

  },

  button: {

    fontSize: 16,

    fontWeight: '600',

    textTransform: 'uppercase',

  },

});


// Uso consistente

<Text style={typography.h1}>Título</Text>

<Text style={typography.body}>Párrafo</Text>


🎯 Resumen: ¿Cuándo usar qué tipo de Texto?

Propósito

Ejemplo

Estilo recomendado

Títulos

Pantallas, secciones

fontSize: 24+, bold

Subtítulos

Explicaciones

fontSize: 18-20, semibold

Párrafos

Contenido principal

fontSize: 16, lineHeight: 24

Botones

Acciones

fontSize: 16, uppercase, bold

Etiquetas

Tags, badges

fontSize: 12-14, background

Código

Fragmentos de código

fontFamily: monospace


🎬 Próximo Tutorial

En el siguiente video aprenderemos:

  • Componente Image para mostrar imágenes

  • Imágenes locales vs remotas

  • Optimización de imágenes

  • ImageBackground para fondos


✅ ¡Ahora dominas el componente Text! Es esencial para cualquier aplicación. Recuerda practicar combinando diferentes estilos y propiedades para crear interfaces de texto ricas y atractivas


Comentarios

Entradas más populares de este blog

18. Visualizar nuestros componentes limpios con StyleSheet

15. Componente Image

Tema: 23. Justify Content en Flexbox para Column (Columna) en React Nativ