Tutorials

Create Recent Twitter Tweet Feed with React, Axios and PHP

Written by Kevin Liew on 27 Apr 2016
12,677 Views • Shares
0 comments

I have been reading up a lot of articles, tutorials and even video about ReactJS. It feels like I'm learning jQuery all over again.

There is no proper way or the official way to write React code. Since it's pretty new, there isn't a lot of resources as well. React's Getting Started introduction doesn't help much, it confuses me even more. Thankfully I found this - Andrew Ray's blog. Well, maybe I'm stupid, but his explanation does clear a lot of questions, especially React Flux. I will not go into explaining the ReactJS, if you're new, you should read these:

We're not going into Flux in this tutorial but just the some basic stuff and how to use it in actual website implementation.

Disclaimer: I'm nowhere near expert, I'm still in the learning stage, trying to code a way out of it. Just like what I did in the past with jQuery, I share everything I learn in Queness, and this time I will be sharing ReactJS. Hopefully, you would able to show me the right way to do it, or maybe I can show you something you don't know.

Alright, in this tutorial, I manage to put together a small application that retrieves Twitter Feed, parse it and display it. I reused many components from this tutorial, and port it into this tutorial.

HTML

This is so far the simplest markup, just a div with ID, this is where ReactJS will render the Twitter feed.

<div id="react-feed"></div>  

Javascript

Here's where all the actions begin. First of all, we retrieve the feed via Twitter OAuth api. You can see that we are calling tweets.php with Axios ajax call. I wrote a quick script that talk to Twitter and retrieve user tweents.

We are using Axios for ajax call. It's very similar with jQuery's $.ajax but much more lightweight and do exactly just the ajax call.

By placing the AJAX call in componentWillMount, we can ensure that we will get the data before the initial rendering occurs.

// get data ready before rendering
componentWillMount: function () {
  var t = this;

  // establish ajax call
  axios.get('tweets.php', {
    params: {
      screen_name: this.props.screen_name,
      count: this.props.count
    }
  })
  .then(function (result) {

    // set state with retrieved tweet data
    t.setState({
      tweets: result.data
    });
  });
},  

We also define an empty array to store the tweet data retrieved from ajax call.

// get ready an empty array for tweet data
getInitialState: function () {
  return {
    tweets: []
  }
},  

There are two helper functions called ify and timeAgo, well I didn't write them, it's code snippets from the Internet. That's why I didn't show the content in this post, you will see it in the source code.

ify will parse the hashtag, alias and url in tweet and convert them into links. timeAgo displays the tweet created datetime to e.g. 2 hours ago, 2 months ago format.

// an utility function to parse tweet's hashtag and link
ify: function (tweet)  {
  ...
},

// an utility function to display time 
timeAgo: function(dateString) {
  ...
},   

In render function, we use a loop to display each tweet. I'm not sure if that's the right way to do, but I have to use dangerouslySetInnerHTML to display the HTML text. dangerouslySetInnerHTML is intentionally named to be frightening to ensure we know what we're doing because improper use of the innerHTML can open you up to a cross-site scripting attack.

render: function () {   

  var th = this;

  return (
    <div>
      {this.state.tweets.map(function(tweet) {            
        return (
          <div key={tweet.id} className="tweet">                  
            <div dangerouslySetInnerHTML={th.ify(tweet.text)} />
            <div className="time">{th.timeAgo(tweet.created_at)}</div>
          </div>
        )
      })}
    </div> 
  )
}   

Finally, we render it to our document like this. It has two props:-

  • screen_name: Twitter account username
  • count: Number of tweets
ReactDOM.render(, document.getElementById('react-feed'))        

This is the overall structure:

var FeedApp = React.createClass({

  // get ready an empty array for tweet data
  getInitialState: function () {
    ..
  },

  // an utility function to parse tweet's hashtag and link
  ify: function (tweet)  {
    ...
  },

  // an utility function to display time 
  timeAgo: function(dateString) {
    ...
  },      

  // get data ready before rendering
  componentWillMount: function () {
    ...
  },

  render: function () {   
    ...
  }    
});

ReactDOM.render(, document.getElementById('react-feed'))      

PHP + Twitter API

For the details, I have explained it in this post - Create a Dead Simple Twitter Feed with jQuery

Conclusion

That's it, hopefully not too complicated. It works so I guess I cracked it. I could have split the looping part in render into another React class, but I decided to keep everything in one class just to make it simple. Stay tuned for next React tutorial.

Demo Download
Join the discussion

Comments will be moderated and rel="nofollow" will be added to all links. You can wrap your coding with [code][/code] to make use of built-in syntax highlighter.