Skip to content

Instantly share code, notes, and snippets.

@bramses
Last active March 11, 2022 18:16
Show Gist options
  • Select an option

  • Save bramses/af87740e53df0d5a3cc2d41f51324b92 to your computer and use it in GitHub Desktop.

Select an option

Save bramses/af87740e53df0d5a3cc2d41f51324b92 to your computer and use it in GitHub Desktop.
A React Component to Tweet
/**
Usage:
<TweetHref slug="{url}">This will be the Tweet</TweetHref>
*/
import styled from 'styled-components';
// create a styled component called StyledA
// that is styled like an anchor tag
// with the font family of Work Sans
// with no text decoration
// with the color of #1DA1F2
const StyledA = styled.a`
font-family: "Work Sans", sans-serif;
text-decoration: none;
color: #1DA1F2;
`
export default function TweetHref({ children, slug }) {
if (!slug) {
// if there is no slug, throw an error
throw new Error('TweetHref component requires a slug prop')
}
// if the length of the children is greater than 220
if (children.length > 220) {
// throw an error
throw new Error('TweetHref component children must be less than 220 characters. Passed in: ' + children)
// otherwise
}
// encode the text to be tweeted
const encoded = encodeURI('\"' + children + '\"' + '\n\n');
const rootURL = ""
// return the styled anchor tag with the encoded text and the url to be tweeted
return (
<StyledA rel="canonical" href={`https://twitter.com/intent/tweet?text=${encoded}&url=${rootURL}/${slug}`} target="_blank" rel="noopener noreferrer">
{children}
[<em>click to tweet</em>]
</StyledA>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment