<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/">
<channel>
<title><![CDATA[SEO - Rafael Quintanilha]]></title>
<description><![CDATA[Essays about software engineering, web development, artificial intelligence, quantitative analysis, financial markets, books and tradition.]]></description>
<link>https://rafaelquintanilha.com/topic/seo/</link>
<image><url>https://rafaelquintanilha.com/content/images/2022/12/Logo-Design--2-.png</url><title>SEO - Rafael Quintanilha</title><link>https://rafaelquintanilha.com/topic/seo/</link></image>
<lastBuildDate>Sun, 04 Dec 2022 23:59:57 GMT</lastBuildDate>
<atom:link href="https://rafaelquintanilha.com/topic/seo/rss/" rel="self" type="application/rss+xml"/>
<ttl>60</ttl>
<item>
<title><![CDATA[React Best Practices: How to Write Better React Apps]]></title>
<description><![CDATA[A summary of modern React best practices, with tips that can be applied to real-world applications.]]></description>
<link>https://rafaelquintanilha.com/react-best-practices-how-to-write-better-react-apps/</link>
<guid isPermaLink="false">6383c14a14168e003dd8f7a8</guid>
<category><![CDATA[React]]></category><category><![CDATA[SEO]]></category><category><![CDATA[Best Practices]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Wed, 07 Sep 2022 19:58:00 GMT</pubDate>

<content:encoded><![CDATA[<h2 id="what-is-react-and-why-use-it"><strong>What is React and why use it?</strong></h2>
<p>While web development isn’t <em>new</em>, some aspects of it are. In particular, frontend engineering is somewhat of a new term. Back in the day, you would see “web designers” and “webmasters”, but rarely <em>frontend developers</em>.</p>
<p>There’s a good reason for it - there was no need! Websites were simple, mostly static, and the bigger complexity was around designs, not functionality.</p>
<p>Needless to say, we are way past that now. Websites evolved into web apps, browsers became more powerful and the era of desktop applications is over, disrupted by the eruption of mobile devices. While it took some time for the consensus to establish in web apps and not in mobile apps, it seems to be fairly understandable now that web apps provide better availability, portability, and ease of use than native applications. And as mobile devices become more powerful, and optimizing for the web becomes a sexy engineering problem, the end result is an outburst of well-engineered, optimized, and resourceful applications right here, on the web.</p>
<p>But as we have learned from the history books, there’s no power vacuum. The web was set to reign, but who shall be the king? Enter <a href="https://reactjs.org/" rel="noopener noreferrer" target="_blank"><strong>React – a JavaScript library for building user interfaces</strong></a>.</p>
<p>This library maintained by the fine folks at Facebook took the market share and ended once and for all the <a href="https://medium.com/@ericclemmons/javascript-fatigue-48d4011b6fc4" rel="noopener noreferrer" target="_blank"><strong>JavaScript fatigue</strong></a>: that feeling everyone around in 2015 had. Every day a new frontend framework is competing for the top spot. Then eventually React appeared, people liked it, and the problem was settled.</p>
<p>This (not so) short introductory story is the answer to <em>what</em> React is and <em>why</em> you need it. Because React is a JavaScript library for the ever-growing frontend environment, you need it because it is popular, way maintained, liked, and used throughout the globe, in FAANGs and local shops. You can’t go wrong choosing React.</p>
<h2 id="what-makes-react-hard-to-learn-for-beginners"><strong>What makes React hard to learn for beginners?</strong></h2>
<p>React doesn’t have a particularly hard abstraction or technical conception. On the contrary, its single source of truth mantra has been a breeze for seasoned web developers.</p>
<p>However, this change in paradigm (for the better) can hit harder if you are used to using vanilla JavaScript or the last king, jQuery. Communication is rarely event-based, as opposed to what JavaScript typically enforces by design or with its backend counterpart, NodeJS.</p>
<p>Componentization is a concept that is easy to grasp but demands time to master. <a href="https://buttercms.com/blog/learn-react-hooks-by-writing-your-first-hook/" rel="noopener noreferrer" target="_blank"><strong>Hooks brought the functional flavor</strong></a> that seems to be the current trend, despite component lifecycles that may be more familiar to Java developers.</p>
<p>In short, what makes React hard for beginners is that <em>it is React</em>, not an adaption, a fork of a known framework, or an abuse of the JavaScript language. It’s a new paradigm, focused on User Interfaces, simplicity, and opinionated state management.</p>
<h2 id="react-best-practices"><strong>React best practices</strong></h2>
<p>Every language and framework has the so-called “best practices”, i.e., a community-accepted set of practices when using the tool. The following isn’t an exhaustive list of them, but an attempt to list the ones that typically concern the average developer.</p>
<h2 id="security"><strong>Security</strong></h2>
<p>Every software engineer that had code shipped to production had to go over this drill. Is the code secure? Are there flaws? Are they exploitable? Given the architecture of the web, this matter is even more flagrant.</p>
<p>However, I’d argue that React doesn’t pose any special security threat that any web application doesn’t have. Be aware of XSS attacks; store authentication tokens safely; sanitize HTML, and so forth.</p>
<h3 id="sanitize-html">Sanitize HTML</h3>
<p>By having its own <em>templating engine</em> that allows dynamic variables to be inserted into HTML, React exposes a security issue that every web developer should be aware of: injecting malicious code in HTML.</p>
<p>As the classical example goes, we don’t want users to pass any kind of script that can be rendered on an HTML page. Because of that, there’s a process called <em>sanitization</em>, where we allow only specific tags to be rendered on a page.</p>
<p>Imagine you have a CMS like ButterCMS and render the content generated by the content creator without any kind of filter. Well, <a href="https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml" rel="noopener noreferrer" target="_blank"><strong>React exposes the property</strong> <em><strong>dangerouslySetInnerHTML</strong></em></a> that serves this very purpose: get a raw HTML for an API, and render it in an element.</p>
<p>But the API isn’t named like that for nothing. Suppose this content contains a valid script that collects user information and posts it back to the attacker database: you’re essentially adding a trojan horse to your website!</p>
<p>In order to prevent such cases, you can use libraries like <a href="https://www.npmjs.com/package/sanitize-html" rel="noopener noreferrer" target="_blank"><strong>sanitize-html</strong></a> to allow only specific tags to be rendered. For example, if your goal is to render a blog post, you can allow only the traditional &#x3C;div>, &#x3C;p>, &#x3C;b>, &#x3C;i>, &#x3C;img>, etc tags, and block suspicious ones like &#x3C;script>.</p>
<h3 id="secure-apis">Secure APIs</h3>
<p>Although this isn’t a problem specific to React, this is a common problem faced by any front-end developer. We typically need to connect to our brothers in blood, the backend engineers, who have carefully crafted an interface for us to communicate.</p>
<p>However, this API often is <em>secured</em>, meaning that you need proper credentials to access it. The authentication process occurs mostly in the backend but is the front-end's job to keep the access token safe and sound.</p>
<p>There is a lot of <a href="https://stackoverflow.com/questions/3220660/local-storage-vs-cookies/3220802#3220802" rel="noopener noreferrer" target="_blank"><strong>debate about whether you should store it in the Local Storage or in cookies</strong></a>, and this matter warrants a post in itself. But while this is a personal choice and both can be used under the right circumstances, I find it crucial that you, as a developer, understand what the tradeoffs of each solution are.</p>
<p>I have used both, and suggest using cookies if you can. They provide more security layers and control, and if used with a compatible library in the backend, like <a href="https://flask-jwt-extended.readthedocs.io/en/stable/" rel="noopener noreferrer" target="_blank"><strong>Python’s Flask</strong></a>, the implementation is a breeze.</p>
<p>In any case, before judging your friend who stores a JWT in the Local Storage, try to understand where the flaw is. Saying “if your app JavaScript is compromised you are screwed” isn’t really an argument; once you’re compromised, well, you are screwed anyway. Understand your app’s needs first, and the rest should come naturally.</p>
<h3 id="install-linters">Install linters</h3>
<p>I mentioned before how good practices are nothing more than a community set of accepted practices, but as you have probably thought, this is subjective and hard to enforce.</p>
<p>Linters come to the rescue. There are awesome linters that will encapsulate a set of JavaScript or React-oriented best practices and complain whenever you drift off. This is great for ending an argument – people will often disagree on how to best handle a particular scenario. A linter, or a programmatic way to warn about an unexpected code usage, will act as the mighty judge, settling the matter once and for all (you need to agree on the linter first though).</p>
<p>Linters are also great for big teams, where many people touch a single file repeatedly. If everybody uses a linter, you cut off most of the inconsistencies, save development time and make reviewing code a breeze.</p>
<p>When coding, you shouldn’t focus too much on aesthetics. Sure, they are nice. But the less you need to worry about it, the better. Let developers focus on what they like, namely, code.</p>
<h2 id="testing"><strong>Testing</strong></h2>
<p>Think about that: you are already a developer, why would you do something manually? Programmers of course thought about that, and resisting the temptation of overengineering, also agreed on writing code for testing their own code. Isn’t it beautiful?</p>
<h3 id="leverage-react-debugging-utilities">Leverage React debugging utilities</h3>
<p>There are a set of React practices that are often neglected. <a href="https://reactjs.org/docs/error-boundaries.html" rel="noopener noreferrer" target="_blank"><strong>Error Boundaries</strong></a> are one of them.</p>
<p>When developing React applications, an interface is typically composed of several components in a tree that can escalate quickly. For that reason, if there’s an error in the application, it’s common to be lost in the hierarchy of components.</p>
<p>Error Boundaries can help you by raising the red flag on the exact node that experienced the flaw. More modern frameworks like <a href="https://buttercms.com/blog/what-is-react-remix/" rel="noopener noreferrer" target="_blank"><strong>React Remix</strong></a> leverage this concept to enhance user and developer experience. Give them a shot and caught the issues in the act.</p>
<p>Another way to add better-debugging tooling to your web app is to convert to TypeScript. Fortunately, TypeScript is widely adopted and integrated into the React ecosystem now. With TypeScript, you get top-notch auto-complete, caught errors on the act, and reduce runtime errors by leveraging features like type-checking. Pairing the typed JavaScript version with a good text editor like VSCode is a game changer for serious web development.</p>
<h3 id="invest-in-test-driven-development">Invest in test-driven development</h3>
<p>Beware when getting into the world of testing – you risk becoming addicted to it. In fact, some people like it so much that they develop backward! First, they create the test, <em>then</em> they write the code.</p>
<p>While this coding style isn’t for everyone, this is particularly interesting when developing a functional application or library. Suppose that you are working on a calculator. There are some well-defined cases that you want to handle, and it’s just fair that you work from there: you start by checking that addition works, then you move to multiplication, and handle edge cases.</p>
<p>For more complex applications, <a href="https://rafaelquintanilha.com/writing-tests-as-user-stories-in-react"><strong>I suggest treating your tests as user stories</strong></a>. Suppose you are working on a feature that needs to do X, Y, and Z. They are valid, strict metrics that you will be testing against. Once you established all the roadblocks, traps, and edge cases, it becomes way easier to just sit down and do what you already know.</p>
<p>Don’t know if this is for you? Well, <em>test</em> first, and then let me know (pun intended).</p>
<h3 id="install-react-testing-library">Install React Testing Library</h3>
<p>Everything I mentioned before about React taking over the power void can be applied to <a href="https://testing-library.com/docs/react-testing-library/intro/" rel="noopener noreferrer" target="_blank"><strong>React Testing Library</strong></a> or RTL. Designed for React and later adapted to other frameworks, the Testing Library took over hacky approaches like Enzyme, where developers would spend more time fixing tests than actually testing their applications.</p>
<p>React Testing Library has a simple API, a big community, and good principles, and should be your go-to library when unit testing your code.</p>
<h3 id="configure-user-events">Configure user events</h3>
<p>One of the main advantages of React Testing Library is abstracting away user events in single lines of code. For example: what if a user presses a specific key? Or if they move their mouse out of the window? Or focus on an input?</p>
<p>All those are events that can happen in a real app and oftentimes have a direct impact on what should happen next. For example, you can assert that a bouncing modal pops up if the user tries to leave the screen (it’s annoying but effective… what are you gonna do?). <a href="https://github.com/testing-library/user-event" rel="noopener noreferrer" target="_blank"><strong>A clear and simple API like the user events API</strong></a> from RTL is all you need in order to test like <em>user stories.</em></p>
<h2 id="components"><strong>Components</strong></h2>
<p>The heart of React, components are the best friend of the frontend developer. They encapsulate logic, UI blocks, and functionality. But how should you approach designing them?</p>
<h3 id="keep-component-creation-to-a-minimum">Keep component creation to a minimum</h3>
<p>Component creation should be understood as building a LEGO. You design the parts and glue them together. You start small, where each part is focused on its own job. It’s the UI equivalent to functional programming, where each function has a single purpose. In fact, components are functions! So the comparison holds even stronger.</p>
<p>When designing an interface, it’s often useful to draw it on a piece of paper. Using the same principle as in the test-driven approach, you have a <em>component-driven approach</em>. Start by designing your interface and what constitutes each part of it – maybe you have a side panel, a list of results in which every result has a call-to-action button… design them as an architect would design a living room, and the rest will flow naturally.</p>
<h3 id="introduce-state">Introduce state</h3>
<p>Using React for building user interfaces is nice, but if they are <em>static</em> there is nothing really exciting about them. Or at least nothing our predecessors, web designers, wouldn’t do with tools like Photoshop.</p>
<p>What transforms React into a really powerful library is its power to, well, <em>react</em> to users' interactions. That’s the heart and soul of frontend engineering – develop a nice UI, sure, but what good is a sleek-looking UI that isn't easy to use?</p>
<p>What solution does React brings to the table? The app or component <em>state</em> will dictate how your UI should behave. For example, it can display an error message for invalid input, disable a button for an incomplete form, share context and variables across many parts of the app, count how many times you have performed an action, tell whether you should render a modal or not… there are endless possibilities that are exactly the reason why frontend development is so exciting: the user input is a new dimension in your variable matrix.</p>
<p>A <em>stateful</em> component is a component that renders differently based on its state. An input component that renders an error message or is disabled is a good example. On the other hand, a <em>stateless</em> component is a plain static UI, but is still useful. Suppose you want to render your website footer. Instead of duplicating code left and right, you can develop it once and call it anywhere, pretty much like a function, generating one source of truth, best for maintainability and consistency.</p>
<h3 id="use-props-to-pass-data-to-a-children-component">Use Props to pass data to a children component</h3>
<p>Sometimes your component is not stateful but still depends on outside variables. Think about a template, for example. It has a recipe, a specific form, but with “gaps” that are dynamically filled (variables).</p>
<p>Properties, or props, are precisely a way to customize a component that should always behave the same but can accept different data. Think about your driving license: everyone has the same, they look the same, and their layout is the same, but the name, number, expiration date, and whatnot are different. Those are the props filling up the gaps.</p>
<p>In React, props are always passed from father to child. We saw already that componentization transforms your app into a huge tree of code, and the communication needs to be direct, and top-down (there are some exceptions like contexts, though).</p>
<p>While this can be annoying occasionally, it really gives predictability to your code. If a variable is such, it <em>must be</em> because it is like so in the parent. And hence you can trace back that value to its origin, helping to debug a lot.</p>
<p>I remember my old days working on CakePHP where I would spend hours trying to decipher where that variable had come from. It was hard because communication wasn’t direct, top-down. It was buried somehow in contexts and controllers. Call it pragmatic, but it will make your life easier.</p>
<h3 id="use-different-component-patterns">Use different component patterns</h3>
<p>As always, there is never one single way to tackle a problem. Before hooks took off on the 16th version of React, there was a famous React pattern called <a href="https://reactjs.org/docs/higher-order-components.html" rel="noopener noreferrer" target="_blank"><strong>HOC, or Higher-Order Components</strong></a>.</p>
<p>In this pattern, you encapsulate a particular component with another one, like a sandwich. But this gives it superpowers, or in less exciting terms, new props for it to use. For example, you could wrap your component in a HOC that would monitor the screen size in order to pass to your child component the width and height as props.</p>
<p>In some sense, Higher-Order Components worked as <em>decorators</em>, injecting logic into a given component. As mentioned, though, React Hooks was a great breakthrough and replaced this behavior with a nicer, more reusable API. Hooks work similarly to plugins, where you call them in your component to get a specific behavior.</p>
<p>Also before hooks, React components would be class-based, bringing more of the objected-oriented world to the frontend community. They would provide lifecycle hooks instead, where you could act when a specific event occurred, like the component mounting, or a specific prop changing.</p>
<p>The React team replaced this paradigm with a new one, using hooks, called <a href="https://reactjs.org/docs/hooks-effect.html" rel="noopener noreferrer" target="_blank"><strong>useEffect</strong></a>. Now, you can monitor everything that makes a component re-render, the act of being updated because something in the tree changed. It’s up to you to monitor and act accordingly to whatever state or prop change happened.</p>
<p>While more flexible, arguably some developers miss the straightness of <em>componentDidMount</em> or <em>componentWillUpdate</em>. If that’s who you are, you should check class-based components.</p>
<h2 id="styling"><strong>Styling</strong></h2>
<p>A hot topic with a myriad of alternatives, styling a web app is never a consensus. Constructed on top of a controversial piece of technology, we shall explore how you can approach styling in your React applications.</p>
<h3 id="try-inline-css">Try inline CSS</h3>
<p>The simples solution, by and large, is to embrace tradition and use an inline style like everyone was doing with HTML in the 90s. There’s nothing really wrong with it – with the exception that is hard to reuse.</p>
<p>React will handle style pretty much like a JSON object, and this will be the source behind the multiple CSS-in-JS frameworks that emerged. In any case, inline CSS is good, simple, and efficient. They will lack performance improvements (like being able to cache a separate CSS file), and maybe software engineering best practices. But they will work just fine.</p>
<h3 id="import-styled-components-as-an-object">Import styled-components as an object</h3>
<p>Using JavaScript to style your components has the unbeatable advantage of being able to control the style dynamically. Suppose you are building a component that changes its color based on a given input. JavaScript and React will make your life a breeze because you can just conditionally use the input to render the desired color.</p>
<p>Of course, people wouldn’t stop there: if you can use JavaScript in such cases, you can also use them to control other aspects of your styling. For example, font size, brand colors, default line height, etc. Using technology like <a href="https://www.styled-components.com/" rel="noopener noreferrer" target="_blank"><strong>styled-components</strong></a> allows you to write CSS-in-JS while creating a hierarchy of values that programmers so often like.</p>
<p>And as I mentioned before, the <em>style</em> property is nothing more than a JSON object. So you can leverage JavaScript constants to build your style schema, inherit from it, and write your component’s style as you would write code. Neat.</p>
<h3 id="abstract-style-components">Abstract style components</h3>
<p>Styles are good and a simple solution, but as a project grows it won’t scale. Think about how many primary buttons you have in your application and you will know what I mean.</p>
<p>As I mentioned in the previous section, styled-components help you to create a basic structure and build from there, with basic properties being set as constants. You can then combine them and create more complex structures, like buttons, paragraphs, headers, heroes, inputs, and so on.</p>
<p>In fact, React creates the perfect ecosystem for you to design your own component library. Forget about Bootstrap, Semantic UI, and their peers – with React, you please any designer you work with consistency and accuracy.</p>
<h3 id="use-css-and-sass-stylesheets">Use CSS and SASS stylesheets</h3>
<p>Everything I said thus far is great but some freaks insist on using plain old CSS files. Why? Well, I can tell (I’m one of those freaks). CSS is a technique on its own, and I prefer the separation of concerns of having a file dedicated to styling. It’s easier to review, change and adapt. Also, it can be cached when performance is at stake.</p>
<p>With the surge of frameworks that allow CSS Modules, the typical problem of classes clashing with each other is over. Plus, it generates a fingerprint that helps developers debug by targeting the precise component with that particular style.</p>
<p>And if you want the option to add parameters to your classes, like a brand color or semantic font size, SASS can help you. Pair both and you will get the best of two worlds, while still looking cool by using a time-tested fool-proof technology like cascading stylesheets.</p>
<h2 id="project-structure"><strong>Project structure</strong></h2>
<p>React is definitely not an opinionated library. As Uncle Ben would recall, “with great powers come great responsibilities”. I would also say, in a poetic tone, that you are free to do whatever you want, but a prisoner of the consequences.</p>
<p>With that in mind, let us take a look at how you can structure your React project.</p>
<h3 id="split-components-into-separate-tsx-files">Split components into separate .tsx files</h3>
<p>We already mentioned the power of componentization and treating components as you would treat functions in a functional paradigm. But in React this is even better if you enforce that only one component should exist per file.</p>
<p>First, files become smaller, and easier to tweak and review. Secondly, the <em>separation of concerns</em> buzzword rings again. By having a single file handling a single part, it’s very easy to spot and tackle eventual changes. Finally, if working on a larger team, will reduce conflicts and make collaboration a breeze.</p>
<h3 id="give-each-component-single-responsibilities">Give each component single responsibilities</h3>
<p>I’m a big fan of small, self-contained files, functions, and components. Think of them as small building blocks that are combined and used to create something bigger, like the pyramids, or a computer processor.</p>
<p>By assigning single responsibilities to each component, you are essentially functioning as a factory, with ultra-specialized employees that handle one thing and that thing only. Therefore, if <em>X</em> goes south, you know immediately that you need to talk with the one responsible for <em>X</em>. If each component has a single responsibility, it follows that it must exist only one component for it.</p>
<p>Combine multiple components with single responsibilities and you get your own production line.</p>
<h3 id="group-files-by-structures-or-routes">Group files by structures or routes</h3>
<p>We have already learned that React won’t enforce any file structure. Some people will circumvent this freedom but enforcing their own strict rules. I disagree. I believe React is better experienced if you leverage this freedom.</p>
<p>I explain: a successful folder structure is one you don’t need to think about. Frankly, the less you need to think about those petty things, the better. On that note, I like to group files <em>semantically</em>, or when they belong to a specific chunk of the app.</p>
<p>Have a route that renders a specific view? Add all your components there. Created a new page? Create also a new folder and add the corresponding components there as well. Simples structure. Not much thought is needed.</p>
<p>I oftentimes see people trying to be smart and breaking down components in multiple folders, with technical characteristics attached to them, like calling them <em>atomic</em>. I don’t like it. This means creating a new file or folder is no longer a no-brainer, and should be actively reviewed at the expense of having inconsistent file structures across the board. If you don’t care about the inconsistencies, then why create a rule in the first place? Moreover, you really don’t gain much (if anything) by adding a custom file structure to your projects. Developers aren’t supposed to be navigating in folders anyway. Components are small and self-contained, which means you potentially have a lot of files, so what’s the use of manually looking for them? Hence my proposal: group files by routes or pages, and forget about it.</p>
<h3 id="avoid-too-much-nesting">Avoid too much nesting</h3>
<p>React is a big tree of components as discussed, and this is fine. However, if you are nesting too much, you probably are doing it wrong.</p>
<p>There are so many levels that you can descend. You have a list, a CRUD, a modal… you can’t nest forever. If possible, favor the horizontal spread of components, in its own routes, shallow enough that you are not lost in the abstraction and easy enough for a developer to find his or her way through the code.</p>
<h2 id="using-react-with-a-headless-cms"><strong>Using React with a headless CMS</strong></h2>
<p>React is a library for building user interfaces, as we have seen. But it has some interesting integrations. For example, you might want to have your app’s content set somewhere else but render it in your shiny, fast, and efficient React app.</p>
<p>For such cases, content management systems like ButterCMS are a breeze. I spoke already about the separation of concerns, but this isn’t only related to code. In fact, the more you can separate areas of expertise, leaving people to their bread and butter, the better.</p>
<p>If you have a team of content creators, you can give them the freedom to put their creativity to work, generating content that will later be consumed and rendered in your application. Your developers shouldn’t need to have additional work if content changes – the own project structure should be able to do it.</p>
<p>Connecting a CMS provider with a React framework like GatsbyJS will empower you to do exactly that – <a href="https://buttercms.com/blog/leveraging-gatsby-incremental-builds/" rel="noopener noreferrer" target="_blank"><strong>connect to the content being generated, listen to changes, and rebuild your site with fresh content</strong></a>.</p>
<p>Server-side rendering applications like NextJS will also be valuable by fetching data from the CMS and serving to the user as requested.</p>
<p>In short, the JavaScript ecosystem for content management has evolved to the point where having blazing-fast, <a href="https://buttercms.com/blog/react-seo-how-to-build-search-friendly-pages-in-react/" rel="noopener noreferrer" target="_blank"><strong>SEO-friendly web apps</strong></a> can be achieved with both great content and developer experiences.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[React SEO: How to Build Search-Friendly Pages in React]]></title>
<description><![CDATA[How to boost your React app SEO ranking with many practical tips.]]></description>
<link>https://rafaelquintanilha.com/react-seo-how-to-build-search-friendly-pages-in-react/</link>
<guid isPermaLink="false">6383abfb14168e003dd8f748</guid>
<category><![CDATA[React]]></category><category><![CDATA[SEO]]></category><category><![CDATA[Best Practices]]></category><category><![CDATA[ButterCMS]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Thu, 21 Jan 2021 18:27:00 GMT</pubDate>

<content:encoded><![CDATA[<p>Digital advertising is a multi-billionaire industry that has been rising sharply. In fact, the money spent worldwide on it has <a href="https://www.statista.com/statistics/237974/online-advertising-spending-worldwide/" rel="noopener noreferrer" target="_blank"><strong>nearly doubled</strong></a> since 2016. The motive for this is clear: companies want to be seen on the Internet.</p>
<p>On the one hand, you can pay a large number of dollars to have your ad featured; on the other hand, you can be seen for free. That’s due to SEO, or Search Engine Optimization. Attracting organic traffic to your website is one of the most profitable actions a business can take, and this is by no means a trivial thing to achieve.</p>
<p>In this article, I’ll guide you on how to build SEO-friendly pages using React, the most popular framework for building modern websites. I'll also show you how these methods can be applied to dynamic content with the help of a <a href="https://buttercms.com/react-cms/" rel="noopener noreferrer" target="_blank"><strong>good React CMS</strong></a>.</p>
<h2 id="the-importance-of-seo"><strong>The Importance of SEO</strong></h2>
<p>Google owns 92% of the search engine market share worldwide and this number has been fairly <a href="https://gs.statcounter.com/search-engine-market-share#yearly-2009-2020" rel="noopener noreferrer" target="_blank"><strong>steady since 2009</strong></a>. It makes sense, then, to target Google and what it considers good practice when developing your SEO strategy.</p>
<figure class="image"><img alt="Search Engine Market Share (2020)" loading="lazy" decoding="async" width="1200" height="628" src="https://rafaelquintanilha.com/_astro/react-seo-search-engine-market-share.iKYtaES7_ZePX6C.webp"><figcaption>Search Engine Market Share (2020)</figcaption></figure>
<p>The core concept is that the higher your website ranks on the Search Results Page (SERP), the higher the likelihood that users will click on it. While this is fairly intuitive, what might surprise you is how large the gap is in click-through rates (CTR) in the first positions — <a href="https://www.smartinsights.com/search-engine-optimisation-seo/seo-analytics/comparison-of-google-clickthrough-rates-by-position/" rel="noopener noreferrer" target="_blank"><strong>recent studies</strong></a> have found that the combined click-through rates for positions 1 and 2 on a SERP are approximately double the combined click-through rates for positions 3 and 4! In other words, your effectiveness in being seen is exponentially affected by how well you fare on the results page.</p>
<h2 id="how-google-ranks-your-website"><strong>How Google Ranks Your Website</strong></h2>
<p>Before we learn how to enhance React SEO, we must understand how the process works. Simply put, Google uses a bot called Googlebot (how creative!) to crawl your application. This robot is called a <em>web crawler</em>.</p>
<p>The crawler will load your application, analyze it, and rank it by a set number of criteria. While exactly how each criterion is evaluated is unknown, one should target as many features as possible. An application optimized for SEO will enforce some rules to increase the likelihood of being highly ranked.</p>
<figure class="image"><img alt="Meta tags" loading="lazy" decoding="async" width="1146" height="584" src="https://rafaelquintanilha.com/_astro/react-seo-meta-tags.zMQ_VCok_Z2vb5iD.webp"><figcaption>Meta tags</figcaption></figure>
<h3 id="crawling-budget">Crawling Budget</h3>
<p>We live in an era of limited resources, and this will always be true. The same concept applies to search engines and their crawlers — they need to spend their time wisely. The result of this policy is what is called a <em>crawling budget</em>, or how much time a crawler will spend analyzing your website. As you might guess, how efficiently Google will parse your application is severely impacted by your app speed. Any effort to improve load time is welcome, which can become a problem for React apps.</p>
<h3 id="accessible-urls">Accessible URLs</h3>
<p>It is imperative for React SEO to have an SEO-friendly URL. In Google’s words: <em>“URLs with words that are relevant to your site's content and structure are friendlier for visitors navigating your site.”</em> The full set of <a href="https://developers.google.com/search/docs/beginner/seo-starter-guide?hl=en&#x26;visit_id=637438582413772187-2328543862&#x26;rd=1#best-practices_6" rel="noopener noreferrer" target="_blank"><strong>best practices can be seen here</strong></a>. This factor turns out to be one of the major problems with Single Page Applications (SPA), such as regular React applications. Once SPAs are evaluated on the client side, the whole application can live within a single URL.</p>
<p>Several other factors affect React SEO. However, the above are the most flagrant shortcomings of a React application and will be the object of discussion for the next sections.</p>
<h2 id="react-seo-the-problem-with-react-applications"><strong>React SEO: The Problem with React Applications</strong></h2>
<p>So far we have learned that search engines use robots called crawlers to parse your website and rank them accordingly in their SERP. Unfortunately, several of the aspects that are valuable to search engines are not found in standard React applications. We will now analyze what exactly React’s limitations are and, later on, learn how we can overcome them.</p>
<h3 id="static-vs-dynamic-sites">Static vs Dynamic Sites</h3>
<p>Back in the day, all web pages were called <em>static.</em> The process is as follows: the user makes a request to a server for a given URL. The server then returns a set of HTML, JavaScript, and CSS files that are served on-demand and rendered on the user’s browser.</p>
<p>This old-fashioned process is ideal for robots — they have all assets for that web page when they access it. However, things changed and web applications became more complex. The content is many times <em>dynamic</em>, meaning that it changes constantly. Think about your Twitter feed: all content is in constant motion, even though the URL remains the same.</p>
<p>Dynamic content is a problem for crawlers once the data might not be available during their crawling time (remember the crawling budget?). Also, it is loaded via JavaScript, meaning the browser needs to <em>render</em> and <em>parse</em> the code before anyone can see anything. This substantially increases the time a crawler needs to parse the content, hence affecting your SEO.</p>
<h3 id="how-spas-work">How SPAs Work</h3>
<p>As mentioned before, React is a Single Page Application. This means that your whole app lives on a single page, even though you can simulate different routes and pages.</p>
<p>While SPAs are very convenient for dynamic applications, they lack good SEO support. For starters, if all you have is a single page, your meta tags will hardly describe accurately each part of your application. Moreover, you won’t be able to generate unique URLs out-of-the-box, resorting to a <em>client-side routing</em> library like <a href="https://reactrouter.com/" rel="noopener noreferrer" target="_blank"><strong>react-router</strong></a>.</p>
<p>And finally, an SPA is a single webpage where JavaScript is responsible for updating the content on the screen. That usually means that the JavaScript code is bulky, which leads to a higher parse time by the browser. Ultimately, your application will load slower (due to the time needed to download + parse a larger JavaScript file) and your crawling budget will run out quickly.</p>
<p>It all looks like React applications are doomed to rot on the dark corners of the SERP, but it doesn’t need to be that way. Next, we will learn how to overcome the aforementioned issues.</p>
<h2 id="server-side-rendering"><strong>Server-Side Rendering</strong></h2>
<p>Server-side rendering (SSR), also known as <em>isomorphic applications</em>, is a clever solution to the SPAs shortcomings.</p>
<p>In order to avoid the single page with bulky JavaScript, the React community evolved to a model where the application is rendered on the server during <em>build time</em>. That means that instead of sending a large JavaScript file to the client and letting it figure out what to render, a compiler will analyze the code on the server and generate multiple pages. These pages will then be served on their specific routes, in the good ol’ static website model.</p>
<p>The advantage of such a model is that you can keep working with a cutting-edge library such as React and still retain the biggest advantage of static websites — blazing-fast load times!</p>
<p>However, it is a product decision to understand if SSR is ideal for your project. As a rule of thumb, if your application has content that changes <em>too</em> often, client-side applications should be the best option. Now, if your content is mostly static, and you have many web pages that would benefit from being found on a search engine (such as a product landing page or a blog post), SSR is the way to go.</p>
<h2 id="implementing-an-ssr-application-in-react"><strong>Implementing an SSR Application in React</strong></h2>
<p>The most famous frameworks for developing SSR applications are <a href="http://gatsbyjs.com/" rel="noopener noreferrer" target="_blank"><strong>Gatsby</strong></a> and <a href="https://nextjs.org/" rel="noopener noreferrer" target="_blank"><strong>Next.js</strong></a>. Although there are differences between them, their main goal is similar: to allow next-generation web applications to remain blazing-fast.</p>
<p>It is beyond the scope of this article to compare both technologies, but I will use Gatsby as an example of how the framework addresses the React SEO dilemma.</p>
<h3 id="react-helmet">React-helmet</h3>
<p><a href="https://github.com/nfl/react-helmet" rel="noopener noreferrer" target="_blank"><strong>React-helmet</strong></a> is the industry standard for meta tags optimization. It allows every page to have its own custom meta tags, what we have seen is a major victory for React SEO. The library also allows for the addition of <a href="https://ogp.me/" rel="noopener noreferrer" target="_blank"><strong>Open Graph</strong></a>, which directly impacts the shareability of your content on potentially highly viral spaces such as social networks.</p>
<figure class="image"><img alt="React Helmet SEO plugin" loading="lazy" decoding="async" width="906" height="309" src="https://rafaelquintanilha.com/_astro/react-helmet-react-seo-plugin.DD9nj6S2_Z1fHjqM.webp"><figcaption>React Helmet SEO plugin</figcaption></figure>
<p>Fortunately, Gatsby provides a wide set of plugins that can be used to simplify your life as a developer. The <a href="https://www.gatsbyjs.com/plugins/gatsby-plugin-react-helmet/" rel="noopener noreferrer" target="_blank"><strong>gatsby-plugin-react-helmet</strong></a> repository is one of the most used and widely maintained plugins in the ecosystem.</p>
<p>If you haven’t tried it already, <a href="https://www.gatsbyjs.com/tutorial/seo-and-social-sharing-cards-tutorial/#reach-skip-nav" rel="noopener noreferrer" target="_blank"><strong>this comprehensive tutorial</strong></a> will help you get up on your feet with Gatsby and react-helmet.</p>
<h3 id="gatsby-image">Gatsby-image</h3>
<p>We have repeatedly insisted on how harmful to your React SEO score large JavaScript files are. However, I have never found a potential performance threat as strong as images.</p>
<p>Developers often optimize too much of what is in their control — dependencies, code splitting, etc. But many overlook that a large image loaded on your website can severely impact its performance. While code is under control, static assets are often not. They are provided by content creators, marketers, authors, and others. Therefore, we need a plan to mitigate the potential impacts.</p>
<p>My favorite solution for this problem is <a href="https://www.gatsbyjs.com/plugins/gatsby-image/" rel="noopener noreferrer" target="_blank"><strong>gatsby-image</strong></a>, another plugin meant to save your life. Gatsby-image takes care of, among several other things, optimizing your images and serving them in the most efficient and responsive format. It enhances the look and feel of your app, not to mention the performance and ultimate SEO gain.</p>
<h3 id="other-plugins">Other Plugins</h3>
<p>Gatsby has a <a href="https://www.gatsbyjs.com/plugins" rel="noopener noreferrer" target="_blank"><strong>vast library of plugins</strong></a>. Many of them are zero-config, meaning that you gain React SEO without much more effort than an <em>npm install</em>. As an example, <a href="https://www.gatsbyjs.com/plugins/gatsby-plugin-sitemap" rel="noopener noreferrer" target="_blank"><strong>gatsby-plugin-sitemap</strong></a> will generate sitemaps for your web page, helping bots to crawl your content in the right way.</p>
<figure class="image"><img alt="Gatsby Plugin Library" loading="lazy" decoding="async" width="1228" height="767" src="https://rafaelquintanilha.com/_astro/gatsby-plugin-library.lIQC1Oxu_1n8NW8.webp"><figcaption>Gatsby Plugin Library</figcaption></figure>
<h3 id="route-based-code-splitting">Route-based Code Splitting</h3>
<p>Another great feature of Gatsby is the ability to serve static pages in their own URL (thus addressing the <em>Accessible URLs</em> point) and be wise about what should be included in that particular page.</p>
<p>Remember how SPAs are penalized by having large chunks of JavaScript being loaded at all times? With route-based code splitting, the only JavaScript code sent from the server to the client will be necessary to render whatever is on that particular page. <a href="https://www.gatsbyjs.com/blog/2019-04-02-behind-the-scenes-what-makes-gatsby-great/#route-based-code-splitting" rel="noopener noreferrer" target="_blank"><strong>The following article describes in detail</strong></a> how it works.</p>
<h3 id="do-i-need-a-static-site-generator">Do I Need a Static Site Generator?</h3>
<p>By all means, every advantage listed in the previous topics can be achieved with vanilla JavaScript and other tools. However, <a href="https://buttercms.com/blog/6-of-the-best-static-site-generators-in-2020/" rel="noopener noreferrer" target="_blank"><strong>SSGs like Gatsby and Next.js</strong></a> will abstract the hassle from you to the point that the standard Gatsby application is born with a 100 SEO score on <a href="https://developers.google.com/web/tools/lighthouse" rel="noopener noreferrer" target="_blank"><strong>Lighthouse</strong></a>, Google’s performance analyzer.</p>
<p>More than recommending framework A or B, the goal of this post is to outline the importance of SEO, the shortcomings of barebone React applications, and which tools can be used to overcome them. Don’t feel pressured to switch and adopt a new technology tomorrow — but be aware that different businesses have different needs and it is your job to find the right tool.</p>
<h2 id="static-sites-can-be-dynamic"><strong>Static Sites Can Be Dynamic</strong></h2>
<p>The last point worth mentioning is that, in fact, static sites can have dynamic content. Yes, I know I said before that they are two different kinds of applications, but bear with me for a moment.</p>
<p>If you opt for a Server Side Rendering strategy, your deployment process will include a <em>building time</em>. During this period, the framework will fetch the most up-to-date data available and construct the static page. That means that the <em>source</em> of data can constantly be changing!</p>
<p>This ends up being one of the main advantages of such a process, given that it allows the leverage of a <a href="https://buttercms.com/blog/what-is-headless-cms/" rel="noopener noreferrer" target="_blank"><em><strong>headless CMS</strong></em></a> such as ButterCMS. Using this strategy, you can have your Gatsby application connected to ButterCMS and fetch all content from an external admin panel. The main advantage is the possibility to offload the need to constantly edit static content onto professionals better suited for such actions, like marketers and copywriters.</p>
<p>Every time a change is made to static content, or in defined intervals, a new build will be triggered, and once it is finished your content will be updated. The process is highly SEO-friendly and, when properly designed, will allow content creators to choose the best features for the web crawler carefully.</p>
<p>ButterCMS is a leading <a href="https://buttercms.com/gatsbyjs-cms/" rel="noopener noreferrer" target="_blank"><strong>Gatsby CMS</strong></a>, and you can set up the integration with your Gatsby application in minutes!</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[Adding a Blog Into an Existing Site]]></title>
<description><![CDATA[A guide for CMS integration with ButterCMS.]]></description>
<link>https://rafaelquintanilha.com/adding-a-blog-into-an-existing-site/</link>
<guid isPermaLink="false">63704b9442a473003d9dc9f3</guid>
<category><![CDATA[React]]></category><category><![CDATA[ButterCMS]]></category><category><![CDATA[SEO]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Thu, 06 Jun 2019 03:00:00 GMT</pubDate>

<content:encoded><![CDATA[<p>Consider the following scenario: you have a fully-functional website, and you want to add a blog to it. The problem: you haven’t previously accounted for this, and you start wondering what the best solution may be that won’t require a major rewrite of your working app.</p>
<p>Perhaps your website is instead still under development, but all solutions for adding blogging functionality seem difficult to fit in your current stack.</p>
<p>Sound familiar?</p>
<p>You may be a good candidate for CMS (Content Management System) integration for your app or website. CMS integration is simply taking your existing website/web app and integrating a Content Management System with it <em>without</em> having to resort to a complex monolithic solution like WordPress. It is the degree of freedom you are looking for in order to keep your tech stack of choice and still be able to enjoy the best of what a Content Management System can offer.</p>
<p>In other words, <strong>CMS integration is how to add CMS capabilities into an existing website</strong>. This article aims to explain more of it in practice, what the pain points are, how to solve them, and how you can efficiently add a CMS into your current project without needing to rewrite everything from scratch.</p>
<h2 id="challenges-of-cms-integration">Challenges of CMS Integration</h2>
<p>Traditional CMS solutions, like WordPress, have historically evolved into whole solutions controlling everything for your app or website. It means that your app will most likely live as a “monolith”, a single unit of technology that is supposed to control the entirety of your website.</p>
<p>This might be fine until it isn’t anymore. Suppose you grow tired of WordPress and want to change the CMS provider. After all, you are likely to encounter scalability issues with a monolithic solution as it grows. You now have a problem, as you will need to rebuild core parts of your app that might not even be related to the CMS. Or maybe you are an experienced developer who likes to write web apps using your preferred tech stack, but requires an easy interface for non-technical content creators and editors to be able to add and edit content without needing you to update code.</p>
<p>Historically, CMS solutions are tightly coupled to the app. You can minimize the impact of an eventual change in the future by early planning, but the reality is that you won’t always be able to foresee the need for it - and even if you do, current approaches are just suboptimal, as we will see next.</p>
<h3 id="the-subdomain-approach">The Subdomain Approach</h3>
<p>A way to circumvent the constraints imposed by a monolith solution is to move your blog to a different subdomain, such as <strong>blog</strong>.example.com. By doing this you can set up your CMS and still keep your favorite tech stack. For example, you might have a website built with Angular + NodeJS and install a WordPress blog in another subdomain.</p>
<p>While this works there are some caveats with this approach:</p>
<ol>
<li><strong>SEO</strong>. The main issue is that setting up your blog under a subdomain <a href="https://buttercms.com/blog/blog-subdomain-or-subdirectory-hint-one-is-40-better" rel="noopener noreferrer" target="_blank">can negatively impact your SEO</a>. For content that depends on organic searches, this is very undesirable.</li>
<li><strong>UI consistency</strong>. You will be tasked with the extra work of maintaining a consistent UI for two separate apps, so you don’t confuse your users. As naive as it is, consider the case where you have developed a layout for your web app and now need to find (or develop) a WordPress theme that resembles it.</li>
<li><strong>Multiple apps overhead</strong>. instead of one, you will have two applications to maintain. In the long run, this may cause a lot of headaches.</li>
</ol>
<h3 id="the-subdirectory-approach">The Subdirectory Approach</h3>
<p>An alternative to subdomains is to use subdirectories. In fact, subdirectories mitigate the major issues presented by subdomains. First, <a href="https://buttercms.com/blog/blog-subdomain-or-subdirectory-hint-one-is-40-better" rel="noopener noreferrer" target="_blank">they are SEO friendly</a>. Also, they are still part of the same app, just installed in a different directory. This structure softens the multi-app and multi-UI overhead.</p>
<p>The problem is that setting a CMS in a subdirectory can be technically challenging. It is definitely non-trivial to orchestrate everything together. A DevOps problem is something you certainly don’t want to foster.</p>
<h3 id="what-then">What Then?</h3>
<p>Both approaches have in common a considerable integration effort. Moreover, you don’t fully decouple your app from the CMS, meaning that they coexist in a clunky way. A truly good solution should neutralize integration risks and have minimal impact on the current architecture, especially from a DevOps perspective. This is something a headless CMS enables you to do.</p>
<h2 id="a-conceptual-overview-of-cms-integration">A Conceptual Overview of CMS Integration</h2>
<p>A headless CMS is a back-end content repository that makes content accessible via API. This approach allows you to treat content as you would treat any regular piece of data.</p>
<h3 id="content-as-data">Content as Data</h3>
<p>Suppose that you want to integrate your app with Google Maps. You do not want to make any styling changes, you should not set up any other servers, and you should keep everything in the same domain without creating a new directory. How is this possible?</p>
<p>This happens because you assume whatever geolocalization data you might need will be fetched in a predictable way from a 3rd-party application. Hence all you need to do is to prepare to receive that piece of information and display it accordingly. For instance, putting a marker on a map given a set of coordinates.</p>
<p>Traditional CMS solutions already perform these operations, but only for internal consumption. WordPress will save your content in the database and retrieve it when necessary, without exposing it to other applications. The way your layout or themes consume this data is different from what a regular API does, because you need to use framework-specific methods. These methods add one more layer of complexity, no matter how thorough you find their documentation.</p>
<p>This is precisely how a solution like Butter can help. ButterCMS, a headless CMS, allows you to create content normally in a separate environment, as it should be, and consume content directly in your app through an API. The end result is your content being managed as regular data, fetched from Butter’s servers and rendered as you wish, without changing the architecture of your app.</p>
<figure class="image"><img alt="Headless CMS diagram" loading="lazy" decoding="async" width="596" height="411" src="https://rafaelquintanilha.com/_astro/headless-cms-with-data-min.S8VZBJOR_2nf80B.webp"><figcaption>Headless CMS diagram</figcaption></figure>
<p>Using content as data means that you need to be language agnostic, i.e. you should be able to grab your content regardless of your tech stack. <a href="https://buttercms.com/api-first-cms/" rel="noopener noreferrer" target="_blank">Butter currently supports all major languages</a>, so you can throw it at your app today and start blogging at once.</p>
<p>In the next section, we will see how it works in practice by adding a blog into a regular website.</p>
<h2 id="cms-integration-in-practice">CMS Integration in Practice</h2>
<p>Now that we understand what CMS integration means, let us see how one can do it. For the sake of this tutorial, I will be using React but as I mentioned earlier, you can work with your favorite stack. Go ahead and <a href="https://buttercms.com/blog-engine/" rel="noopener noreferrer" target="_blank">check all available APIs on the ButterCMS website</a> if you haven’t done that before.</p>
<p>In our example, let us assume that we have an existing website and our goal is to add a blog into it. Here’s how it looks like before we add any Butter.</p>
<figure class="image"><img alt="Simple website with no blog content." loading="lazy" decoding="async" width="776" height="827" src="https://rafaelquintanilha.com/_astro/simple-app.BEYqVaWD_Z1XzqoX.webp"><figcaption>Simple website with no blog content.</figcaption></figure>
<p>There is nothing fancy on the site right now. It’s just a regular website with some dummy content. You can follow this tutorial by <a href="https://github.com/rafaelquintanilha/butter-example/tree/without-butter" rel="noopener noreferrer" target="_blank">checking this GitHub repo</a>. This project was bootstrapped with <a href="https://facebook.github.io/create-react-app/" rel="noopener noreferrer" target="_blank">Create React App</a>. For simplicity I’ll omit CSS changes but the main file can be inspected <a href="https://github.com/rafaelquintanilha/butter-example/blob/master/src/App.css" rel="noopener noreferrer" target="_blank">here</a>.</p>
<h3 id="adding-the-router">Adding the Router</h3>
<p>Let’s add a page that will hold our blog content and will work as a subdirectory. As explained before, this approach improves SEO. For this, we will need <a href="https://reacttraining.com/react-router/web/guides/quick-start" rel="noopener noreferrer" target="_blank">React Router</a>. In your app directory open the terminal and type:</p>
<figure class="code"><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span>yarn react-router-dom</span></span></code></pre></figure>
<p>Or alternatively:</p>
<figure class="code"><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span>npm i --save react-router-dom</span></span></code></pre></figure>
<p>To simplify the code, I’ll break our home down into three different components. Here is how <em>App.js</em> looks like:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React, { Component } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#97CCAE"> './App.css'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> Home </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> './Home'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> Header </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> './Header'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> Footer </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> './Footer'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">class</span><span style="color:#EDCC95"> App</span><span style="color:#A1C1E4"> extends</span><span style="color:#ECEBE8"> Component {</span></span>
<span class="line"><span style="color:#EDCC95">  render</span><span style="color:#ECEBE8">() {</span></span>
<span class="line"><span style="color:#A1C1E4">    return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#EDCC95"> className</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"container"</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">Header</span><span style="color:#ECEBE8"> /></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">Home</span><span style="color:#ECEBE8"> /></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">Footer</span><span style="color:#ECEBE8"> /></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">    )</span></span>
<span class="line"><span style="color:#ECEBE8">  }</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> App</span></span></code></pre></figure>
<p>Now, we want to be able to render either <code>Home</code> or the list of blog posts. We will then replace Home with the router and make sure that the main element is common to all routes:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#ECEBE8">…</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#ECEBE8">  BrowserRouter </span><span style="color:#A1C1E4">as</span><span style="color:#ECEBE8"> Router,</span></span>
<span class="line"><span style="color:#ECEBE8">  Route,</span></span>
<span class="line"><span style="color:#ECEBE8">  Switch</span></span>
<span class="line"><span style="color:#ECEBE8">} </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react-router-dom'</span><span style="color:#ECEBE8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">class</span><span style="color:#EDCC95"> App</span><span style="color:#A1C1E4"> extends</span><span style="color:#ECEBE8"> Component {</span></span>
<span class="line"><span style="color:#EDCC95">  render</span><span style="color:#ECEBE8">() {</span></span>
<span class="line"><span style="color:#A1C1E4">    return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#EDCC95"> className</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"container"</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">Router</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;</span><span style="color:#A1C1E4">Header</span><span style="color:#ECEBE8"> /></span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;</span><span style="color:#A1C1E4">main</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">            &#x3C;</span><span style="color:#A1C1E4">Switch</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">              &#x3C;</span><span style="color:#A1C1E4">Route</span><span style="color:#EDCC95"> exact</span><span style="color:#EDCC95"> path</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"/"</span><span style="color:#EDCC95"> component</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{Home} /></span></span>
<span class="line"><span style="color:#ECEBE8">            &#x3C;/</span><span style="color:#A1C1E4">Switch</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;/</span><span style="color:#A1C1E4">main</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;</span><span style="color:#A1C1E4">Footer</span><span style="color:#ECEBE8"> /></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;/</span><span style="color:#A1C1E4">Router</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">    );</span></span>
<span class="line"><span style="color:#ECEBE8">  }</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"><span style="color:#ECEBE8">…</span></span></code></pre></figure>
<p>Save and check your progress by running <code>npm start</code> and going to <a href="http://localhost:3000" rel="noopener noreferrer" target="_blank">http://localhost:3000</a>. You will see that your app loads normally but if you change the URL to <a href="http://localhost:3000/blog" rel="noopener noreferrer" target="_blank">http://localhost:3000/blog</a> an empty space will be rendered. Let’s fix that!</p>
<h3 id="adding-the-blog-page">Adding the Blog Page</h3>
<p>Once the router is all set, let us create a dummy page which we will use to hold the blog content in just a moment. Go ahead and create a file called <em>Blog.js</em>, adding this code:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> Blog</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">h1</span><span style="color:#ECEBE8">>Blog&#x3C;/</span><span style="color:#A1C1E4">h1</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">  )</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> Blog</span></span></code></pre></figure>
<p>Now it’s time to make our router aware of this new page. In <em>App.js</em>:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">...</span></span>
<span class="line"><span style="color:#ECEBE8">&#x3C;</span><span style="color:#A1C1E4">main</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">  &#x3C;</span><span style="color:#A1C1E4">Switch</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">Route</span><span style="color:#EDCC95"> exact</span><span style="color:#EDCC95"> path</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"/"</span><span style="color:#EDCC95"> component</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{Home} /></span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">Route</span><span style="color:#EDCC95"> exact</span><span style="color:#EDCC95"> path</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"/blog"</span><span style="color:#EDCC95"> component</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{Blog} /></span></span>
<span class="line"><span style="color:#ECEBE8">  &#x3C;/</span><span style="color:#A1C1E4">Switch</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">&#x3C;/</span><span style="color:#A1C1E4">main</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#A1C1E4">...</span></span></code></pre></figure>
<p>We need a way to allow users to visit the blog page without needing to manually change the URL. Let’s fix that in <em>Header.js</em>:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> { Link } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react-router-dom'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> Header</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">  &#x3C;</span><span style="color:#A1C1E4">header</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">nav</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#EDCC95"> className</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"logo"</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">Link</span><span style="color:#EDCC95"> to</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"/"</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          Fine Coffee{</span><span style="color:#97CCAE">' '</span><span style="color:#ECEBE8">}</span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;</span><span style="color:#A1C1E4">span</span><span style="color:#EDCC95"> role</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"img"</span><span style="color:#EDCC95"> aria-label</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"Coffee"</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">            ☕</span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;/</span><span style="color:#A1C1E4">span</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;/</span><span style="color:#A1C1E4">Link</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">ul</span><span style="color:#EDCC95"> className</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"menu"</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">li</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;</span><span style="color:#A1C1E4">Link</span><span style="color:#EDCC95"> to</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"/blog"</span><span style="color:#ECEBE8">>Blog&#x3C;/</span><span style="color:#A1C1E4">Link</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;/</span><span style="color:#A1C1E4">li</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">li</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;</span><span style="color:#A1C1E4">a</span><span style="color:#EDCC95"> href</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"tel:"</span><span style="color:#ECEBE8">>Call Us&#x3C;/</span><span style="color:#A1C1E4">a</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;/</span><span style="color:#A1C1E4">li</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;/</span><span style="color:#A1C1E4">ul</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;/</span><span style="color:#A1C1E4">nav</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">  &#x3C;/</span><span style="color:#A1C1E4">header</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> Header</span></span></code></pre></figure>
<p>And that’s it! You now have a subdomain all set just waiting for your blog posts:</p>
<figure class="image"><img alt="Blog routing" loading="lazy" decoding="async" width="783" height="833" src="https://rafaelquintanilha.com/_astro/cms-integration-blog-routing.CVJPKQ8y_jCnfc.webp"><figcaption>Blog routing</figcaption></figure>
<h3 id="adding-butter">Adding Butter</h3>
<p>In order to use Butter to fetch your content, you will need an API key. Go to <a href="https://buttercms.com/" rel="noopener noreferrer" target="_blank">Butter’s main page</a> and sign up for the trial in order to get one.</p>
<p>With the key in hand, create a file called <em>butter-client.js</em> under the <em>src</em> folder:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> Butter </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'buttercms'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> butter </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> Butter</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'&#x3C;YOUR_API_KEY>'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> butter</span></span></code></pre></figure>
<p>Make sure to replace <code>&#x3C;YOUR_API_KEY></code> with your actual key.</p>
<p>The next step is to modify <em>Blog.js</em> in order to connect with Butter. For some extra fun I will use the new React Hooks API.</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React, { useState, useEffect } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> butter </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> './butter-client'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> PostSnippet </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> './PostSnippet'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> Blog</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> [loading, setLoading] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useState</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">false</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> [error, setError] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useState</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">false</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> [data, setData] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useState</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">null</span><span style="color:#ECEBE8">)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#EDCC95"> fetchPosts</span><span style="color:#A1C1E4"> =</span><span style="color:#A1C1E4"> async</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#EDCC95">    setLoading</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">true</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">    setError</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">false</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#A1C1E4">    try</span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">      const</span><span style="color:#ECEBE8"> response </span><span style="color:#A1C1E4">=</span><span style="color:#A1C1E4"> await</span><span style="color:#EDCC95"> butter.post.list</span><span style="color:#ECEBE8">({</span></span>
<span class="line"><span style="color:#ECEBE8">        page: </span><span style="color:#97CCAE">1</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#ECEBE8">        page_size: </span><span style="color:#97CCAE">10</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#ECEBE8">      })</span></span>
<span class="line"><span style="color:#EDCC95">      setData</span><span style="color:#ECEBE8">(response.data)</span></span>
<span class="line"><span style="color:#ECEBE8">    } </span><span style="color:#A1C1E4">catch</span><span style="color:#ECEBE8"> (e) {</span></span>
<span class="line"><span style="color:#EDCC95">      setError</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">`There was an error: ${</span><span style="color:#97CCAE">e.message</span><span style="color:#97CCAE">}`</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#ECEBE8">    }</span></span>
<span class="line"><span style="color:#EDCC95">    setLoading</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">false</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#ECEBE8">  }</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">  useEffect</span><span style="color:#ECEBE8">(() </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#EDCC95">    fetchPosts</span><span style="color:#ECEBE8">()</span></span>
<span class="line"><span style="color:#ECEBE8">  }, [])</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#EDCC95"> getPosts</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      {</span><span style="color:#EDCC95">data.data.map</span><span style="color:#ECEBE8">((post, i) </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">PostSnippet</span><span style="color:#ECEBE8"> {</span><span style="color:#A1C1E4">...</span><span style="color:#ECEBE8">post} </span><span style="color:#EDCC95">key</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{i} /></span></span>
<span class="line"><span style="color:#ECEBE8">      ))}</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">  )</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#EDCC95"> getContent</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">    if</span><span style="color:#ECEBE8"> (loading) </span><span style="color:#A1C1E4">return</span><span style="color:#ECEBE8"> &#x3C;</span><span style="color:#A1C1E4">p</span><span style="color:#ECEBE8">>Fetching posts...&#x3C;/</span><span style="color:#A1C1E4">p</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#A1C1E4">    if</span><span style="color:#ECEBE8"> (error) </span><span style="color:#A1C1E4">return</span><span style="color:#ECEBE8"> &#x3C;</span><span style="color:#A1C1E4">p</span><span style="color:#ECEBE8">>{error}&#x3C;/</span><span style="color:#A1C1E4">p</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#A1C1E4">    if</span><span style="color:#ECEBE8"> (</span><span style="color:#A1C1E4">!</span><span style="color:#ECEBE8">data) </span><span style="color:#A1C1E4">return</span><span style="color:#A1C1E4"> null</span></span>
<span class="line"><span style="color:#A1C1E4">    return</span><span style="color:#EDCC95"> getPosts</span><span style="color:#ECEBE8">()</span></span>
<span class="line"><span style="color:#ECEBE8">  }</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">h1</span><span style="color:#ECEBE8">>Blog&#x3C;/</span><span style="color:#A1C1E4">h1</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      {</span><span style="color:#EDCC95">getContent</span><span style="color:#ECEBE8">()}</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">  )</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> Blog</span></span></code></pre></figure>
<p>The key part is the highlighted line. This is where we communicate with ButterCMS and retrieve our content. Notice that for simplicity we are fetching only the first ten posts. You can check the <a href="https://buttercms.com/docs/api/?javascript" rel="noopener noreferrer" target="_blank">API Reference</a> if you are curious about other possibilities.</p>
<p>The rest of the code is about setting up control variables and rendering the correct content. Notice that we run <code>fetchPosts()</code> only when the component mounts, which is defined by the <code>useEffect</code> hook without any dependencies (an empty array).</p>
<p>Observe that for each returned post we render the <code>PostSnippet</code> component, where we display basic information about the post such as the title, the summary, and the author’s name. Let’s move forward and create <em>PostSnippet.js</em>:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> moment </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'moment'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> PostSnippet</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> props </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#EDCC95"> className</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"post-snippet"</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">h3</span><span style="color:#ECEBE8">>{props.title}&#x3C;/</span><span style="color:#A1C1E4">h3</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">p</span><span style="color:#ECEBE8">>{props.summary}&#x3C;/</span><span style="color:#A1C1E4">p</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          By{</span><span style="color:#97CCAE">' '</span><span style="color:#ECEBE8">}</span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;</span><span style="color:#A1C1E4">strong</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">            {props.author.first_name} {props.author.last_name}</span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;/</span><span style="color:#A1C1E4">strong</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">span</span><span style="color:#EDCC95"> className</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"publication-date"</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          Published on {</span><span style="color:#EDCC95">moment</span><span style="color:#ECEBE8">(props.published)</span><span style="color:#EDCC95">.format</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'YYYY-MM-DD'</span><span style="color:#ECEBE8">)}</span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;/</span><span style="color:#A1C1E4">span</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">  )</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> PostSnippet</span></span></code></pre></figure>
<p>Refer to the documentation to inspect all values returned by the API. Note the use of <a href="https://momentjs.com/" rel="noopener noreferrer" target="_blank">MomentJS</a> for formatting the date of publication.</p>
<p>Here is how your blog page should be looking now with the dummy post Butter automatically creates:</p>
<figure class="image"><img alt="Blog with post" loading="lazy" decoding="async" width="777" height="832" src="https://rafaelquintanilha.com/_astro/blog-with-post.hfqFvTjw_Z1knkmt.webp"><figcaption>Blog with post</figcaption></figure>
<p>The last step is to display the full post and have a permalink, i.e. a permanent URL, to it.</p>
<h3 id="routing-to-the-post">Routing to the Post</h3>
<p>Every post will have its own link. Let’s go back to <em>App.js</em> and add a new route:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">...</span></span>
<span class="line"><span style="color:#ECEBE8">&#x3C;</span><span style="color:#A1C1E4">Switch</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">  &#x3C;</span><span style="color:#A1C1E4">Route</span><span style="color:#EDCC95"> exact</span><span style="color:#EDCC95"> path</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"/"</span><span style="color:#EDCC95"> component</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{Home} /></span></span>
<span class="line"><span style="color:#ECEBE8">  &#x3C;</span><span style="color:#A1C1E4">Route</span><span style="color:#EDCC95"> exact</span><span style="color:#EDCC95"> path</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"/blog"</span><span style="color:#EDCC95"> component</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{Blog} /></span></span>
<span class="line"><span style="color:#ECEBE8">  &#x3C;</span><span style="color:#A1C1E4">Route</span><span style="color:#EDCC95"> path</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"/blog/:slug"</span><span style="color:#EDCC95"> render</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{Post} /></span></span>
<span class="line"><span style="color:#ECEBE8">&#x3C;/</span><span style="color:#A1C1E4">Switch</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#A1C1E4">...</span></span></code></pre></figure>
<p>This new route will be activated when the URL is in the format <a href="https://example.com/blog/my-fancy-post" rel="noopener noreferrer" target="_blank">https://example.com/blog/my-fancy-post</a> and render the <code>Post</code> component. In order to make this work, we need <code>Post</code> to have all the information needed to render the content. Let’s go back to <code>PostSnippet</code> and add a hyperlink to the title:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> PostSnippet</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> props </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#EDCC95"> className</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"post-snippet"</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">h3</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">Link</span><span style="color:#EDCC95"> to</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{{</span></span>
<span class="line"><span style="color:#ECEBE8">          pathname: </span><span style="color:#97CCAE">`/blog/${</span><span style="color:#97CCAE">props.slug</span><span style="color:#97CCAE">}`</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#ECEBE8">          state: props</span></span>
<span class="line"><span style="color:#ECEBE8">        }}></span></span>
<span class="line"><span style="color:#ECEBE8">          {props.title}</span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;/</span><span style="color:#A1C1E4">Link</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;/</span><span style="color:#A1C1E4">h3</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      ...</span></span></code></pre></figure>
<p>Notice that we use the slug as the permalink and we pass the props contained in the snippet directly to whichever component is set to the route (in our case, <code>Post</code>). Very neat from the react-router folks!</p>
<p>Finally, it is time to create the <code>Post</code> component:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> moment </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'moment'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> { Link } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react-router-dom'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> Post</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> props </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> data </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> props.location.state</span></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#EDCC95"> className</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"post"</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">h1</span><span style="color:#ECEBE8">>{data.title}&#x3C;/</span><span style="color:#A1C1E4">h1</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">hr</span><span style="color:#ECEBE8"> /></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#EDCC95"> className</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"author"</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">img</span><span style="color:#EDCC95"> src</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{data.author.profile_image} </span><span style="color:#EDCC95">alt</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"Author"</span><span style="color:#ECEBE8"> /></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          Published by{</span><span style="color:#97CCAE">' '</span><span style="color:#ECEBE8">}</span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;</span><span style="color:#A1C1E4">strong</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">            {data.author.first_name} {data.author.last_name}</span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;/</span><span style="color:#A1C1E4">strong</span><span style="color:#ECEBE8">>{</span><span style="color:#97CCAE">' '</span><span style="color:#ECEBE8">}</span></span>
<span class="line"><span style="color:#ECEBE8">          on {</span><span style="color:#EDCC95">moment</span><span style="color:#ECEBE8">(data.published)</span><span style="color:#EDCC95">.format</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'MMMM Do, YYYY'</span><span style="color:#ECEBE8">)}</span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">hr</span><span style="color:#ECEBE8"> /></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#EDCC95"> dangerouslySetInnerHTML</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{{ __html: data.body }} /></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">hr</span><span style="color:#ECEBE8"> /></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">Link</span><span style="color:#EDCC95"> to</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"/blog"</span><span style="color:#ECEBE8">></span><span style="color:#97CCAE">&#x26;larr;</span><span style="color:#ECEBE8"> Back to the posts list&#x3C;/</span><span style="color:#A1C1E4">Link</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">  )</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> Post</span></span></code></pre></figure>
<p>The data passed via the state prop of the <code>Link</code> component is accessible through <code>props.location.state</code>. This is all we need in order to display the correct content.</p>
<p>If everything went well, this is the final result:</p>
<figure class="image"><img alt="View post" loading="lazy" decoding="async" width="783" height="833" src="https://rafaelquintanilha.com/_astro/cms-integration-view-post.CQB6s5QY_GjSbm.webp"><figcaption>View post</figcaption></figure>
<h3 id="adding-content">Adding Content</h3>
<p>Once we successfully integrated the CMS into our existing website, we can easily manage the content on Butter’s side. Fortunately, there is no need to touch any code anymore - <em>and we have decoupled our app from the CMS!</em></p>
<p>To illustrate how easy adding new content can be, let’s open Butter’s admin panel, click on <em>Blog Posts</em> and create a new post by adding some content and hitting <em>Publish</em>:</p>
<figure class="image"><img alt="Butter interface" loading="lazy" decoding="async" width="1092" height="830" src="https://rafaelquintanilha.com/_astro/butter-interface.DHRFQaEH_Z1iw3Gi.webp"><figcaption>Butter interface</figcaption></figure>
<p>With the post published, go back to the app and check that it’s already there:</p>
<figure class="image"><img alt="Blog with a new post" loading="lazy" decoding="async" width="777" height="833" src="https://rafaelquintanilha.com/_astro/blog-with-new-post.C1y69cCn_ezJie.webp"><figcaption>Blog with a new post</figcaption></figure>
<p>And that’s it! Our integration is complete with minimum effort.</p>
<p>The <a href="https://github.com/rafaelquintanilha/butter-example" rel="noopener noreferrer" target="_blank">full code for this tutorial is available on GitHub</a>. There is also a <a href="https://butter-example.netlify.com/" rel="noopener noreferrer" target="_blank">live example</a> if you are curious about the end result.</p>
<h2 id="conclusion">Conclusion</h2>
<p>The web is continuously evolving resulting in obtrusive solutions that don’t play along with other technologies being pushed aside. Integration and maintainability are major concerns that need to be addressed with responsibility.</p>
<p>Treating your content as regular data gives you the flexibility you need to enjoy the power of CMS solutions without being chained to a piece of technology, as you never know when you may want to switch it in the future. Freedom of choice and fewer maintenance headaches are huge wins for developers.</p>
<p>To wrap it up, a good CMS integration should:</p>
<ul>
<li><strong>Decouple your website from the data</strong>. Both should coexist without being directly connected, in the sense that changes in one end do not affect the other end.</li>
<li><strong>Allow easy integration</strong>. A plain and simple API will do the job. Just call the API when you want to insert content from the CMS into your app.</li>
<li><strong>Have a reduced cost of change</strong>. If you ever want to change the underlying technologies that power up your application, having a CMS should not impact the complexity of the change.</li>
<li><strong>Give you freedom of tech stack</strong>. The CMS should be agnostic to whichever tech stack you decided to use in your project. They are separate entities and therefore should not interfere with each other apart from the API.</li>
</ul>]]></content:encoded>
</item>
</channel>
</rss>
