Categories
NativeScript React

NativeScript React — Flexbox and Grid Layouts

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.

Flexbox Layout with Justify Content

We can set the justifyContent prop of a flexboxLayout to add spacing between the child components.

For example, we can write:

import * as React from "react";

export default function Greeting({ }) {
  return (
    <flexboxLayout
      flexDirection="column-reverse"
      justifyContent="space-around"
      backgroundColor="#3c495e"
    >
      <label text="first" height={70} backgroundColor="red" />
      <label
        text="second"
        alignSelf="center"
        width={70}
        height={70}
        backgroundColor="green"
      />
      <label
        text="thirdnflex-end"
        alignSelf="flex-end"
        width={70}
        height={70}
        backgroundColor="blue"
      />
      <label text="fourth" height={70} backgroundColor="yellow" />
    </flexboxLayout>
  );
}

space-around adds space around the label s.

column-reverse place items in a column, starting from the bottom.

alignSelf changes the position of items across the main axis.

GridLayout

We can use the GridLayout component to place items in a grid.

For example, we can write:

import * as React from "react";

export default function Greeting({ }) {
  return (
    <gridLayout
      columns="115, 115"
      rows="115, 115"
    >
      <label text="0,0" row={0} col={0} backgroundColor="red" />
      <label text="0,1" row={0} col={1} backgroundColor="green" />
      <label text="1,0" row={1} col={0} backgroundColor="blue" />
      <label text="1,1" row={1} col={1} backgroundColor="yellow" />
    </gridLayout>
  );
}

We add the label s and set their location with the row and col props.

The columns and rows props have the width of the columns and the height of the rows respectively.

Grid Layout with Star Sizing

We can set the star sizing to allot space proportionally to child elements.

For instance, we can write:

import * as React from "react";

export default function Greeting({ }) {
  return (
    <gridLayout
      columns="*, 2*"
      rows="2*, 3*"
      backgroundColor="#3c495e"
    >
      <label text="0,0" row={0} col={0} backgroundColor="red" />
      <label text="0,1" row={0} col={1} backgroundColor="green" />
      <label text="1,0" row={1} col={0} backgroundColor="blue" />
      <label text="1,1" row={1} col={1} backgroundColor="yellow" />
    </gridLayout>
  );
}

The columns prop sets the first column to take 1/3 of the screen’s width and the 2nd column takes 2/3.

And the rows prop sets the first column to take 2/5 of the screen’s width and the 2nd column takes 3/5.

Grid Layout with Fixed and Auto-Sizing

We can mix fixed-size items with automatically sized items.

For instance, we can write:

import * as React from "react";

export default function Greeting({ }) {
  return (
    <gridLayout
      columns="80, auto"
      rows="80, 80"
      backgroundColor="#3c495e"
    >
      <label text="0,0" row={0} col={0} backgroundColor="red" />
      <label text="0,1" row={0} col={1} backgroundColor="green" />
      <label text="1,0" row={1} col={0} backgroundColor="blue" />
      <label text="1,1" row={1} col={1} backgroundColor="yellow" />
    </gridLayout>
  );
}

We set the columns prop to 80px and automatically sized to fit the content with auto respectively.

And we set both rows to have 80px height respectively.

Conclusion

We can add flexbox and grid layouts into our mobile app with React NativeScript.

Categories
NativeScript React

NativeScript React — Dock and Flexbox Layouts

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.

Dock Multiple Children to the Same Side

We can dock multiple child components on the same side.

For example, we can write:

import * as React from "react";

export default function Greeting({ }) {
  return (
    <dockLayout stretchLastChild backgroundColor="#3c495e">
      <label text="left 1" dock="left" width={40} backgroundColor="red" />
      <label text="left 2" dock="left" width={40} backgroundColor="green" />
      <label text="left 3" dock="left" width={40} backgroundColor="blue" />
      <label text="last child" backgroundColor="yellow" />
    </dockLayout>
  );
}

We set dock to left on the first 3 label s, so we have them display side by side.

