Dynamic Twitch Link

Posted on November 24, 2019

I added a new dynamic twitch link to the website. When I'm not live on Twitch, it's just a normal link. When I go live it turns purple and gets a red "recording dot" next to it.

It's a pretty simple component, I'm super happy about it. Here's the source:

1import React, { useEffect, useState } from 'react';
2import fetch from 'isomorphic-unfetch';
3import styled from 'styled-components';
4
5const StyledTwitchLink = styled.a`
6 color: ${props => (props.isLive ? props.theme.palette.twitch : props.theme.palette.black)};
7 padding: 8px 16px;
8 display: block;
9 text-transform: uppercase;
10 font-size: 0.8em;
11 letter-spacing: -0.5px;
12 font-weight: 700;
13 text-decoration: none;
14 display: inline-flex;
15 align-items: center;
16 justify-content: center;
17 transition: color 0.25s ease-in-out;
18 &:visited {
19 color: ${props => (props.isLive ? props.theme.palette.twitch : props.theme.palette.black)};
20 }
21 &:hover {
22 color: ${props => props.theme.palette.twitch};
23 cursor: pointer;
24 }
25 &::after {
26 content: '';
27 width: 8px;
28 height: 8px;
29 border-radius: 50%;
30 display: ${props => (props.isLive ? 'block' : 'none')};
31 background-color: ${props => props.theme.palette.red};
32 margin-left: 4px;
33 }
34 @media screen and (max-width: ${props => props.theme.layout.mobileMaxWidth}) {
35 font-size: 1.6em;
36 padding: 16px;
37 }
38`;
39
40const TwitchLink = () => {
41 const [isLive, setLive] = useState(false);
42 useEffect(() => {
43 fetch('https://api.twitch.tv/helix/streams?user_login=TWITCH_USERNAME', {
44 headers: {
45 'Client-ID': 'YOUR CLIENT ID
46 }
47 })
48 .then(res => res.json())
49 .then(twitchData => {
50 if (twitchData.data.length > 0 && twitchData.data[0].viewer_count !== null) {
51 setLive(true);
52 }
53 });
54 }, []);
55
56 return (
57 <StyledTwitchLink href="https://twitch.tv/TWITCH_USERNAME" isLive={isLive}>
58 Twitch
59 </StyledTwitchLink>
60 );
61};
62
63export default TwitchLink;

Updated on November 27, 2019