Last active
December 18, 2018 17:21
-
-
Save alalfakawma/ab3cfb010039445599bba3569d24e26b to your computer and use it in GitHub Desktop.
Animated Typer component for React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Author: Aseem Lalfakawma<https://github.com/alalfakawma> | |
This component has 4 props - | |
- text: The text you want to have a typing animation (Default: 'This is a blinker component') | |
- textClass: Add class to text (Default: null) | |
- cursorBlinkSpeed: Cursor's blink speed in ms (Default: 500) | |
- typeSpeed: Speed of the typing (Default: 250) | |
- cursorClass: Add class to cursor (Default: null) | |
*/ | |
import React, { Fragment } from 'react'; | |
import PropTypes from 'prop-types'; | |
export default class Typer extends React.Component { | |
state = { | |
onScreen: [], | |
toBeDisplayed: this.props.text | |
} | |
constructor(props) { | |
super(props); | |
this.blinker = React.createRef(); | |
} | |
componentDidMount() { | |
const { current: cursor } = this.blinker; | |
// Run typer and blinker | |
setInterval(() => { | |
if (cursor.style.visibility === "hidden") cursor.style.visibility = ""; | |
else cursor.style.visibility = "hidden"; | |
}, this.props.cursorBlinkSpeed); | |
const blinkTime = setInterval(() => { | |
const onScreen = this.state.onScreen; | |
let splitString = this.state.toBeDisplayed.split(''); | |
onScreen.push(splitString.shift()); | |
this.setState({ | |
onScreen: onScreen, | |
toBeDisplayed: splitString.join('') | |
}); | |
// Stop typing when the full text has been displayed | |
if (this.state.toBeDisplayed.length === 0) clearInterval(blinkTime); | |
}, this.props.typeSpeed); | |
} | |
render() { | |
return ( | |
<Fragment> | |
<span className={ this.props.textClass }>{ this.state.onScreen.join('') }</span> | |
<span ref={ this.blinker } style={{ visibility: "hidden" }} className={ this.props.cursorClass }>|</span> | |
</Fragment> | |
); | |
} | |
} | |
Typer.defaultProps = { | |
text: "This is a blinker component", | |
cursorBlinkSpeed: 500, | |
typeSpeed: 250, | |
}; | |
Typer.propTypes = { | |
text: PropTypes.string.isRequired, | |
textClass: PropTypes.string, | |
cursorClass: PropTypes.string, | |
cursorBlinkSpeed: PropTypes.number, | |
typeSpeed: PropTypes.number | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment