Skip to content

Instantly share code, notes, and snippets.

@iris-i
Created January 8, 2018 21:31
Show Gist options
  • Save iris-i/d13b727813b6e9ea4f839cadb132bcd7 to your computer and use it in GitHub Desktop.
Save iris-i/d13b727813b6e9ea4f839cadb132bcd7 to your computer and use it in GitHub Desktop.
React Marquee using CSS transform
import React from 'react';
import ReactDOM from 'react-dom';
class SimpleMarquee extends React.Component {
constructor(props) {
super(props);
this.state = {
textwidth: 0,
containerwidth: 0,
rate: 1
}
this.getElementWidth = this.getElementWidth.bind(this);
}
componentDidMount() {
this.setState({
textwidth: this.getElementWidth('ticker'),
containerwidth: window.innerWidth
});
}
getElementWidth(refId) {
let coords = ReactDOM.findDOMNode(this.refs[refId]).getBoundingClientRect();
return coords.width;
}
render() {
let width = this.state.textwidth > 1900 ? this.state.textwidth + 30: this.state.textwidth;
let container = this.state.containerwidth;
let speed = 10;
// formula is to: (Width of the text node + width of the main container / Width of the main container) * speed;
let duration = ((width + container)/container)* speed;
let style = {
animationDuration: `${duration}s`
};
console.log(`Text width is ${width}: Container width is ${container} duration is ${duration}`);
return (
<div className="marquee" style = {style}>
<p dangerouslySetInnerHTML={this.props.message} ref="ticker" />
</div>
);
}
}
export default SimpleMarquee;
@iris-i
Copy link
Author

iris-i commented Jan 8, 2018

Works but slightly WIP because the formula for calculating the animation duration dynamically needs fine-tuning. Rignt now the text does not scroll completely out of sight before re-scrolling.
Needs the CSS here to work: https://codepen.io/irisibk/pen/qpXaJz

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment