React Native Auto-Scrolling for Fun and Profit

Utilizing code to display your favorite stocks in a fun way.

Daniel Warrick
5 min readFeb 13, 2018
https://spin.atomicobject.com/wp-content/uploads/20171227202359/ReactNative.png

Time for another tutorial! This time, I’ll be using the React-Native library to design an animated scroll that shows real-time stock prices for tech companies. Let’s be honest, this sounds a bit boring. I was originally going to be mapping the prices for crypto-currencies but ran into some trouble with the CryptoCompare API (you can only grab one price at a time).

I promise though, this component has some fun applications that I’ll get into toward the end. With that being said, let’s get started!

First, we need to set up our directory. To do this, I’ll be using Create-React-Native-app.

cd myDirectory
create-react-native-app stock_ticker
cd stock_ticker
touch StockTicker.js

Let’s start by creating our component class in StockTicker.js:

import React from 'react';import { StyleSheet, ScrollView, Text, View, Dimensions } from 'react-native';const { width, height } = Dimensions.get('window');class StockTicker extends React.Component {
constructor(props) {
super(props);
this.state = {
currentPosition: 0,
stocks: [],
};
this.scrolling = this.scrolling.bind(this);
}
render(){
return(
<View></View>
); }
export default StockTicker;
https://iextrading.com/images/apps/iex-app-icon.png

Next, we can start declaring some functions to get our stock information from the IEX finance API. This API gives you an unlimited number of free requests. If you want to see the complete API, there’s a link at the end.

These will be the stock symbols we’ll be grabbing from the API. I just chose the top 50 tech stocks off the NASDAQ, but you can enter any stock you would like.

getSymbols() {
let stockSymbols = [
'AAPL', 'GOOGL', 'GOOG', 'MSFT', 'FB',
'TSM', 'INTC', 'ORCL', 'CSCO', 'NVDA',
'IBM', 'SAP', 'TXN', 'QCOM', 'ADBE',
'AVGO', 'DCM', 'CRM', 'AABA', 'BIDU',
'ITW', 'ATVI', 'AMAT', 'ADP', 'MU',
'VMW', 'CTSH', 'INTU', 'NXPI', 'INFY',
'EA', 'ETN', 'HPQ', 'ADI', 'NOK',
'FISV', 'DXC', 'LRCX', 'NOW', 'HPE',
'WDC', 'WDAY', 'WIT', 'TWTR', 'ADSK',
'SNAP', 'WPP', 'RHT', 'KYO', 'CERN',
]
return stockSymbols;
}

We can use these symbols by looping through the array, and concatenating each symbol with the GET request URL (delimited by commas).

async getStockObj() {    // Get symbols to send to API
let symbols = this.getSymbols();
// Add symbols to fetch query
let url = 'https://api.iextrading.com/1.0/stock/market /batch?types=price,company&symbols=';
for (let ctr = 0; ctr < symbols.length; ctr++) {
url += symbols[ctr] + ',';
}
// Make GET request
try {
let fetchResponse = await fetch(url);
let json = await fetchResponse.json();
// Convert json to array
let stocksArray = [];
Object.keys(json).map((key, index) => {
stocksArray.push(json[key]);
});
console.log(stocksArray);
// Store array in state
this.setState({ stocks: stocksArray });
}
catch (err) {
console.log(err);
}
}
https://s3.envato.com/files/46232615/Banner_SE3.jpg

At this point it’s good to double check we’re receiving our object. Upon calling this function, your terminal should be displaying an array of objects in the following format:

Object {
"company": Object {
"CEO": "",
"companyName": "Activision Blizzard Inc",
"description": "Activision Blizzard Inc is one of the largest console video game publishers, and Blizzard, one of the largest PC video game publishers. Its franchise gaming portfolio includes World of Warcraft, and Call of Duty worldwide.",
"exchange": "Nasdaq Global Select",
"industry": "Application Software",
"issueType": "cs",
"sector": "Technology",
"symbol": "ATVI",
"website": "http://www.activisionblizzard.com",
},
"price": 67.08,
}

We can start displaying this information by moving into our render() function. It should only be displaying our scroll if the API call is complete. Otherwise, the user should see a “Loading” screen.

render() {
// Render scrollview only if API call is complete
if (this.state.stocks.length > 1) {
return (
<View>
<ScrollView
style={styles.scrollview}
horizontal={true}
ref={(ref) => this.ticker = ref}
bounces={true}
>
{this.state.stocks.map((item, index) => (
// Display each stock's information
<View key={index} style={styles.view}>
<View style={styles.hr} />
<Text style={styles.text}>{item.company.companyName}
</Text>
<Text style={styles.text}>{item.company.symbol}
</Text>
<Text style={styles.text}>${item.price}</Text>
<View style={styles.hr} />
</View>
))}
</ScrollView>
</View>
);
}
// Display 'Loading' if API call hasn't yet finished
else {
return (
<View style={styles.view}>
<View style={styles.scrollview}>
<Text style={styles.text}>Loading...</Text>
</View>
</View>
);
}
}

The last function will handle our auto-scrolling feature by using the ScrollView’s ‘scrollTo’ method. By invoking this method within a setInterval, we can make the ScrollView constantly scroll to the left. To make it seem to repeat at the end of our list, we include a maxOffset variable. Once our function scrolls to this value, the ScrollView will jump back to position zero.

componentDidMount(){
this.activeInterval = setInterval(this.scrolling, 100);
}

Be sure to clear this interval when finished.

componentWillUnmount(){
clearInterval(this.activeInterval);
}

Call this in componentDidMount():

// Scrolling Animation
scrolling() {
// Start scrolling if there's more than one stock to display
if (this.state.stocks.length > 1) {
// Increment position with each new interval
position = this.state.currentPosition + 5;
this.ticker.scrollTo({ x: position, animated: true });
// After position passes this value, snaps back to beginning
let maxOffset = 20000;

// Set animation to repeat at end of scroll
if (this.state.currentPosition > maxOffset) {
this.ticker.scrollTo({ x: 0, animated: false })
this.setState({ currentPosition: 0 });
}
else {
this.setState({ currentPosition: position });
}
}
}

And that’s it! Here’s the final product:

That color scheme…

Earlier, I mentioned some possible applications. While I was testing this, the color scheme reminded me of something, and I couldn’t quite think of it until…

https://img.cinemablend.com/filter:scale/cb/e/f/9/7/7/e/ef977e8bdc9231ca6db169baac52161744bca8b0d34f99da8c73e0208712fb4f.jpg?mw=600

Basically, with a few quick fixes, this code could be repurposed as a Star Wars crawl generator. In order to do that, you would need to do the following:

  • Change ScrollView from horizontal to vertical
  • Change ‘toScroll’ function from x-offset to y-offset
  • Use currentPosition with some basic math to increment the font size
  • Ditch the stock API stuff and add your own text

Whatever way you decide to apply this, thanks for reading. Have fun, and keep coding!

Here is the complete code:

Further Reading:

--

--