react-native-typewriter-effect
Version:
Typing animation library for React Native
52 lines • 1.94 kB
JavaScript
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Platform } from 'react-native';
import { Text, Vibration } from 'react-native';
const DEFAULT_MAX_DELAY = 100;
const DEFAULT_MIN_DELAY = 10;
export default function TypeWriterEffect(props) {
const {
content,
onTyped,
onTypingEnd,
minDelay = DEFAULT_MIN_DELAY,
maxDelay = DEFAULT_MAX_DELAY,
vibration = true,
backspaceEffect = false
} = props;
const initialIndex = backspaceEffect ? content.length : 0;
const [currentCharIndex, setCurrentCharIndex] = useState(initialIndex);
const timeoutId = useRef(null);
const delta = backspaceEffect ? -1 : 1;
const startTypeWriter = useCallback(ms => {
timeoutId.current = setTimeout(() => {
setCurrentCharIndex(currentCharIndex + delta);
if (vibration && Platform.OS === 'android') {
Vibration.vibrate(1);
}
}, ms);
}, [currentCharIndex, vibration, delta]);
const clear = () => {
if (timeoutId.current) {
clearTimeout(timeoutId.current);
timeoutId.current = null;
}
};
useEffect(() => {
setCurrentCharIndex(initialIndex);
}, [content, initialIndex]);
useEffect(() => {
clear();
const currentChar = content.charAt(currentCharIndex);
const nextChar = content.charAt(currentCharIndex + delta);
if (currentChar) {
onTyped === null || onTyped === void 0 ? void 0 : onTyped(currentChar, currentCharIndex);
}
if (!nextChar) {
onTypingEnd === null || onTypingEnd === void 0 ? void 0 : onTypingEnd();
return;
}
startTypeWriter(Math.round(Math.random() * (maxDelay - minDelay) + minDelay));
}, [onTyped, startTypeWriter, onTypingEnd, currentCharIndex, content, maxDelay, minDelay, delta]);
return /*#__PURE__*/React.createElement(Text, props, content.substring(0, backspaceEffect ? currentCharIndex : currentCharIndex + 1));
}
//# sourceMappingURL=index.js.map