One place for hosting & domains

      Component

      Responsive Carousel Component with Angular 2

      Note: Updates:

      • March 22, 2016: Provided a Demo Link which is available on Plunker
      • March 21, 2016: Updated a poorly formatted markdown. A { instead of a [ for a link.

      Introduction

      The web is growing. It is growing so fast that if you don’t catch up you might not be able to shine bright in your career as a web developer.

      A few months ago I started hearing about Web Components from the mouths of so-called professional developers. I knew it was one of those new things that “I don’t really need now, but I must learn it for the future”. Unfortunately, for poor me, Angular, which has always been my favorite JavaScript framework, decided to componentize everything.

      This concept is one of the standards of the web that can boast of being easy to grasp.

      Basically, web components give room for you to simply bundle these tags with their styles and scripts as a reusable component that is exposed via one tag (instead of littering your HTML with similar confusing tags).

      A component is basically just a grouping of HTML/JS/CSS all in one.

      Web Components are a new standard that will be here to stay because it is widely accepted. The problem is that we web devs know how this new stuff rolls.

      Web Components is widely accepted, but not widely supported on browsers, and this is where Angular 2 comes in.

      Angular 2 is the “new guy”. It implements components at its core and makes it simple to work with components in our daily web projects.

      I understand that the reason why a lot of us have yet to embrace this “new guy” is because learning Angular 1 was not fun and now we are hearing of another version with a different concept. The good news is Angular 2 is actually simple and you just need 4-5 days to start doing wonders with it.

      Now enough talking. Let’s have a little fun making a CSS-based (and I really mean CSS-based) carousel component with Angular 2.

      npm has become so popular that, recently, tutorials forget to remind us to install them. Therefore, kindly install Node so as to get its package manager, npm.

      Create a folder in your favorite directory. This will be located probably in your projects folder or desktop. Name it angular2-carousel-component. Navigate via your CLI to this created folder.

      Create package.json and tsconfing.json at the root of the folder with the following contents:

      package.json:

      {
        "name": "angular2-quickstart",
        "version": "1.0.0",
        "scripts": {
          "tsc": "tsc",
          "tsc:w": "tsc -w",
          "lite": "lite-server",
          "start": "concurrent \"npm run tsc:w\" \"npm run lite\" "
        },
        "license": "ISC",
        "dependencies": {
          "angular2": "2.0.0-beta.0",
          "systemjs": "0.19.6",
          "es6-promise": "^3.0.2",
          "es6-shim": "^0.33.3",
          "reflect-metadata": "0.1.2",
          "rxjs": "5.0.0-beta.0",
          "zone.js": "0.5.10"
        },
        "devDependencies": {
          "concurrently": "^1.0.0",
          "lite-server": "^1.3.1",
          "typescript": "^1.7.3"
        }
      }
      

      tsconfig.json

      {
        "compilerOptions": {
          "target": "ES5",
          "module": "system",
          "moduleResolution": "node",
          "sourceMap": true,
          "emitDecoratorMetadata": true,
          "experimentalDecorators": true,
          "removeComments": false,
          "noImplicitAny": false
        },
        "exclude": [
          "node_modules"
        ]
      }
      

      The tsconfig.json file is a configuration file for TypeScript (more on that later) which the properties are explained here in the “Appendix: TypeScript configuration” section. We can go ahead and install the dependencies by running:

      1. npm install

      Add two more folders, app and images. Our main application codes will be in the app folder, but you can copy the images for the slides here into the images folder.

      We are all set to make our component, but before we do that, let us explain the CSS-based carousel and how it is implemented.

      Carousels are one of the most popular concepts in the web, but it has its own price. There are heavy images to display and scripts to manipulate the image slides.

      How about we just endure only the pain caused by these images and leave out the troubles of JavaScript? How about we make a Carousel with just CSS? How possible is that?

      Actually making Carousels has never been easy until I read Harry Roberts article on his blog. Before you get so excited about this simplicity, be sure that your Carousel will be dead simple and basic, and won’t have many controls. Just be rest assured that it will be a RESPONSIVE “carousel”.

      Assuming we have a template as shown below:

      <div class="carousel">
      
        <ul class="slides">
      
          <li>
            <h2>We are covered</h2>
            <img src="images/covered.jpg" alt="">
          </li>
      
          <li>
            <h2>Generation Gap</h2>
            <img src="images/generation.jpg" alt="">
          </li>
      
          <li>
            <h2>Potter Me
            <img src="images/potter.jpg" alt="">
          </li>
      
          <li>
            <h2>Pre-School Kids</h2>
            <img src="images/preschool.jpg" alt="">
          </li>
      
          <li>
            <h2>Young Peter Cech</h2>
            <img src="images/soccer.jpg" alt="">
          </li>
      
        </ul>
      
      </div>
      

      Harry’s idea is to make the .slides wrapper have a width that is equal to the number of slides multiplied by the viewport. So, assuming our viewport is 100% and we have 5 items, the width of the slides should be 500% so as to contain all the slides when aligned horizontally.

      We may leave the CSS implementation for now and see it while making the carousel component.

      Angular 2 uses Typescript, which from a general perspective is a semi-language that compiles to JavaScript. It implements everything JS, but just gives that feel of strictness that C-based languages have that JS does not have. Don’t be overwhelmed, it is just a “cool JavaScript”.

      Microsoft has a TypeScript plugin for Sublime which will help you with hinting, syntax highlighting, and many other those goodies

      There are also many other TypeScript plugins for various editors which makes using TypeScript easy no matter what environment you work in.

      As the idea is to make strict applications, let us first define an interface for the images collection. The interface is just like in any other language, it is a signature that we must adhere to if we care to use it. In the app folder, add a file named image.interface.ts:

      export interface Image {
        title: string;
        url: string;
      }
      

      You do not have to understand what interfaces are before you can follow this tutorial.

      We just exported an Image Interface that will serve as a signature for the collection of our images. This is typically saying that if you want to make an image collection that implements that interface, it must have a title and url property of type string.

      Now that we have a signature, we can go ahead and create the carousel component. Create carousel.component.ts in the app directory:

      
      import {Component} from 'angular2/core';
      
      
      import {Image} from './image.interface';
      
      
      @Component({
        
        selector: 'css-carousel',
        
        template: `
       <div class="carousel">
      
        <ul class="slides">
      
          <li *ngFor="#image of images">
            <h2>{{image.title}}</h2>
            <img src="{{image.url}}" alt="">
          </li>
      
        </ul>
      
      </div>
        `,
        
        styles: [`
      .carousel{
          overflow:hidden;
          width:100%;
      }
      .slides{
          list-style:none;
          position:relative;
          width:500%; /* Number of panes * 100% */
          overflow:hidden; /* Clear floats */
              /* Slide effect Animations*/
          -moz-animation:carousel 30s infinite;
          -webkit-animation:carousel 30s infinite;
          animation:carousel 30s infinite;
      }
      .slides > li{
          position:relative;
          float:left;
          width: 20%; /* 100 / number of panes */
      }
      .carousel img{
          display:block;
          width:100%;
          max-width:100%;
      }
      .carousel h2{
          margin-bottom: 0;
          font-size:1em;
          padding:1.5em 0.5em 1.5em 0.5em;
          position:absolute;
          right:0px;
          bottom:0px;
          left:0px;
          text-align:center;
          color:#fff;
          background-color:rgba(0,0,0,0.75);
          text-transform: uppercase;
      }
      
      @keyframes carousel{
          0%    { left:-5%; }
          11%   { left:-5%; }
          12.5% { left:-105%; }
          23.5% { left:-105%; }
          25%   { left:-205%; }
          36%   { left:-205%; }
          37.5% { left:-305%; }
          48.5% { left:-305%; }
          50%   { left:-405%; }
          61%   { left:-405%; }
          62.5% { left:-305%; }
          73.5% { left:-305%; }
          75%   { left:-205%; }
          86%   { left:-205%; }
          87.5% { left:-105%; }
          98.5% { left:-105%; }
          100%  { left:-5%; }
      }
        `],
      })
      
      export class CSSCarouselComponent {
          
        public images = IMAGES;
      }
      
      
      var IMAGES: Image[] = [
        { "title": "We are covered", "url": "images/covered.jpg" },
        { "title": "Generation Gap", "url": "images/generation.jpg" },
        { "title": "Potter Me", "url": "images/potter.jpg" },
        { "title": "Pre-School Kids", "url": "images/preschool.jpg" },
        { "title": "Young Peter Cech", "url": "images/soccer.jpg" }
      ];
      

      When we ran the npm install command, we pulled the Angular 2 package into our folder. The first line is importing the Angular core library. We also imported the Image interface that we created earlier as we will make use of it here. Notice that we do not have to add the .ts extension when importing.

      The file is exporting a CSSCarouselComponent class which has a public property of an array of images implementing image interface. The class also has a @Component decorator which is specifying the meta-properties of this class. The selector is the name we want the tag to have and the template is the HTML for the component and styles, which is the CSS trick we played to get our carousel working.

      Note: Angular 2 supports 3 types of styles which are template-inline, component-inline, and external CSS. Just like the normal way, you can add styles directly to template tags which are referred to as template-inline. This is unlike old times, an acceptable practice, because of encapsulation.

      Component-inline is what we just implemented in our demo above while external can be achieved by just replacing the component-inline styles with: [styleUrls: 'style.css']

      Next up is to create our app component which just serves as a parent. The app component is like the building in the illustration I made while introducing this article. It has the same skeleton as the carousel component. Create app.component.ts in app folder with the following contents:

      
      import {Component} from 'angular2/core';
      
      
      import {CSSCarouselComponent} from './carousel.component';
      
      
      @Component({
        
        selector: 'my-app',
        
        template: `
        <div class="wrapper">
          <css-carousel></css-carousel>
          </div>
        `,
         
        styles: [`
         .wrapper{
            width: 60%;
            margin: 60px auto;
          }
        `],
        
         directives: [CSSCarouselComponent]
      })
      
      export class AppComponent { }
      
      

      The major difference here is the directives property in the @Component decorator which is an array of all the imported components that we will use on this component. Notice we already imported the CSSCarouselComponent after importing angular’s core library.

      We can now boot up the app. All there is to do when booting is to import angular, import the app to boot, and boot with the bootstrap() method. Create a file in app with the name boot.ts:

      
      import {bootstrap}    from 'angular2/platform/browser'
      
      import {AppComponent} from './app.component'
      
      bootstrap(AppComponent);
      

      As usual, an index.html entry point is needed for our cool app. Create one on the root and update it with:

      
          <title>CSS Carousel Angular 2 Compopnent</title>
      
          
          
          
          
          <script src="node_modules/es6-shim/es6-shim.min.js"></script>
          <script src="node_modules/systemjs/dist/system-polyfills.js"></script>
          
      
          <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
          <script src="node_modules/systemjs/dist/system.src.js"></script>
          <script src="node_modules/rxjs/bundles/Rx.js"></script>
          <script src="node_modules/angular2/bundles/angular2.dev.js"></script>
          
      
          
          
          <script>
            System.config({
              packages: {
                app: {
                  format: 'register',
                  defaultExtension: 'js'
                }
              }
            });
            System.import('app/boot')
                  .then(null, console.error.bind(console));
          </script>
          
      
      
          <my-app>Loading...</my-app>
      

      Some JavaScript libraries are included, but you should care more about System.js which is a third-party library that adds ES6 module loading functionality across browsers. As seen in the file it helps load our bootstrap file app/boot in the index.html file.

      You can run the app via your CLI with:

      1. npm start

      Web components are going to trend whether we are ready for it or not. Even if we are to keep trends aside, web components are really an appreciated and accepted concept. Some tools like Polymer and React already started a good job, but if you love angular like me, then Angular 2 is an awesome option.

      One last thing, forget the competition among these tools, just stick to what you can afford because they all meet the basic requirements you need to make a web component application.

      How To Boost SEO Using Gatsby’s SEO Component and Gatsby React Helmet


      The author selected /dev/color to receive a donation as part of the Write for DOnations program.

      Introduction

      When a user codes and deploys a website, they often want an online audience to find and read the website they’ve created. Search engine optimization (SEO) is the practice of making a website discoverable by this online audience. Optimizing search involves making changes to your Gatsby app so that it will show up in the results for search engines like Google, Bing, and DuckDuckGo. This is often done by fine-tuning the metadata that ends up in the HTML for your site.

      In this tutorial, you will configure Gatsby’s SEO component that comes with SEO tooling right out of the box. You will add meta tags to your site using Gatsby React Helmet. Meta tags are important because they give search engines information about your site. Usually the better understanding Google has about your site, the more accurately it can index your webpage. You will also create social media cards for Twitter, and Open Graph meta tags in Facebook. There are over one billion people using some form of social media, so optimizing for social media is an efficient way to get your website in front of many internet users.

      Prerequisites

      Step 1 — Creating an Empty Project

      In this section, you are going to create a new project based on the Gatsby starter default template. You are going to create a whale-watching website, and in the following steps you will improve its SEO. This will give you a solid project that you can optimize with meta tags and social media assets.

      First, use the CLI tool to start a new project named gatsby-seo-project:

      • gatsby new gatsby-seo-project https://github.com/gatsbyjs/gatsby-starter-default

      This creates a new website from the starter template in the gatsby-starter-default GitHub repository from Gatsby.

      Once the project is created, move into the src/images folder of the project:

      • cd gatsby-seo-project/src/images

      Once you are in the images folder, download a picture of a whale from the stock photography website Unsplash:

      • wget 'https://unsplash.com/photos/JRsl_wfC-9A/download?force=true&w=640'

      Wget is a Gnu command that downloads files from the internet.

      Next, list all of the images in the same images directory with the ls command:

      You will receive the following output:

      Output

      'download?force=true&w=640' gatsby-astronaut.png gatsby-icon.png

      'download?force=true&w=640' is a hard name to remember, so rename it to whale-watching.png:

      • mv 'download?force=true&w=640' whale-watching.png

      Now that you have your whale image, go to the root of your project and open src/pages/index.js. Make the highlighted change in the following code to customize your website:

      gatsby-seo-project/src/pages/index.js

      import * as React from "react"
      import { Link } from "gatsby"
      import { StaticImage } from "gatsby-plugin-image"
      
      import Layout from "../components/layout"
      import SEO from "../components/seo"
      
      const IndexPage = () => (
        <Layout>
          <SEO title="Home" />
          <h1>Whale watching for all</h1>
          <p>Come see extraordinary whales!</p>
          <StaticImage
            src="https://www.digitalocean.com/community/tutorials/images/whale-watching.png"
            width={300}
            quality={95}
            formats={["AUTO", "WEBP", "AVIF"]}
            alt="A surfacing whale"
            style={{ marginBottom: `1.45rem` }}
          />
          <p>
            <Link to="/page-2/">Go to page 2</Link> <br />
            <Link to="/using-typescript/">Go to "Using TypeScript"</Link>
          </p>
        </Layout>
      )
      
      export default IndexPage
      

      Save the file. To try out the code, start a local development server with the following command:

      Once the server is running, check localhost:8000 in your browser. You will find your new site rendered in the browser:

      Gatsby site with whale image and text.

      You are now finished setting up your project. Next, you will add meta tags to your site header with React Helmet.

      Step 2 — Creating an SEO Component with React Helmet

      In this section, you are going to learn how to control the technical SEO aspects of your site with the help of Gatsby’s React Helmet plugin and an SEO component. The Helmet plugin provides server side rendering to all of the metadata found in the head of the Gatsby site. This is important because, without server side rendering, there is a chance that server engine bots might not be able to scrape and record metadata before the site is rendered, making it more difficult to index the site for search.

      When you use gatsby-starter-default as a base for your website, it already comes with everything you need to start tweaking SEO. To do this, you will be working with the following files:

      • gatsby-config.js: Gatsby config includes metadata values that GraphQL will query and place in the SEO file.

      • src/components/seo.js: This file contains the Helmet and the SEO component.

      You are first going to open the gatsby-config.js file, which is located at the root of your project:

      Before you make any changes to the file, examine the plugins key in the exported object. The Gatsby default starter already has the Helmet plugin installed, as shown in the following highlighted line:

      gatsby-seo-project/gatsby-config.js

      module.exports = {
        siteMetadata: {
          title: `Gatsby Default Starter`,
          description: `Kick off your next, great Gatsby project with this default starter. This barebones starter ships with the main Gatsby configuration files you might need.`,
          author: `@gatsbyjs`,
        },
        plugins: [
          `gatsby-plugin-react-helmet`,
          `gatsby-plugin-image`,
          {
            resolve: `gatsby-source-filesystem`,
            options: {
              name: `images`,
              path: `${__dirname}/src/images`,
            },
          },
          `gatsby-transformer-sharp`,
          `gatsby-plugin-sharp`,
          {
            resolve: `gatsby-plugin-manifest`,
            options: {
              name: `gatsby-starter-default`,
              short_name: `starter`,
              start_url: `/`,
              background_color: `#663399`,
              theme_color: `#663399`,
              display: `minimal-ui`,
              icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site.
            },
          },
          `gatsby-plugin-gatsby-cloud`,
          // this (optional) plugin enables Progressive Web App + Offline functionality
          // To learn more, visit: https://gatsby.dev/offline
          // `gatsby-plugin-offline`,
        ],
      }
      

      Next, direct your attention to the siteMetadata key. This contains an object that holds the metadata for your site. You are going to change the title, the description, and the author. You will also add keywords to help users search for your site:

      gatsby-seo-project/gatsby-config.js

      module.exports = {
        siteMetadata: {
          title: `Wondrous World of Whale Watching`,
          description: `Come and enjoy an experience of a lifetime! Watch whales with us!`,
          author: `@digitalocean`,
          keywords: `whales, marine life, trip, recreation`,
        },
      ...
      

      The keywords metadata is instrumental in optimizing for search. While the topic of choosing keywords is beyond the scope of this tutorial, you can learn more about the basics of SEO at Google’s search documentation website. Here you have added specific search terms that users might use when searching for a site like the sample whale-watching site.

      Save and close this file.

      Next, proceed to open the SEO component:

      • nano src/components/seo.js

      There is a lot going on in the SEO component. Focus your attention on the SEO function. In this function you are using GraphQL to query the siteMetadata object. Remember that you have added keywords to your siteMetadata object, so make the following highlighted change to your query:

      gatsby-seo-project/src/components/seo.js

      ...
      function SEO({ description, lang, meta, title}) {
        const { site } = useStaticQuery(
          graphql`
            query {
              site {
                siteMetadata {
                  title
                  description
                  author
                  keywords
                }
              }
            }
          `
        )
      ...
      

      Below the SEO function, add a reference to this queried data in a keywords constant to make the data easier to work with:

      gatsby-seo-project/src/components/seo.js

      ...
        const keywords = site.siteMetadata.keywords
        const metaDescription = description || site.siteMetadata.description
        const defaultTitle = site.siteMetadata?.title
      ...
      

      The variable keywords has all of the keywords you created in the gatsby-config.js file. The variable metaDescription is a description that you can pass as a prop on a page or query from the siteMetadata object in gatsby-config.js. Finally, defaultTitle is set to the value of title in the siteMetadata object. The ? in the siteMetadata attribute checks for a null value and returns undefined for a null or nullish value.

      Next, inspect what the SEO component is returning, and add an object for keywords:

      gatsby-seo-project/src/components/seo.js

      ...
        return (
          <Helmet
            htmlAttributes={{
              lang,
            }}
            title={title}
            titleTemplate={defaultTitle ? `%s | ${defaultTitle}` : null}
            meta={[
              {
                name: `description`,
                content: metaDescription,
              },
              {
                name: `keywords`,
                content: keywords,
              },
              {
                property: `og:title`,
                content: title,
              },
              {
                property: `og:description`,
                content: metaDescription,
              },
              {
                property: `og:type`,
                content: `website`,
              },
              {
                name: `twitter:card`,
                content: `summary`,
              },
              {
                name: `twitter:creator`,
                content: site.siteMetadata?.author || ``,
              },
              {
                name: `twitter:title`,
                content: title,
              },
              {
                name: `twitter:description`,
                content: metaDescription,
              },
            ].concat(meta)}
          />
        )
      ...
      

      You are returning a Helmet component. Helmet populates the head of an HTML document using server side rendered data, which makes it easier for Google to crawl and record the metadata. htmlAttributes={{lang,}} specifies the language of the element’s content, and title is the title found in the metadata, which comes from siteMetadata. titleTemplate creates the title tag, which is important, since Google penalizes sites that are missing a title tag.

      After this section, you’ll find the meta object, which contains the metadata. Most of the values here come from siteMetadata.

      Finally, examine the SEO.defaultProps and SEO.propTypes objects:

      gatsby-seo-project/src/components/seo.js

      ...
      SEO.defaultProps = {
        lang: `en`,
        meta: [],
        description: ``,
      }
      
      SEO.propTypes = {
        description: PropTypes.string,
        lang: PropTypes.string,
        meta: PropTypes.arrayOf(PropTypes.object),
        title: PropTypes.string.isRequired,
      }
      

      SEO.defaultProps are the default values of the SEO props. SEO.propTypes passes the correct value type and acts as a light typing system.

      Save your file with the new keywords entry and start the local server in your terminal:

      After the server has starter, enter localhost:8000 in the browser. Open up the view of the HTML in your browser; for Chrome, right click the window and open DevTools. Choose Elements and open the <head></head> tag. In this tag, you will find the following line:

      ...
      <meta name="keywords" content="whales, marine life, trip, recreation" data-react-helmet="true">
      ...
      

      You have now successfully set the header data with React Helmet.

      In this section, you created metadata to improve the SEO of your whale-watching site. In the next section, you’ll add an image and make this site easier to share on social media.

      Step 3 — Adding Images to Enhance Social Sharing

      Social networks play an important role in attracting attention to your content. In this section, you are going to add an image to two features that optimize sharing your site on social: your Twitter card and the Open Graph protocol for Facebook. You will also learn which tools to use to ensure that your metadata is appearing on these two social network platforms.

      Open up gatsby-config in a text editor:

      You are going to add images/whale-watching.png into the siteMetadata:

      gatsby-seo-project/gatsby-config.js

      module.exports = {
        siteMetadata: {
          title: `Wondrous World of Whale Watching`,
          description: `Come and enjoy an experience of a lifetime! Watch whales with us!`,
          author: `@digitalocean`,
          keywords: `whales, marine life, trip, recreation`,
          image: `src/images/whale-watching.png`
        },
        plugins: [
          `gatsby-plugin-react-helmet`,
          `gatsby-plugin-image`,
          {
            resolve: `gatsby-source-filesystem`,
            options: {
              name: `images`,
              path: `${__dirname}/src/images`,
            },
          },
          `gatsby-transformer-sharp`,
          `gatsby-plugin-sharp`,
          {
            resolve: `gatsby-plugin-manifest`,
            options: {
              name: `gatsby-starter-default`,
              short_name: `starter`,
              start_url: `/`,
              background_color: `#663399`,
              theme_color: `#663399`,
              display: `minimal-ui`,
              icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site.
            },
          },
          `gatsby-plugin-gatsby-cloud`,
          // this (optional) plugin enables Progressive Web App + Offline functionality
          // To learn more, visit: https://gatsby.dev/offline
          // `gatsby-plugin-offline`,
        ],
      }
      

      GraphQL will now be able to query the image. Close and save the file.

      Next, open up seo.js in the text editor:

      • nano src/components/seo.js

      Now that your image is in the site metadata, it’s time to add it to the SEO component. Add the following highlighted lines to seo.js:

      gatsby-seo-project/src/components/seo.js

      ...
      function SEO({ description, lang, meta, title}) {
        const { site } = useStaticQuery(
          graphql`
            query {
              site {
                siteMetadata {
                  title
                  description
                  author
                  keywords
                  image
                }
              }
            }
          `
        )
        const image = site.siteMetadata.image
        const keywords = site.siteMetadata.keywords
        const metaDescription = description || site.siteMetadata.description
        const defaultTitle = site.siteMetadata?.title
      
        return (
          <Helmet
            htmlAttributes={{
              lang,
            }}
            title={title}
            titleTemplate={defaultTitle ? `%s | ${defaultTitle}` : null}
            meta={[
              {
                name: `description`,
                content: metaDescription,
              },
              {
                name: `keywords`,
                content: keywords,
              },
              {
                property: `og:title`,
                content: title,
              },
              {
                property: `og:description`,
                content: metaDescription,
              },
              {
                property: `og:type`,
                content: `website`,
              },
              {
                property: `og:image`,
                content: image,
              },
              {
                name: `twitter:card`,
                content: `summary`,
              },
              {
                name: `twitter:image`,
                content: image,
              },
              {
                name: `twitter:creator`,
                content: site.siteMetadata?.author || ``,
              },
              {
                name: `twitter:title`,
                content: title,
              },
              {
                name: `twitter:description`,
                content: metaDescription,
              },
            ].concat(meta)}
          />
        )
      }
      
      SEO.defaultProps = {
        lang: `en`,
        meta: [],
        description: ``,
      }
      
      SEO.propTypes = {
        description: PropTypes.string,
        image: PropTypes.string,
        lang: PropTypes.string,
        meta: PropTypes.arrayOf(PropTypes.object),
        title: PropTypes.string.isRequired,
      }
      
      export default SEO
      

      In this code, you:

      • Added the image to the GraphQL query
      • Created an image variable and set the value to the image found in siteMetadata
      • Added og:image to the meta object
      • Added twitter:image to the meta object
      • Added image to SEO.propTypes

      Save your changes and close seo.js.

      The final step in this process is to test these changes on Twitter and Facebook. This cannot be done from a local development server; in order to test your site, you must first deploy it. There are many ways to do this, including using DigitalOcean’s App Platform, which you can read about in the How To Deploy a Gatsby Application to DigitalOcean App Platform tutorial.

      This tutorial will use a Gatsby app hosted on App Platform as an example. You can find this app at https://digital-ocean-gatsby-seo-xkmfq.ondigitalocean.app/, and it includes the SEO changes you made to your site in this tutorial.

      If you want to test if social media objects show up on Twitter, head over https://cards-dev.twitter.com/validator. This validator is maintained by Twitter, and requires a Twitter account to use. Put the URL for the sample deployed site into the validator:

      Twitter card validator

      Notice that the custom image will now show when users tweet about your website.

      Next, head over to Facebook’s Open Graph validator at https://developers.facebook.com/tools/debug/. This is maintained by Facebook, and requires a Facebook account to use. Add the URL for the sample app into the URL field. The debugger will provide you with more detail about which og objects are present and which ones are missing:

      Facebook open graph validator

      Notice that the image appears with a title and a description in the Link Preview section.

      You’ve now added an image to your metadata, a Twitter card, and a Facebook Open Graph.

      Conclusion

      In this tutorial, you boosted the SEO of your site using Gatsby’s React Helmet and the SEO component. You’ve also learned how to add images to social media cards to make your site more shareable.

      With the basics of SEO covered, you can now read more about optimizing search for Gatsby at the official Gatsby documentation.





      Source link

      What is a Component?


      A software component is a web service, software package, or module that contains a set of interrelated functions. Components are typically used in front-end frameworks like React and Svelte.

      In component-based software engineering, components are used to separate different functions within an application, upholding the separation of concerns and reusability approach of this form of engineering.

      To learn more about components, follow our tutorial to implement a component in a React project, How to Implement a Modal Component in React.



      Source link