FlexboxLayout

We can add a flexboxLayout component to arrange child components with flexbox CSS properties.

For example, we can write:

import * as React from "react";

export default function Greeting({ }) {
  return (
    <flexboxLayout backgroundColor="#3c495e">
      <label text="first" width={70} backgroundColor="red" />
      <label text="second" width={70} backgroundColor="green" />
      <label text="third" width={70} backgroundColor="blue" />
    </flexboxLayout>
  );
}

We add the label s and they’ll be displayed side by side.

Also, we can set the flexDirection to 'column' so that we stack the child components:

import * as React from "react";

export default function Greeting({ }) {
  return (
    <flexboxLayout flexDirection="column" backgroundColor="#3c495e">
      <label text="first" height={70} backgroundColor="red" />
      <label text="second" height={70} backgroundColor="green" />
      <label text="third" height={70} backgroundColor="blue" />
    </flexboxLayout>
  );
}

We set the alignItems prop to align the items the way we want in the flexboxLayout container:

import * as React from "react";

export default function Greeting({ }) {
  return (
    <flexboxLayout alignItems="flex-start" backgroundColor="#3c495e">
      <label text="first" width={70} height={70} backgroundColor="red" />
      <label text="second" width={70} height={70} backgroundColor="green" />
      <label text="third" width={70} height={70} backgroundColor="blue" />
    </flexboxLayout>
  );
}

We set alignItems to flex-start to put the label s side by side in the top left corner.

Also, we can set the order prop by writing:

import * as React from "react";

export default function Greeting({ }) {
  return (
    <flexboxLayout alignItems="flex-start" backgroundColor="#3c495e">
      <label text="first" order={2} width={70} height={70} backgroundColor="red" />
      <label text="second" order={3} width={70} height={70} backgroundColor="green" />
      <label text="third" order={1} width={70} height={70} backgroundColor="blue" />
    </flexboxLayout>
  );
}

This way, we switch the order of the label s.

Rows can be wrapped if we set the flexWrap prop to 'wrap' :

import * as React from "react";

export default function Greeting({ }) {
  return (
    <flexboxLayout flexWrap="wrap" backgroundColor="#3c495e">
      <label text="first" width='30%' backgroundColor="red" />
      <label text="second" width='30%' backgroundColor="green" />
      <label text="third" width='30%' backgroundColor="blue" />
      <label text="fourth" width='30%' backgroundColor="yellow" />
    </flexboxLayout>
  );
}

We set the width of each label to 30%, so the last one will show in the 2nd row.

Conclusion

We can add dock and flex layouts into our mobile app with NativeScript React.

Categories
NativeScript React

Getting Started with Mobile Development with NativeScript React

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.

Install NativeScript

We start by install the nativescript Node package globally by running:

npm install -g nativescript

Create the App Project

Once we installed the package, we create the project by writing:

tns create my-blank-react --react

Then we can run tns run android to run the project after going into the folder.

This should be done as an admin user. Then we can select Configure for Local Build and let it install all the packages that are required to run the project.

If Genymotion is started, then you should see the project.

First App

Once we create the project, then we should see the AppContainer.tsx file.

It is the entry point component for our app.

And it has the following code:

import * as React from "react";
import { Dialogs } from "@nativescript/core";

export default function Greeting({ }) {
  return (
    <gridLayout
      width={"100%"}
      height={"100%"}
      rows={"*, auto, auto, *"}
      columns={"*, 200, *"}
    >
      <label
        row={1}
        col={1}
        className="info"
        textAlignment={"center"}
        fontSize={24}
      >
        <formattedString>
          <span className="fas" text="&#xf135;" />
          <span> Hello World!</span>
        </formattedString>
      </label>
      <button
        row={2}
        col={1}
        fontSize={24}
        textAlignment={"center"}
        onTap={() => Dialogs.alert("Tap received!")}
      >
        Tap me
      </button>
    </gridLayout>
  );
}

