Reputation: 151
I want to have a blink cursor in a ...
I wrote this code, but impossible for me to understand why it's not working.
const [cursor,setCursor]=useState<string>("");
function blink(){
if(cursor == '|'){
setCursor("")
}
else{
setCursor("|")
}
setTimeout(function(){ blink()}, 1000);
}
useEffect(() => {
blink();
}, []);
return (
<div>
<span>{text}</span><span>{cursor}</span>
</div>
);
};
Thanks in advance :)
Upvotes: 0
Views: 65
Reputation: 19947
function blink(){
if(cursor == '|'){
setCursor("")
}
else{
setCursor("|")
}
}
useEffect(() => {
setTimeout(blink, 1000); // <- move setTimeout to here
}, [cursor]); // <- and you need to pass cursor as a dep
Upvotes: 1
Reputation: 51756
Seems like you wanted this:
const [cursor, setCursor] = useState('');
useEffect(() => {
const handle = setInterval(() => {
setCursor(oldCursor => oldCursor === '|' ? '' : '|');
}, 1000);
return () => {
clearInterval(handle);
};
}, [setCursor]);
return (
<div>
<span>{text}</span><span>{cursor}</span>
</div>
);
Upvotes: 1