DEV Community

anderu
anderu

Posted on • Updated on

Today i learn to build a lite version of Twitter - Twimba

Twimba screenshot

  • This project tutorial from Scrimba teach to use the data attribute so the 'reply', 'like' and 'retweet' to conditionally render the button styles according to post's uuid.
document.addEventListener('click', function(e){
    if(e.target.dataset.like){
       handleLikeClick(e.target.dataset.like) 
    }
    else if(e.target.dataset.retweet){
        handleRetweetClick(e.target.dataset.retweet)
    }
    else if(e.target.dataset.reply){
        handleReplyClick(e.target.dataset.reply)
    }
    else if(e.target.id === 'tweet-btn'){
        handleTweetBtnClick()
    }
})
Enter fullscreen mode Exit fullscreen mode
  • The combine of all button in document.addEventListener can gather all button to act accordingly to own function.
function handleTweetBtnClick(){
    const tweetInput = document.getElementById('tweet-input')

    if(tweetInput.value){
        tweetsData.unshift({
            handle: `@Scrimba`,
            profilePic: `images/scrimbalogo.png`,
            likes: 0,
            retweets: 0,
            tweetText: tweetInput.value,
            replies: [],
            isLiked: false,
            isRetweeted: false,
            uuid: uuidv4()
        })
    render()
    tweetInput.value = ''
    }
}
Enter fullscreen mode Exit fullscreen mode
  • User can tweet anything and handleTweetBtnClick() will form the data in object and push into database then only render out the tweet.
let likeIconClass = ''

        if (tweet.isLiked){
            likeIconClass = 'liked'
        }

<span class="tweet-detail">
                    <i class="fa-solid fa-heart 
                    ${likeIconClass}"
                    data-like="${tweet.uuid}"
                    ></i>
                    ${tweet.likes}
                </span>
Enter fullscreen mode Exit fullscreen mode
  • In the render function the part I want to highlight is the use of data-'attribute', example above show the 'like' button use the data-like and then condition is set up to check if the tweet.isLiked button clicked then 'liked' class will be add into ${likeIconClass} and like button will turn into red color.
import { v4 as uuidv4 } from 'https://jspm.dev/uuid';
console.log(uuidv4())
Enter fullscreen mode Exit fullscreen mode
  • Another thing to highlight is the use of CDNs example here is the UUID version 4. Just call the function of uuidv4() then we can get uuid accordingly which is easy to use and helpful.

Eat, sleep, code, repeat!
Andrew Tan

Top comments (0)