We see a button to open a dialog.

The dialog is displayed with the Dialogs.alert method.

AbsoluteLayout

We can add position components on a page with absoluteLayout .

For example, we can write:

import * as React from "react";

export default function Greeting({ }) {
  return (
    <absoluteLayout backgroundColor="#3c495e">
      <label text="10,10" left={10} top={10} width={100} height={100} backgroundColor="red" />
      <label text="120,10" left={120} top={10} width={100} height={100} backgroundColor="green" />
      <label text="10,120" left={10} top={120} width={100} height={100} backgroundColor="blue" />
      <label text="120,120" left={120} top={120} width={100} height={100} backgroundColor="yellow" />
    </absoluteLayout>
  );
}

We add the absoluteLayout component to add our layout.

Then we add the label components inside it to show boxes with the given background color, width, and height.

left and top sets the x and y coordinates of the top left corner of the components.

We can add components that overlap with absoluteLayout .

For example, we can write:

import * as React from "react";

export default function Greeting({ }) {
  return (
    <absoluteLayout backgroundColor="#3c495e">
      <label text="10,10" left={10} top={10} width={100} height={100} backgroundColor="red" />
      <label text="30,40" left={30} top={40} width={100} height={100} backgroundColor="yellow" />
    </absoluteLayout>
  );
}

We set the left and top props so that the label s overlap each other.

DockLayout

The dockLayout lets us add a layout where the components snap to the left, right, top, or bottom of the screen.

For example, we can write:

import * as React from "react";

export default function Greeting({ }) {
  return (
    <dockLayout stretchLastChild={false} backgroundColor="#3c495e">
      <label text="left" dock="left" width={40} backgroundColor="red" />
      <label text="top" dock="top" height={40} backgroundColor="green" />
      <label text="right" dock="right" width={40} backgroundColor="blue" />
      <label text="bottom" dock="bottom" height={40} backgroundColor="yellow" />
    </dockLayout>
  );
}

to add label s to the edges of the screen.

The dock prop sets the location that the label s are docked to.

stretchLastChild lets us stretch the last child component to the nearest components if it’s true .

If we set stretchLastChild to true :

import * as React from "react";

export default function Greeting({ }) {
  return (
    <dockLayout stretchLastChild backgroundColor="#3c495e">
      <label text="left" dock="left" width={40} backgroundColor="red" />
      <label text="top" dock="top" height={40} backgroundColor="green" />
      <label text="right" dock="right" width={40} backgroundColor="blue" />
      <label text="bottom" dock="bottom" backgroundColor="yellow" />
    </dockLayout>
  );
}

Then the ‘bottom’ label is stretched to meet the other label s.

Conclusion

We can create a simple mobile app with various layouts in our mobile app with NativeScript React.

Categories
React D3

Adding Graphics to a React App with D3 — Bar Chart

D3 lets us add graphics to a front-end web app easily.

Vue is a popular front end web framework.

They work great together. In this article, we’ll look at how to add graphics to a Vue app with D3.

Create a Bar Chart

We can create a bar chart with D3 in our React app by reading in the data, creating the axes, and adding the bars.

For example, we can write:

public/data.csv

year,population
2006,20
2008,25
2010,38
2012,61
2014,43
2016,26
2017,62

src/App.js

import React, { useEffect } from "react";
import * as d3 from "d3";

