React Hooks Typed.js Demo
by mattboldt
HTML
<script src="https://rawgit.com/mattboldt/typed.js/master/lib/typed.js"></script>
<link rel="stylesheet" href="https://rawgit.com/mattboldt/typed.js/master/assets/demos.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react-root">
</div>
CSS
/* Adding CSS manually is only necessary in JSFiddle,
where CSS can't be inserted into the <head> */
.typed-cursor{
opacity: 1;
animation: typedjsBlink 0.7s infinite;
-webkit-animation: typedjsBlink 0.7s infinite;
animation: typedjsBlink 0.7s infinite;
}
@keyframes typedjsBlink{
50% { opacity: 0.0; }
}
@-webkit-keyframes typedjsBlink{
0% { opacity: 1; }
50% { opacity: 0.0; }
100% { opacity: 1; }
}
.typed-fade-out{
opacity: 0;
transition: opacity .25s;
-webkit-animation: 0;
animation: 0;
}
Babel + JSX
const TypedReactHooksDemo = () => {
// Create reference to store the DOM element containing the animation
const el = React.useRef(null);
// Create reference to store the Typed instance itself
const typed = React.useRef(null);
React.useEffect(() => {
const options = {
strings: [
'Some <i>strings</i> are slanted',
'Some <strong>strings</strong> are bold',
'HTML characters × ©'
],
typeSpeed: 50,
backSpeed: 50,
};
// elRef refers to the <span> rendered below
typed.current = new Typed(el.current, options);
return () => {
// Make sure to destroy Typed instance during cleanup
// to prevent memory leaks
typed.current.destroy();
}
}, [])
return (
<div className="wrap">
<h1>Typed.js</h1>
<div className="type-wrap">
<span style={{ whiteSpace: 'pre' }} ref={el} />
</div>
<button onClick={() => typed.current.toggle()}>Toggle</button>
<button onClick={() => typed.current.start()}>Start</button>
<button onClick={() => typed.current.stop()}>Stop</button>
<button onClick={() => typed.current.reset()}>Reset</button>
<button onClick={() => typed.current.destroy()}>Destroy</button>
</div>
);
}
ReactDOM.render(
<TypedReactHooksDemo />,
document.getElementById('react-root')
);