cdcasey.dev

gatsbyhireactsite info

Adding Styling

A quick note about SEO: react-seo-component made everything super-easy.

I had grand plans of using Emotion to create a theme, but then somehow I stumbled on Typography.js. It made styling the site text as easy as adding the plugin to gatsby-config.js and pointing it to a file with the following line:

1const typography = new Typography(github);

Then it was time to add the ability to highlight individual lines. I figured out the solution when I realized that everything after the language modifier in the markdown files became part of a metastring prop that gets passed to the Code.tsx component from the MDXProvider. With that knowledge, I could modify Code.tsx to look for line numbers (with help of the parse-numeric-range library):

1export const Code = ({ codeString, language, ...props }: CodeProps): React.ReactElement => {
2
3...
4
5 const { metastring } = props;
6 let numbers: number[] = [];
7 numbers = rangeParser(metastring);
8
9...
10
11 return (
12
13...
14
15 let highlightClass = css``;
16 if (numbers.indexOf(i + 1) !== -1) {
17 highlightClass = css`
18 background-color: rgb(53, 59, 69, 0.9);
19 `;
20 }
21
22 let diffClass = css``;
23 if (firstToken.content.startsWith('+')) {
24 diffClass = css`
25 background-color: darkgreen;
26 `;
27 } else if (firstToken.content.startsWith('-')) {
28 diffClass = css`
29 background-color: darkred;
30 `;
31 }
32
33...

Then all I had to do was to add line numbers after the language for highlighting of individial lines, or att a + or - to make something look like a git diff. Not perfectly generalized, but good enough for my blog!

1```javascript 1-3,5
2<code snippet>
3+ git diff add
4- git diff remove
5```

It occurs to me that with line highlighting, I'll probably never use the git diff functionality. But it looks cool, so I leave it in. I now have a theme that I like, line highlighting, AND the copy button. Time to start publishing.

next: "More" Button for Gatsby

prev: Adding Images