const createBarChart = async () => {
  const svg = d3.select("svg"),
    margin = 200,
    width = svg.attr("width") - margin,
    height = svg.attr("height") - margin;

  svg
    .append("text")
    .attr("transform", "translate(100,0)")
    .attr("x", 50)
    .attr("y", 50)
    .attr("font-size", "20px")
    .attr("class", "title")
    .text("Population bar chart");

  const x = d3.scaleBand().range([0, width]).padding(0.4),
    y = d3.scaleLinear().range([height, 0]);
  const g = svg.append("g").attr("transform", "translate(100, 100)");
  const data = await d3.csv("data.csv");

  x.domain(
    data.map(function (d) {
      return d.year;
    })
  );
  y.domain([
    0,
    d3.max(data, function (d) {
      return d.population;
    })
  ]);

  g.append("g")
    .attr("transform", `translate(0, ${height})`)
    .call(d3.axisBottom(x))
    .append("text")
    .attr("y", height - 250)
    .attr("x", width - 100)
    .attr("text-anchor", "end")
    .attr("font-size", "18px")
    .attr("stroke", "blue")
    .text("year");

  g.append("g")
    .append("text")
    .attr("transform", "rotate(-90)")
    .attr("y", 6)
    .attr("dy", "-5.1em")
    .attr("text-anchor", "end")
    .attr("font-size", "18px")
    .attr("stroke", "blue")
    .text("population");

  g.append("g").attr("transform", "translate(0, 0)").call(d3.axisLeft(y));
  g.selectAll(".bar")
    .data(data)
    .enter()
    .append("rect")
    .attr("class", "bar")
    .style("fill", "lightgreen")
    .on("mouseover", onMouseOver)
    .on("mouseout", onMouseOut)
    .attr("x", function (d) {
      return x(d.year);
    })
    .attr("y", function (d) {
      return y(d.population);
    })
    .attr("width", x.bandwidth())
    .transition()
    .ease(d3.easeLinear)
    .duration(200)
    .delay(function (d, i) {
      return i * 25;
    })
    .attr("height", function (d) {
      return height - y(d.population);
    });

  function onMouseOver(d, i) {
    d3.select(this).attr("class", "highlight");

    d3.select(this)
      .transition()
      .duration(200)
      .attr("width", x.bandwidth() + 5)
      .attr("y", function (d) {
        return y(d.population) - 10;
      })
      .attr("height", function (d) {
        return height - y(d.population) + 10;
      });

    g.append("text")
      .attr("class", "val")
      .attr("x", function () {
        return x(d.year);
      })
      .attr("y", function () {
        return y(d.value) - 10;
      });
  }

  function onMouseOut(d, i) {
    d3.select(this).attr("class", "bar");

    d3.select(this)
      .transition()
      .duration(200)
      .attr("width", x.bandwidth())
      .attr("y", function (d) {
        return y(d.population);
      })
      .attr("height", function (d) {
        return height - y(d.population);
      });

     d3.selectAll(".val").remove();
  }
};

export default function App() {
  useEffect(() => {
    createBarChart();
  }, []);

  return (
    <div className="App">
      <svg width="500" height="500"></svg>
    </div>
  );
}

We add the svg element in our template.

Then we create the title by writing:

svg
  .append("text")
  .attr("transform", "translate(100,0)")
  .attr("x", 50)
  .attr("y", 50)
  .attr("font-size", "20px")
  .attr("class", "title")
  .text("Population bar chart");

x and y are the x and y coordinates of the top left corner of the text.

transform transforms the text by translating it.

The font-size has the font size for the title.

Then we create the x and y ranges we use for the axes:

const x = d3.scaleBand().range([0, width]).padding(0.4),
  y = d3.scaleLinear().range([height, 0]);
const g = svg.append("g").attr("transform", "translate(100, 100)");
const data = await d3.csv("data.csv");

x.domain(
  data.map(function(d) {
    return d.year;
  })
);
y.domain([
  0,
  d3.max(data, function(d) {
    return d.population;
  }),
]);

We set the domain of x and y with the domain method.

Then we create the x-axis with the axisBottom method:

g.append("g")
  .attr("transform", `translate(0, ${height})`)
  .call(d3.axisBottom(x))
  .append("text")
  .attr("y", height - 250)
  .attr("x", width - 100)
  .attr("text-anchor", "end")
  .attr("font-size", "18px")
  .attr("stroke", "blue")
  .text("year");

The attr method sets all the CSS styles.

Then we add the label for the y-axis by writing:

