Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

Añadir texto animado en React o React Native

Tiempo de lectura: < 1 minuto

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

scabble - pexels

Este componente recibe un texto y lo anima caracter a caracter.

Primero vamos a crear este componente:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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;
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;
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<TextoAnimado texto={"Texto animado"}/>
<TextoAnimado texto={"Texto animado"}/>
<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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<TextoAnimado texto={"Texto animado para poder detener pulsar boton"} stopAnimation={stopAnimacion} />
<TextoAnimado texto={"Texto animado para poder detener pulsar boton"} stopAnimation={stopAnimacion} />
<TextoAnimado texto={"Texto animado para poder detener pulsar boton"} stopAnimation={stopAnimacion} />
0

1 comentario en «Añadir texto animado en React o React Native»

Deja un comentario