Crear un componente bocadillo animado para un videojuego React Native o React

Tiempo de lectura: 2 minutos

Hoy vamos a crear un componente que representa un bocadillo de texto animado para React o React Native.

bocadillo game - pexels

El componente recibirá un texto o un elemento qué represente un texto y además mostrará un puntero animado al final del texto.

import React, { useEffect, useState } from "react";
import { View, StyleSheet, Text } from "react-native";
import TextoCustom from "./TextoCustom";

interface BocadilloTextoProps {
    texto: string | React.ReactNode;
    mostrarPuntero?: boolean;
}

const BocadilloTexto: React.FC<BocadilloTextoProps> = ({ texto, mostrarPuntero = true }) => {
    const [mostrarCursor, setMostrarCursor] = useState(true);

    useEffect(() => {
        if (!mostrarPuntero) return;

        const interval = setInterval(() => {
            setMostrarCursor((prev) => !prev);
        }, 500); // Parpadeo cada 500ms

        return () => clearInterval(interval);
    }, [mostrarPuntero]);

    return (
        <View style={styles.contenedor}>
            <View style={styles.bocadillo}>
                <View style={styles.textoContainer}>
                    <TextoCustom style={styles.texto}>{texto}</TextoCustom>
                    {mostrarPuntero && (
                        <Text style={styles.cursor}>{mostrarCursor ? "▌" : " "}</Text>
                    )}
                </View>
            </View>
        </View>
    );
};

export default BocadilloTexto;

const styles = StyleSheet.create({
    contenedor: {
        alignItems: "center",
        justifyContent: "center",
        marginVertical: 10,
        width: "100%",
    },
    bocadillo: {
        backgroundColor: "white",
        padding: 10,
        borderRadius: 10,
        width: "80%",
        borderWidth: 2,
        borderColor: "black",
        shadowColor: "#000",
        shadowOffset: { width: 2, height: 2 },
        shadowOpacity: 0.3,
        shadowRadius: 2,
        elevation: 3,
    },
    textoContainer: {
        flexDirection: "row",
        alignItems: "center", // Mantiene el cursor alineado con el texto
    },
    texto: {
        fontSize: 18,
        textAlign: "left",
        flexShrink: 1, // Permite que el texto se ajuste sin afectar el cursor
    },
    cursor: {
        fontSize: 18, // Mismo tamaño del texto para evitar movimientos
        fontWeight: "bold",
        marginLeft: 2, // Espacio entre el texto y el cursor
    },
});

Y para utilizarlo haremos esto:

 <BocadilloTexto texto={"¡Hola, viajero!"} />

También podemos utilizarlo con el componente TextoAnimado animado que hemos creado en un tutorial anterior.

 <BocadilloTexto texto={<TextoAnimado texto="¡Hola, viajero!" />} />

Deja un comentario