Categories
Gatsby.js

Gatsby.js — SASS, Plugins, Themes, and Data Sources

Gatsby is a static web site framework that’s based on React.

We can use it to create static websites from external data sources and more.

In this article, we’ll look at how to create a site with Gatsby.

Styling with Sass/SCSS

We can use SASS and SCSS to style our components in Gatsby projects.

We just have to create .sass and .scss files and they’ll be compiled to .css automatically.

Working with Plugins

We can add plugins by install the required packages and then add them to our config.

For instance, if we want to add the gatsby-source-filesystem plugin, we run:

npm install gatsby-source-filesystem

Then in gatsby-config.js , we add:

/**
 * Configure your Gatsby site with this file.
 *
 * See: https://www.gatsbyjs.com/docs/gatsby-config/
 */

module.exports = {
  /* Your site config here */
  plugins: [
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/images`,
      },
    },
  ],
}

to add the plugin.

Creating a New Plugin

We can create our own plugin by using the Gatsby plugin starter.

We run:

gatsby new my-plugin https://github.com/gatsbyjs/gatsby-starter-plugin

in our project folder to add the plugin.

Then in gatsby-config.js , we add our plugin by writing:

/**
 * Configure your Gatsby site with this file.
 *
 * See: https://www.gatsbyjs.com/docs/gatsby-config/
 */

module.exports = {
  /* Your site config here */
  plugins: [
    require.resolve(`../my-plugin`),
  ],
}

Themes

Gatsby lets us abstract Gatsby config with themes.

We run:

npm install gatsby-theme-blog

to install the gatsby-theme-blog into our project folder.

To add the theme, we add:

module.exports = {
  plugins: [
    {
      resolve: `gatsby-theme-blog`,
      options: {
        /*
        - basePath defaults to `/`
        */
        basePath: `/blog`,
      },
    },
  ],
}

into gatsby-config.js .

Also, we can create a new project with the given theme by running:

gatsby new {your-project-name} https://github.com/gatsbyjs/gatsby-starter-blog-theme

to create our Gatsby project with the gatsby-starter-blog-theme .

Data Sourcing

We can add our own data sources into our Gatsby project.

To do this, we write:

gatsby-node.js

exports.sourceNodes = ({ actions, createNodeId, createContentDigest }) => {
  const people = [
    { name: "james", age: 20 },
    { name: "mary", age: 23 },
  ]
  people.forEach(({ name, age }) => {
    const node = {
      name,
      age,
      id: createNodeId(`person-${name}`),
      internal: {
        type: "person",
        contentDigest: createContentDigest({ name, age }),
      },
    }
    actions.createNode(node)
  })
}

We add the people array entries as a data source so that they can be queries in the GraphQL API.

The actions.createNode method lets us create the data that we can query.

createNodeId creates the ID for the entry.

createContentDigest creates a stable content digest from a string or an object.

Now when we go to http://localhost:8000/__graphql, we can make the following query:

query MyQuery {
  allPerson {
    nodes {
      id
      name
      age
    }
  }
}

to get the data.

We should get something like:

{
  "data": {
    "allPerson": {
      "nodes": [
        {
          "id": "48340d0f-e756-5cc7-abb2-c6d83821835e",
          "name": "james",
          "age": 20
        },
        {
          "id": "d2eaea74-1415-52b0-b732-2ac106ec6f55",
          "name": "mary",
          "age": 23
        }
      ]
    }
  },
  "extensions": {}
}

returned as the response.

Conclusion

We can use SASS or SCSS, and add plugins, themes, data sources into our Gatsby project.

Categories
Gatsby.js

Gatsby.js — Styling Components

Gatsby is a static web site framework that’s based on React.

We can use it to create static websites from external data sources and more.

In this article, we’ll look at how to create a site with Gatsby.

Styling with CSS

We can add global styles into the src/styles/global.css file:

html {
  background-color: green;
}
p {
  color: maroon;
}

Then in gatsby-browser.js , we add:

import "./src/styles/global.css"

to import the global styles.

Then the styles will be applied everywhere

Layout Styles

We can add the styles to the layout file so that they can be applied to all the child components.

For example, we can write:

src/components/layout.css

html {
  background-color: green;
}
p {
  color: maroon;
}

src/components/layout.js

import { Link } from "gatsby"
import React from "react"
import './layout.css'

export default function Layout({ children }) {
  return (
    <div style={{ margin: `0 auto`, maxWidth: 650, padding: `0 1rem` }}>
      <Link to='/foo'>foo</Link>
      <Link to='/bar'>bar</Link>
      {children}
    </div>
  )
}

src/pages/bar.js

import React from "react"
import Layout from "../components/layout"

export default function Bar() {
  return <Layout>
    <div>bar</div>
  </Layout>
}

src/pages/foo.js

import React from "react"
import Layout from "../components/layout"

export default function Bar() {
  return <Layout>
    <div>bar</div>
  </Layout>
}

Then the styles will be applied to the Foo and Bar pages.

Styled Components

We can use the Styled Components library to create styled components with Gatsby.

To do this, we run:

npm install gatsby-plugin-styled-components styled-components babel-plugin-styled-components

to install the required packages.

Then in gatsby-config.js , we write:

/**
 * Configure your Gatsby site with this file.
 *
 * See: https://www.gatsbyjs.com/docs/gatsby-config/
 */

module.exports = {
  /* Your site config here */
  plugins: [`gatsby-plugin-styled-components`],
}

to add the plugin into our project.

Then we can use it by writing:

src/pages/index.js

import React from "react"
import styled from "styled-components"
const Container = styled.div`
  margin: 3rem auto;
  max-width: 700px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
`
const Avatar = styled.img`
  flex: 0 0 100px;
  width: 96px;
  height: 96px;
  margin: 0;
`
const Username = styled.h2`
  margin: 0 0 12px 0;
  padding: 0;
`
const User = props => (
  <>
    <Avatar src={props.avatar} alt={props.username} />
    <Username>{props.username}</Username>
  </>
)
export default function UsersList() {
  return (
    <Container>
      <User
        username="Jane Doe"
        avatar="https://s3.amazonaws.com/uifaces/faces/twitter/adellecharles/128.jpg"
      />
      <User
        username="Bob Jones"
        avatar="https://s3.amazonaws.com/uifaces/faces/twitter/vladarbatov/128.jpg"
      />
    </Container>
  )
}

We create the Container component which is a styled div.

Avatar is a styled image. And Username is a styled h2 component.

User has the combination of the Avatar and Username components.

CSS Modules

We can use CSS modules in our Gatsby project.

To use it, we can write:

src/pages/index.module.css

.feature {
  margin: 2rem auto;
  max-width: 500px;
  color: red;
}

src/pages/index.js

import React from "react"
import style from "./index.module.css"
export default function Home() {
  return (
    <section className={style.feature}>
      <h1>hello world</h1>
    </section>
  )
}

We just import the CSS as a module into our component.

Then we can apply the classes by accessing the style import as an object with the class name as the property name.

Conclusion

We can style our components in various ways with Gatsby.

Categories
Gatsby.js

Getting Started with Creating Static Sites with Gatsby.js

Gatsby is a static web site framework that’s based on React.

We can use it to create static websites from external data sources and more.

In this article, we’ll look at how to create a site with Gatsby.

Install the Gatsby CLI

We run:

npm install -g gatsby-cli

to install the Gatsby CLI.

Create a New Site

Once we installed the Gatsby CLI, we run:

gatsby new gatsby-site https://github.com/gatsbyjs/gatsby-starter-hello-world

to let Gatsby CLI create a project.

Then we can start developing by running the dev server:

cd gatsby-site
gatsby develop

When we make changes, we’ll see the latest changes displayed.

Create a Production Build

To create a production build, we run:

gatsby build

And to serve the production build locally, we run:

gatsby serve

Pages

We add pages with into the src/pages folder.

And we can link between pages with the Link component.

For example, we can write:

src/pages/foo.js

import { Link } from "gatsby"
import React from "react"

export default function Foo() {
  return <>
    <Link to='/foo'>foo</Link>
    <Link to='/bar'>bar</Link>
    <div>foo</div>
  </>
}

src/pages/bar.js

import React from "react"
import { Link } from "gatsby"

export default function Bar() {
  return <>
    <Link to='/foo'>foo</Link>
    <Link to='/bar'>bar</Link>
    <div>bar</div>
  </>
}

We add the Link component and the links to the pages will be added.

The URL path is determined by the file name.

So foo.js maps to /foo , and bar.js maps to /bar .

Layout

We can create a layout component with Gatsby to add shared markup, styles, and functionality across multiple pages.

To do this, we write:

src/components/layout.js

import { Link } from "gatsby"
import React from "react"

export default function Layout({ children }) {
  return (
    <div style={{ margin: `0 auto`, maxWidth: 650, padding: `0 1rem` }}>
      <Link to='/foo'>foo</Link>
      <Link to='/bar'>bar</Link>
      {children}
    </div>
  )
}

src/pages/foo.js

import React from "react"
import Layout from "../components/layout"

export default function Foo() {
  return <Layout>
    <div>foo</div>
  </Layout>
}

src/pages/bar.js

import React from "react"
import Layout from "../components/layout"

export default function Bar() {
  return <Layout>
    <div>bar</div>
  </Layout>
}

We moved the Link components to layout.js so we can reference everything in one place.

In the Layout component, we have the children prop to render the child components that wrapped inside the Layout component.

Creating Pages Programmatically with createPage

We can create pages programmatically.

To do this, we write:

gatsby-node.js

exports.createPages = ({ actions }) => {
  const { createPage } = actions
  const dogData = [
    {
      name: "fido",
      breed: "Sheltie",
    },
    {
      name: "sparky",
      breed: "Corgi",
    },
  ]
  dogData.forEach(dog => {
    createPage({
      path: `/${dog.name}`,
      component: require.resolve(`./src/templates/dog-template.js`),
      context: { dog },
    })
  })
}

src/templates/dog-template.js

import React from "react"

export default function DogTemplate({ pageContext: { dog } }) {
  return (
    <section>
      {dog.name} - {dog.breed}
    </section>
  )
}

We export the createPages function.

Inside the function, we call the actions.createPage function with the path to the page.

component has the template we want to render the data in.

The context has the data we want to render.

Then in dog-template.js , we get the data from the pageContext prop and render them.

Now when we go to http://localhost:8000/fido, we see:

fido - Sheltie

And when we go to http://localhost:8000/sparky, we see:

sparky - Corgi

Conclusion

We can add pages manually and automatically with Gatsby.js

Categories
NativeScript React

NativeScript React — Navigation

React is an easy to use framework for building front end apps.

NativeScript is a mobile app framework that lets us build native mobile apps with popular front end frameworks.

In this article, we’ll look at how to build an app with NativeScript React.

Navigation

We can use the react-nativescript-navigation package to add navigation to our app.

To install the package, we run:

npm install --save react-nativescript-navigation @react-navigation/native

Tab Navigation

Once we installed the package, we can add tab navigation by using the TabNavigator object.

For instance, we can write:

import * as React from "react";
import { BaseNavigationContainer } from '@react-navigation/core';
import { stackNavigatorFactory, tabNavigatorFactory } from "react-nativescript-navigation";

const TabNavigator = tabNavigatorFactory();

function First({ navigation }) {
  function onButtonTap() {
    navigation.navigate('second');
  }

  return (
    <flexboxLayout
      style={{
        flexGrow: 1,
        width: "100%",
        height: "100%",
        flexDirection: "column",
        alignItems: "center",
        justifyContent: "center",
        backgroundColor: "yellow",
      }}
    >
      <label fontSize={24} text={"first route!"} />
      <button onTap={onButtonTap} fontSize={24} text={"Go to next route"} />
    </flexboxLayout>
  );
}

function Second({ navigation }) {
  function onButtonTap() {
    navigation.goBack();
  }

  return (
    <flexboxLayout
      style={{
        flexGrow: 1,
        flexDirection: "column",
        alignItems: "center",
        justifyContent: "center",
        backgroundColor: "gold",
      }}
    >
      <label fontSize={24} text={"second route!"} />
      <button onTap={onButtonTap} fontSize={24} text={"Go back"} />
    </flexboxLayout>
  );
}

export default function Greeting({ }) {
  return (
    <frame>
      <page>
        <actionBar title="My App">
        </actionBar>
        <BaseNavigationContainer>
          <TabNavigator.Navigator initialRouteName="first">
            <TabNavigator.Screen name="first" component={First} />
            <TabNavigator.Screen name="second" component={Second} />
          </TabNavigator.Navigator>
        </BaseNavigationContainer>
      </page>
    </frame>
  );
}

We call the tabNavigationFactory to create the TabNavigator object.

It has the TabNavigator.Navigator component to add navigation.

And the TabNavigator.Screen component adds the screens for the navigation.

The name prop has the name of the screen.

The First and Second components are added as the screens.

First and Second have the navigation prop, which has the navigate method to navigate to the screen we want by its name.

The goBack method goes back to the previous screen.

Stack Navigation

If we don’t want to add tabs into our app but want to add navigation, we can use the StackNavigator object.

To do this, we write:

import * as React from "react";
import { BaseNavigationContainer } from '@react-navigation/core';
import { stackNavigatorFactory, tabNavigatorFactory } from "react-nativescript-navigation";

const StackNavigator = stackNavigatorFactory();

function First({ navigation }) {
  function onButtonTap() {
    navigation.navigate('second');
  }

  return (
    <flexboxLayout
      style={{
        flexGrow: 1,
        width: "100%",
        height: "100%",
        flexDirection: "column",
        alignItems: "center",
        justifyContent: "center",
        backgroundColor: "yellow",
      }}
    >
      <label fontSize={24} text={"first route!"} />
      <button onTap={onButtonTap} fontSize={24} text={"Go to next route"} />
    </flexboxLayout>
  );
}

function Second({ navigation }) {
  function onButtonTap() {
    navigation.goBack();
  }

  return (
    <flexboxLayout
      style={{
        flexGrow: 1,
        flexDirection: "column",
        alignItems: "center",
        justifyContent: "center",
        backgroundColor: "gold",
      }}
    >
      <label fontSize={24} text={"second route!"} />
      <button onTap={onButtonTap} fontSize={24} text={"Go back"} />
    </flexboxLayout>
  );
}

export default function Greeting({ }) {
  return (
    <frame>
      <page>
        <actionBar title="My App">
        </actionBar>
        <BaseNavigationContainer>
          <StackNavigator.Navigator initialRouteName="first">
            <StackNavigator.Screen name="first" component={First} />
            <StackNavigator.Screen name="second" component={Second} />
          </StackNavigator.Navigator>
        </BaseNavigationContainer>
      </page>
    </frame>
  );
}

We have similar code as the TabNavigator , the only difference is that we replaced it with StackNavigator .

StackNavigator is created with the stackNavigatorFactory function.

Then we see the screens rendered and we can navigate by tapping on the buttons.

Conclusion

We can add navigation into our React NativeScript app with the react-nativescript-navigation package.

Categories
NativeScript React

NativeScript React — Text View, Time Picker, and Web View

React is an easy to use framework for building front end apps.

NativeScript is a mobile app framework that lets us build native mobile apps with popular front end frameworks.

In this article, we’ll look at how to build an app with NativeScript React.

TextView

A textView is a UI component that shows an editable or read-only multiline text container.

For example, we can use it by writing:

import * as React from "react";

export default function Greeting({ }) {
  return (
    <frame>
      <page>
        <actionBar title="My App">
        </actionBar>
        <stackLayout horizontalAlignment='center'>
          <textView text="MultiLine Text" />
        </stackLayout>
      </page>
    </frame>
  );
}

to add some text onto the screen.

The text prop has the text.

We can also add formatted text with:

import * as React from "react";

export default function Greeting({ }) {
  return (
    <frame>
      <page>
        <actionBar title="My App">
        </actionBar>
        <stackLayout horizontalAlignment='center'>
          <textView >
            <formattedString>
              <span text="You can use text attributes such as " />
              <span text="bold, " fontWeight="bold" />
              <span text="italic " fontStyle="italic" />
              <span text="and " />
              <span text="underline." textDecoration="underline" />
            </formattedString>
          </textView>
        </stackLayout>
      </page>
    </frame>
  );
}

We add the formattedString and span components in our text view to add styled text.

We add the styling with various props.

TimePicker

The timePicker component lets us select a time.

For instance, we can use it by writing:

import * as React from "react";

export default function Greeting({ }) {
  const [selectedHour, setSelectedHour] = React.useState(0)
  const [selectedMinute, setSelectedMinute] = React.useState(0)
  return (
    <frame>
      <page>
        <actionBar title="My App">
        </actionBar>
        <stackLayout horizontalAlignment='center'>
          <timePicker
            hour={selectedHour}
            minute={selectedMinute}
            onTimeChange={({ value }) => {
              setSelectedHour((value as Date).getHours())
              setSelectedMinute((value as Date).getMinutes())
            }}
          />
        </stackLayout>
      </page>
    </frame>
  );
}

We add the timePicker component with the hour prop to set the hour on the time picker.

minute sets the minute on the time picker.

onTimeChange is a function to set the hour and minute.

We can restrict the values that can be picked with the maxHour , minHour , maxMinute , and minMinute props.

WebView

A webView is a UI component that lets us show web content in our app.

We can write:

import * as React from "react";

export default function Greeting({ }) {
  return (
    <frame>
      <page>
        <actionBar title="My App">
        </actionBar>
        <stackLayout horizontalAlignment='center'>
          <webView src="http://nativescript-vue.org/" />
        </stackLayout>
      </page>
    </frame>
  );
}

to show the content of a given URL.

Also, we can show static HTML:

import * as React from "react";

export default function Greeting({ }) {
  return (
    <frame>
      <page>
        <actionBar title="My App">
        </actionBar>
        <stackLayout horizontalAlignment='center'>
          <webView src="<div><h1>Some static HTML</h1></div>" />
        </stackLayout>
      </page>
    </frame>
  );
}

And we can display content from a file:

assets/index.html

<p>hello world</p>

components/AppContainer.tsx

import * as React from "react";

export default function Greeting({ }) {
  return (
    <frame>
      <page>
        <actionBar title="My App">
        </actionBar>
        <stackLayout horizontalAlignment='center'>
          <webView src="~/assets/index.html" />
        </stackLayout>
      </page>
    </frame>
  );
}

Then we see ‘hello world’ displayed.

Conclusion

We can add a web view, text view, and time picker into our app with React NativeScript.