React Typescript provides a convenient feature called the Automatic Typewriter effect, which

Currently, I am aiming to implement a captivating Typewriting effect using styled components, but encountering some obstacles in the process.

The approach involves defining two animations - one for character typing and another for caret blinking within the container element. By utilizing the :after pseudo-element with inline styling, I add the animated caret, while dynamically setting the text content and character count through JavaScript.

Incorporating properties like white-space: nowrap and overflow: hidden helps conceal excess content, although these styles seem ineffective within my application despite being correctly declared and applied inline.

App.tsx

import React from 'react';
import { Box } from '@mui/material';

const styles = {
    typewriterEffect: {
        display: "flex",
        justifyContent: "center",
        fontFamily: "monospace",
      },
      
      "typewriter-effect > text": {
        maxWidth: 0,
        animation: "typing 3s steps(var(--characters)) infinite"
        ...
        
      }
};

function Typewriter() {
    const typeWriter: HTMLElement | null = document.getElementById('typewriter-text');
    const text = 'Lorem ipsum dolor sit amet.';
    
    typeWriter.innerHTML = text;
    typeWriter.style.setProperty('--characters', text.length);
    ...
}

export {Typewriter};

Answer №2

I created a custom hook for the purpose of typing animation

export const useTypeWriter = (content = '') => {
    const [prevContent, setPrevContent] = useState(content);
    const [animatedContent, setAnimatedContent] = useState('');
    const hasContentChanged = prevContent === content;

    const generateContent = () => {
        setAnimatedContent((prevAnimatedContent) => {
            const charCount = prevAnimatedContent.length;
            if (prevAnimatedContent.length + 1 !== content.length) setTimeout(generateContent, 90);

            return prevAnimatedContent + content[charCount];
        });
    };

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

        setPrevContent(content);
        generateContent(content);
    }, [hasContentChanged]);

    return animatedContent;
};

To use this hook, you can do the following:

const typeWriterContent = useTypeWriter('Entire content')
return (<div>{typeWriterContent}</div>)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to display and conceal divs/sections by clicking on navigation bar buttons without utilizing javascript or JQuery?

As I work on coding a page for an assignment, I'm faced with the challenge of implementing a navigation bar with three sections: Business Plan, About Us, and Contact Us. While trying to incorporate clickable buttons using label and radio input element ...

Is there a more effective alternative to using the ternary condition operator for extended periods of time?

Do you know of a more efficient solution to handle a situation like this? <tr [style.background]="level == 'ALARM' ? 'violet' : level == 'ERROR' ? 'orange' : level == 'WARNING' ? 'yellow' ...

Using Vuetify to filter items in a v-data-table upon clicking a button

My table structure is similar to this, https://i.sstatic.net/56TUi.png I am looking to implement a functionality where clicking on the Filter Button will filter out all items that are both male and valid with a value of true. users = [ { name: &apos ...

A guide on sorting through categories in Angular 9

Having trouble filtering categories in a Webshop? I've been following a tutorial by Mosh but I can't seem to get it right. No error messages but nothing is being filtered or displayed. I'm brand new to Angular and/or typescript, so please be ...

Using object in TypeScript to reduce arrays

Is there a way to set the return value for my reducer in TypeScript? I am looking to achieve: Instead of using 'any', what should I assign as the type for acc? How can I define my return type so that the output will be {temp: 60, temp: 60}? retu ...

Having trouble getting indented Sass syntax to work with node-sass and gulp-sass?

With the introduction of Libsass 2.0, the indented syntax became available to libsass users. However, I have been facing issues trying to get it to work with node-sass and gulp-sass. Currently, all components are updated to their latest versions: node-sas ...

Tips for setting a fixed width on a Material-UI table cell to truncate the content

When displaying a Table of users with infinite scroll, I encountered an issue where the first column containing user names of varying lengths caused the table to jump in size as more users were added. To address this problem, I wanted to set a fixed width ...

Transferring JSON information from a dialog component to another component

In my application, I have 2 components named list and details, which are nested inside a parent component called customer. When the user clicks the delete button within the details component, a dialog window pops up like this: https://i.sstatic.net/hd4t3. ...

Tips on updating an object in Angular 2/4 without losing the reference

Here's my scenario: I have two instances, originalMember and toSaveMember, both belonging to the same class called Person. How can I update all the values from toSaveMember to originalMember, while still retaining the original reference of originalMem ...

Typing Redux Thunk with middleware in TypeScript: A comprehensive guide

I recently integrated Redux into my SPFx webpart (using TypeScript), and everything seems to be working fine. However, I'm struggling with typing the thunk functions and could use some guidance on how to properly type them. Here's an example of ...

Having difficulty with printing a particular div

I need help with printing a specific div containing checkboxes using jQuery. The checkboxes are initially checked based on data from a database, but when I try to print the div, the checkboxes remain unchecked in the print view. Below is the code snippet ...

The datatype 'string' cannot be assigned to the datatype '(token: string) => void'

Within my Angular2 application, I have a class that includes several properties which will be assigned values within components. @Injectable() export class Globals { private token: string; private authorization: string; private roleUser: boole ...

Customize default spacing in Material-UI theme according to different screen sizes

I am able to change the color but struggling to adjust the spacing. My goal is to reduce the spacing globally for mobile devices. const Styled = styled(Paper)(({ theme }) => ({ spacing: 50, color: '#ff0099', [theme.breakpoints.down(&a ...

Utilizing the power of Scoped CSS with Bootstrap/Bootstrap-Vue Integration

I'm currently working on a chrome extension and utilizing Bootstrap-Vue in my Vue files. I have imported bootstrap/bootstrap-vue into my js file, but the styling is being applied globally. Is there a way to scope the Bootstrap only onto specific inser ...

Issue TS2300: Redundant reference of 'Location' identifier

In my Location.ts file, there is a declaration: class Location { // ... } When I run tsc, it produces the following error message: 1 class Location { ../../../../usr/local/lib/node_modules/typescript/lib/lib.dom.d.ts:9249:11 9249 interface Lo ...

Is there a way to retrieve the chosen value from a select element?

How do I retrieve the chosen value from a select element? In my select.component.ts file: export class PfSelectComponent implements OnInit { constructor() { } ngOnInit() { } @Input() options : Array<Object>; } Contents of select.compon ...

Trouble with vertical drop-down navigation

I am currently working on adapting a horizontal desktop navigation menu to be responsive. I successfully changed it to display horizontally on smaller screens, but now I am facing an issue with the dropdown submenus covering the parent items below them. Wh ...

Toggle between two different global SCSS styles using a selector

I am in the process of upgrading my company's AngularJS project to Angular 8 using ngUpgrade. This has resulted in a hybrid application with components from both AngularJS and Angular. Additionally, I am utilizing an angular material template that inc ...

CodeBlast: A Kid's Game

I'm facing an issue with a puzzle called "A child's play" on Codingame. My coding language is typescript! The task is as follows: Recently, playful programming has become popular in elementary schools where students use assembly blocks to prog ...

Transform the X-th image using CSS nth transformation

I am currently working on developing a small game that involves using point icons, with some of them being overlaid on top of each other. My current approach is the following: .wormicon:nth-child(2) { transform: translateX(-50%); } .wormicon:nth-child ...