Hoy vamos a crear un pequeño componente que añade texto animado para nuestros juegos en React o React Native.

Este componente recibe un texto y lo anima caracter a caracter.
Primero vamos a crear este componente:
import { marron } from "@/constants/Colors"; import React, { useState, useEffect } from "react"; import { View, StyleSheet } from "react-native"; import TextoCustom from "./TextoCustom"; const VELOCIDAD_CARACTERES_PANTALLA = 50; // Milisegundos entre caracteres interface TextoAnimadoProps { texto: string; stopAnimation?: boolean; } const TextoAnimado: React.FC<TextoAnimadoProps> = ({ texto, stopAnimation = false }) => { const [textoAnimado, setTextoAnimado] = useState<string>(""); useEffect(() => { setTextoAnimado(""); // Reiniciar animación al recibir un nuevo texto let index = 0; const interval = setInterval(() => { //Rellenar el texto animado con cada caracter del texto original if (stopAnimation) { //Pinta el texto completo si se detiene la animación setTextoAnimado(texto); clearInterval(interval); return; } if (index < texto.length) { let textoActual = texto.substring(0, index + 1); setTextoAnimado(textoActual); index++; } }, VELOCIDAD_CARACTERES_PANTALLA); return () => clearInterval(interval); // Limpiar intervalo cuando el componente se desmonta }, [texto, stopAnimation]); return ( <View> <Text style={{fontSize: 20, textAlign: "left" }}> {textoAnimado} </Text> </View> ); }; export default TextoAnimado;
Ahora podemos utilizar el componente de esta forma:
<TextoAnimado texto={"Texto animado"}/>
Y si queremos detener la animación podemos crear un botón o un componente pulsable por encima para establecer stopAnimation a true:
<TextoAnimado texto={"Texto animado para poder detener pulsar boton"} stopAnimation={stopAnimacion} />

Ingeniero en Informática, Investigador, me encanta crear cosas o arreglarlas y darles una nueva vida. Escritor y poeta. Más de 20 APPs publicadas y un libro en Amazon.
1 comentario en «Añadir texto animado en React o React Native»