Trying to implement ityped in a React app. The code shown below should work in JSX; however, this React app is written in Typescript (TSX), which is why it fails with a type error.
"Intro.tsx" component:
import React, { useEffect, useRef } from 'react';
import { init } from 'ityped';
import "./intro.scss";
export default function Intro() {
const textRef = useRef(null);
useEffect(() => {
init(textRef.current, {
showCursor: false,
strings: ['Web developer', 'Logo designer']
})
}, []);
return (
<div className="intro" id="intro">
<div className="left">
<div className="imgContainer">
<img src="assets/man.png" alt="" />
</div>
</div>
<div className="right">
<div className="wrapper">
<h2>Hi there, I'm</h2>
<h1>Andreas Petersen</h1>
<h3>A <span ref={textRef}></span> </h3>
</div>
<a href="#portfolio">
<img src="assets/down.png" alt="" />
</a>
</div>
</div>
)
}
My guess is that const textRef = useRef(null);
needs to be defined in a way, so that init()
from ityped can understand it correctly.
You'll need to do two things. First, like you guessed, you'll need to specify what sort of ref this is:
const textRef = useRef<HTMLSpanElement>(null);
Secondly, even with that type, textRef.current
can still be null as far as the types are concerned. So you either need to add code to your use effect to check for null:
useEffect(() => {
if (!textRef.current) {
return;
}
init(textRef.current, {
showCursor: false,
strings: ['Web developer', 'Logo designer']
})
}, []);
Or if you're confidant that you've made it impossible for it to be null after the first render (ie, you're unconditionally passing it into a component that will use it), you can use a non-null assertion (!
) to insist to typescript that you know it's not null:
useEffect(() => {
init(textRef.current!, {
showCursor: false,
strings: ['Web developer', 'Logo designer']
})
}, []);
Be aware that this second option means you're telling typescript not to check your work. If you make a mistake and it actually can be null, typescript can't tell you that, and you may get unexpected behavior at runtime.