g.append("g")
  .append("text")
  .attr("transform", "rotate(-90)")
  .attr("y", 6)
  .attr("dy", "-5.1em")
  .attr("text-anchor", "end")
  .attr("font-size", "18px")
  .attr("stroke", "blue")
  .text("population");

Then we add the y-axis itself by writing:

g.append("g").attr("transform", "translate(0, 0)").call(d3.axisLeft(y));

And we add the bars by writing:

g.selectAll(".bar")
  .data(data)
  .enter()
  .append("rect")
  .attr("class", "bar")
  .style("fill", "lightgreen")
  .on("mouseover", onMouseOver)
  .on("mouseout", onMouseOut)
  .attr("x", function(d) {
    return x(d.year);
  })
  .attr("y", function(d) {
    return y(d.population);
  })
  .attr("width", x.bandwidth())
  .transition()
  .ease(d3.easeLinear)
  .duration(200)
  .delay(function(d, i) {
    return i * 25;
  })
  .attr("height", function(d) {
    return height - y(d.population);
  });

We add a mouseover event listener that expands the bar when we hover our mouse over it.

Also, we add the mouseout event listener to restore the bar to its original size when we move our mouse away from the bar.

We set the x and y attributes so that we can position it on the x-axis.

Then, we add some transition to it when it’s loading with the transition , ease , and duration calls.

And finally, we set the height of the bar to by setting the height attribute in the last attr call.

Conclusion

We can create a bar chart from CSV data with D3.

Categories
React D3

Adding Graphics to a React App with D3 — Loading JSON, XML, and TSV

D3 lets us add graphics to a front-end web app easily.

Vue is a popular front end web framework.

They work great together. In this article, we’ll look at how to add graphics to a Vue app with D3.

Loading JSON

We can load JSON stored in an external file.

For example, we can write:

public/data.json

[
  {
    "name": "John",
    "age": 30,
    "city": "New York"
  },
  {
    "name": "Jane",
    "age": 20,
    "city": "San Francisco"
  }
]

src/App.js

import React, { useEffect } from "react";
import * as d3 from "d3";

const readJson = async () => {
  const data = await d3.json("/data.json");
  for (const { name, age } of data) {
    console.log(name, age);
  }
};

export default function App() {
  useEffect(() => {
    readJson();
  }, []);

  return <div className="App"></div>;
}

We have the readJson function that reads data from data.json .

And then we loop through the data array that has the parsed entries.

We get:

John 30
Jane 20

logged.

Loading XML File

D3 also comes with the d3.xml method to load the XML file.

For instance, we can write:

public/data.xml

<?xml version="1.0" encoding="UTF-8"?>
<root>
<row>
    <name>John</name>
    <age>30</age>
</row>
<row>
    <name>Jane</name>
    <age>32</age>
</row>
</root>

src/App.js

import React, { useEffect } from "react";
import * as d3 from "d3";

const readXml = async () => {
  const data = await d3.xml("/data.xml");
  for (const n of data.documentElement.getElementsByTagName("name")) {
    console.log(n.textContent);
  }
};

export default function App() {
  useEffect(() => {
    readXml();
  }, []);

  return <div className="App"></div>;
}

In the readXml function, we call d3.xml to read the data.

Then we get the elements with the name tag and then loop through the returned items.

Loading Tab Separated Files

We can load tab-separated files with the d3.tsv method.

For example, we can write:

public/data.tsv

name age city
John 30 New York
Jane 20 San Francisco

src/App.js

import React, { useEffect } from "react";
import * as d3 from "d3";

const readTsv = async () => {
  const data = await d3.tsv("/data.tsv");
  for (const { name, age, city } of data) {
    console.log(name, age, city);
  }
};

export default function App() {
  useEffect(() => {
    readTsv();
  }, []);

  return <div className="App"></div>;
}

We call the readTsv method.

And then we loop through the parsed rows and log them.

Then we get:

John 30 New York
Jane 20 San Francisco

logged in the console.

Conclusion

We can load CSV, TSV, XML, and JSON files with D3 in our Vue app.