Categories
NativeScript React

NativeScript React — Segmented Bar and Inputs

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.

SegmentedBar

The segmentBar component lets us add a UI bar that displays a set of buttons for discrete selection.

We can show text or images on the buttons.

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>
        <flexboxLayout justifyContent='center' >
          <segmentedBar>
            <segmentedBarItem title="First" />
            <segmentedBarItem title="Second" />
            <segmentedBarItem title="Third" />
          </segmentedBar>
        </flexboxLayout>
      </page>
    </frame>
  );
}

We add the segmentedBar into our app.

Then we add the segmentedBarItem into our bar to show some items.

We can also get and set the index of the item selected with:

import * as React from "react";

export default function Greeting({ }) {
  return (
    <frame>
      <page>
        <actionBar title="My App">
        </actionBar>
        <flexboxLayout justifyContent='center' >
          <segmentedBar
            selectedIndex={0}
            onSelectedIndexChange={({ value }) => {
              console.log(value)
            }}
          >
            <segmentedBarItem title="First" />
            <segmentedBarItem title="Second" />
            <segmentedBarItem title="Third" />
          </segmentedBar>
        </flexboxLayout>
      </page>
    </frame>
  );
}

selectedIndex has the index of the item we want to select by default.

And onSelectedIndexChange has a function that gets the value of the index of the latest selected item.

value has the index.

Slider

A slider is a UI component that gives us a slider control for picking values in a specified numeric range.

For example, we can write:

import * as React from "react";

export default function Greeting({ }) {
  const [val, setVal] = React.useState(0)
  return (
    <frame>
      <page>
        <actionBar title="My App">
        </actionBar>
        <flexboxLayout justifyContent='center' >
          <slider value={val} onValueChange={({ value }) => setVal(value)} />
        </flexboxLayout>
      </page>
    </frame>
  );
}

to add the slider component into our app.

We set the value to the val state.

And we get the value and set the value of val in the onValueChange callback.

Switch

A switch lets us toggle between 2 states.

For example, we can write:

import * as React from "react";

export default function Greeting({ }) {
  const [val, setVal] = React.useState(true)
  return (
    <frame>
      <page>
        <actionBar title="My App">
        </actionBar>
        <stackLayout horizontalAlignment='center'>
          <switch
            checked={val}
            onCheckedChange={({ value }) => setVal(value)}
          />
          <label text={val.toString()} style={{ textAlignment: 'center' }} />
        </stackLayout>
      </page>
    </frame>
  );
}

We add the switch component with the checked prop to set the checked value.

onCheckChange has a function to get the checked value of the and we set that as the value of the val state.

TextField

The textField component is an input component for letting users enter a line of text.

For instance, we can write:

import * as React from "react";

export default function Greeting({ }) {
  const [textFieldValue, setTextFieldValue] = React.useState()
  return (
    <frame>
      <page>
        <actionBar title="My App">
        </actionBar>
        <stackLayout horizontalAlignment='center'>
          <textField
            text={textFieldValue}
            hint="Enter text..."
            onTextChange={({ value }) => setTextFieldValue(value)}
          />
          <label text={textFieldValue} style={{ textAlignment: 'center' }} />
        </stackLayout>
      </page>
    </frame>
  );
}

We add the textField and listen to the onTextChange event to get the latest entered value.

text has the entered text.

hint is the placeholder for the text field.

Conclusion

We can add a segmented bar, text input, slider, and switch into our mobile app with React NativeScript.

Categories
NativeScript React

NativeScript React — Nav Buttons, Progress Bar, Scroll View, and Search Box

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.

NavigationButton

We can add a navigationButton component to the actionBar to add a button into the top bar.

For example, we can write:

import * as React from "react";

export default function Greeting({ }) {
  return (
    <frame>
      <page>
        <actionBar title="My App">
          <navigationButton
            nodeRole="navigationButton"
            text="Go back"
            android={{
              position: undefined,
              systemIcon: "ic_menu_back"
            }}
            onTap={() => { }}
          />
        </actionBar>
        <flexboxLayout justifyContent='center' >
        </flexboxLayout>
      </page>
    </frame>
  );
}

to add the button.

We add the onTap prop to add a function to run when we tap on the button.

Page

The page component lets us add an app screen into our app.

To use it, we can write:

import * as React from "react";

export default function Greeting({ }) {
  return (
    <frame>
      <page>
        <actionBar title="My App">
        </actionBar>
        <flexboxLayout justifyContent='center' >
        </flexboxLayout>
      </page>
    </frame>
  );
}

We can set various props like stratus bar style, background under the status bar, and more.

Progress

The progress component lets us show a bar to indicate the progress of a task

For example, we can write:

import * as React from "react";

export default function Greeting({ }) {
  return (
    <frame>
      <page>
        <actionBar title="My App">
        </actionBar>
        <flexboxLayout justifyContent='center' >
          <progress value={50} maxValue={100} />
        </flexboxLayout>
      </page>
    </frame>
  );
}

to add a progress bar into our app.

ScrollView

A scrollView component lets us show a scrollable content area.

Content can be scrolled vertically or horizontally.

For example, we can write:

import * as React from "react";

export default function Greeting({ }) {
  return (
    <frame>
      <page>
        <actionBar title="My App">
        </actionBar>
        <flexboxLayout justifyContent='center' >
          <scrollView orientation="horizontal">
            <stackLayout orientation="horizontal">
              {Array(100)
                .fill(undefined)
                .map((_, i) => <label
                  key={i}
                  text={i.toString()}
                  style={{ width: 30 }}
                />)
              }
            </stackLayout>
          </scrollView>
        </flexboxLayout>
      </page>
    </frame>
  );
}

to render an array of numbers and make the scroll view and stack layout scrollable horizontally with the orientation prop set to horizontal .

SearchBar

We can use the searchBar component to add a search bar into our app.

For example, we can write:

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

export default function Greeting({ }) {
  const [value, setValue] = React.useState()
  return (
    <frame>
      <page>
        <actionBar title="My App">
        </actionBar>
        <flexboxLayout justifyContent='center' >
          <searchBar
            hint="Search hint"
            text="searchPhrase"
            onTextChange={({ value }) => setValue(value)}
            onSubmit={() => Dialogs.alert(value)}
            onClose={() => console.log('close')}
          />
        </flexboxLayout>
      </page>
    </frame>
  );
}

We add the searchBar component with the hint prop to add a placeholder into the search box.

text has the default value of the text that we enter into the search box.

onTextChange has a function that’s called when we enter something into the box.

We can get what we enter with the value property from the parameter.

onSubmit is called when we press Enter.

onClose is called when we tap the close button.

Conclusion

We can add navigation buttons, progress bar, scroll view, and search bar into our React NativeScript app.

Categories
NativeScript React

NativeScript React — Updating List Views and List Pickers

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.

Updating the List of Items in the ListView

We can push more items to the array when we pull down the list view.

For example, we can write:

import { ItemEventData, ObservableArray } from "@nativescript/core";
import * as React from "react";
import { ListView } from "react-nativescript";

type MyItem = { text: string };

const itemsToLoad: number = 100;
const items: ObservableArray<MyItem> = new ObservableArray(
  [...Array(itemsToLoad).keys()]
    .map((value: number) => ({ text: `Item ${value.toString()}` }))
);

const cellFactory = (item: MyItem) => {
  return <label text={item.text} />;
};

const onItemTap = ({ index }: ItemEventData) => {
  const { text }: MyItem = items[index];
  console.log(`Tapped item index ${index}: "${text}".`);
};

export default function Greeting({ }) {
  const loadMoreRef = React.useRef(true);
  const loadMoreTimeoutRef = React.useRef(undefined);

  React.useEffect(() => {
    clearTimeout(loadMoreTimeoutRef.current!);
  }, []);

  const onLoadMoreItems = (args: ItemEventData) => {
    if (!loadMoreRef.current) {
      console.log(`[onLoadMoreItems] debouncing.`);
      return;
    }

    console.log(`[onLoadMoreItems] permitted.`);

    loadMoreTimeoutRef.current = setTimeout(
      () => {
        const itemsToPush: MyItem[] = [];

        for (let i = items.length; i < + items.length + itemsToLoad; i++) {
          const lastValueIncremented: number = i;

          itemsToPush.push({
            text: `Item ${lastValueIncremented.toString()}`
          });
        }

    items.push(itemsToPush);
        loadMoreRef.current = true;
      },
      750
    );

    loadMoreRef.current = false;
  };

  return (
    <frame>
      <page>
        <actionBar title="Default Page Title" />
        <flexboxLayout justifyContent='center' >
          <ListView
            items={items}
            cellFactory={cellFactory}
            onItemTap={onItemTap}
            onLoadMoreItems={onLoadMoreItems}
          />
        </flexboxLayout>
      </page>
    </frame>
  );
}

The items array is an ObservableArray , which we can listen to changes for.

We have the cellFactory function to return the row we render.

Then in the Greeting component, we have the the useRef hook for storing our timer.

We assign the timer in the onLoadMoreItem function.

When loadMoreRef.current is true , we call itemsToPush.push to load more data.

Then once we created the timer, we set loadMoreRef.current to false so we stop loading the data in the next render cycle.

In the ListView , we add the onLoadMoreItems prop to run the onLoadMoreItems function.

ListPicker

The ListPicker component lets us select a value from a preconfigured list.

For example, we can write:

import * as React from "react";
import { EventData, ListPicker } from "@nativescript/core";

const listOfItems = ['apple', 'orange', 'grape']

export default function Greeting({ }) {
  return (
    <frame>
      <page>
        <actionBar title="Default Page Title" />
        <flexboxLayout justifyContent='center' >
          <listPicker
            items={listOfItems}
            selectedIndex={0}
            onSelectedIndexChange={(args: EventData) => {
              const listPicker: ListPicker = args.object as ListPicker;
              const { selectedIndex } = listPicker;
              const item = listPicker.items[selectedIndex];
              console.log(item)
            }}
          />
        </flexboxLayout>
      </page>
    </frame>
  );
}

We add the listPicker component with the items prop to set the items we can pick.

selectedIndex sets the index of the item that’s selected by default.

onSelectedIndexChange has a function to get the item that’s chosen.

Conclusion

We can add a list picker and load more items as we pull down a list view with React NativeScript

Categories
JavaScript

Common JavaScript Mistakes — Part 3

JavaScript is a language that’s friendlier than many other programming languages in the world. However, it’s still very easy to make mistakes when writing JavaScript code through misunderstanding or overlooking stuff that we already know. By avoiding some of the mistakes below, we can make our lives easier by preventing bugs and typos in our code that bog us down with unexpected results.


Trying to Overload Functions

Functional overloading is a feature of some programming languages where you can declare functions with the same name but different signatures. In JavaScript, we can’t overload functions. Whenever a function is declared more than once, the one that is declared later overwrites the one that’s declared earlier. This is because functions are objects and declaring a function is like assigning an object to a variable. When you assign an object to a variable more than once, then the value that’s assigned later will overwrite the value that’s assigned earlier. That means that we can’t have two functions with the same name in the same module in JavaScript. For example, if we have the following,

function add(a, b, c) {  
  return a + b + c;  
}

function add(a, b) {  
  return a + b;  
}

console.log(add(1, 2, 3));

then we get three because the add function that’s declared later has overwritten the one that’s declared earlier. To fix this, we have to rename one of them. We can also put them inside two different objects. Then they can have the same name since they aren’t in the same level. Also, we can write an Immediately Invoked Function Expression, or IIFE for short. IIFEs are run as soon as they’re defined. To wrap them in an object, we can write the following:

const a = {  
  add(a, b, c) {  
    return a + b + c;  
  }  
}

const b = {  
  add(a, b) {  
    return a + b;  
  }  
}

console.log(a.add(1, 2, 3));  
console.log(b.add(1, 2, 3));

As we can see, if we run the code, then the console.log of the first one will be six and the second one will be three since a.add has three parameters and b.add has two.

We can also use an IIFE as in the following example:

const sum1 = (function add(a, b, c) {  
  return a + b + c;  
})(1, 2, 3);

const sum2 = (function add(a, b) {  
  return a + b;  
})(1, 2, 3);

console.log(sum1);  
console.log(sum2);

In the code above, we wrapped the function inside the parentheses and then called it immediately after it was defined. Then we assigned the returned result to a variable. After that, we get six and three as we wanted. Because we called each function immediately and returned the result, we get the right result since they didn’t overlap. It also means that they can’t be called again.


Missing Parameters

When we add a new parameter to a function, then we have to remember to pass in the extra argument in the function calls. Otherwise, there may be undefined errors. To avoid undefined parameters creating errors, we can either check for it in our function, or we can set a default value of the parameter. For example, if we have the following function

function addressFn(address, city, region) { ... }

and we want to add a countryparameter and we have other parts of our program calling the function above, then we can add a default parameter. We can do this by writing the following:

function addressFn(address, city, region, country = 'US') { ... }

This way, if the country argument didn’t get passed in, country will be set to 'US'.


Forgetting About the this Keyword

When we try to access some property from another property inside an object, we should use the this keyword to get the property’s value that we want. For example, if we have the following,

let obj = {  
  prop: "some text",  
  method() {  
    console.log(prop);  
  }  
};

obj.method();

we will get an Uncaught ReferenceError: prop is not defined error when we run the code above. This is because we forgot to put the this keyword before the prop variable. Instead, we need to write the following:

let obj = {  
  prop: "some text",  
  method() {  
    console.log(this.prop);  
  }  
};

obj.method();

When we run the code above, then we get 'some text', which is what we wanted.


Iterate Through the Object Keys

The for...in loop will loop through the keys of the current object as well as all the prototypes’ keys. This isn’t ideal for all situations. It’s also slower than the other ways of iterating through the keys of an object. With the for...in loop, we need to use the Object.hasOwnProperty function to check that the property is originally defined in the object. This makes the loop even slower. This is a problem if we have a large object with lots of properties. For example, if we have,

const parent = {  
  pa: 1,  
  pb: 2  
}  
let obj = Object.create(parent);obj.a = 1;  
obj.b = 2;  
obj.c = 3;  
obj.d = 4;  
obj.e = 5;

then the for...in loop will loop through all the properties of the parent and the properties added to obj. If we only want to loop through the properties in obj, then we have to loop using the hasOwnProperty function as in the following code:

for (const key in obj) {  
  if (obj.hasOwnProperty(key)) {  
    console.log(obj[key]);  
  }  
}

However, this is slower than the newer alternatives, which are Object.keys to get the keys of an object and Object.entries to get the key-value pairs of an object. Then we loop through them with the for...of loop since both return arrays. They only loop through the object’s properties and nothing up the prototype chain. The fastest ways to loop through the entries are these two functions. We can use them as follows:

const parent = {  
  pa: 1,  
  pb: 2  
}  
let obj = Object.create(parent);obj.a = 1;  
obj.b = 2;  
obj.c = 3;  
obj.d = 4;  
obj.e = 5;for (const key of Object.keys(obj)) {  
  console.log(obj[key]);  
}

for (const [key, value] of Object.entries(obj)) {  
  console.log(value);  
}

In each example, we get the following logged,

a 1  
b 2  
c 3  
d 4  
e 5

which means that we’re getting what we want from the Object.keys and Object.entries functions.


Even though JavaScript is a friendly language, it’s still very easy to make mistakes when writing JavaScript code. Remember that in JavaScript, we can’t overload functions, so we can’t define two functions with the same name in the same level. If there’s potential for a function parameter to not be set, then we can set a default parameter so that it will never be undefined. Also, we can’t forget about the this object when we’re accessing one property from another property of the same object. Finally, we shouldn’t use the for...in loop anymore to loop through the keys of an object because it’s slow and clunky if we just want to loop through the keys of the current object without its prototype’s keys. We want to use the Object.keys or Object.entries functions instead so we get the keys or the key-value pairs, respectively, as arrays, and we can loop through them like any other array.

Categories
NativeScript React

NativeScript React — List Views

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.

ListView

We can add a vertically scrolling list with the ListView component.

For example, we can write:

import * as React from "react";
import { ListView } from "react-nativescript";
import { ItemEventData } from "@nativescript/core";

type MyItem = { text: string };

const items: MyItem[] = [
  { text: 'apple' },
  { text: 'orange' },
  { text: 'grape' },
]

const cellFactory = (item: MyItem) => {
  return <label text={item.text} />;
};

const onItemTap = ({ index }: ItemEventData) => {
  const { text }: MyItem = items[index];
  console.log(`Tapped item index ${index}: "${text}".`);
};

export default function Greeting({ }) {
  return (
    <frame>
      <page>
        <actionBar title="Default Page Title" />
        <flexboxLayout justifyContent='center' >
          <ListView
            items={items}
            cellFactory={cellFactory}
            onItemTap={onItemTap}
          />
        </flexboxLayout>
      </page>
    </frame>
  );
}

We add the ListView with the items prop to add the items we want to display.

cellFactory is a function that returns the component with the row.

And onItemTap is the event handler that’s run when we tap on a row.

In the onItemTap function, we get the index of the item that we tapped on.

So we can get the item from that.

Using ListView with Multiple Templates

We can add ListView with multiple templates.

For example, we can write:

import * as React from "react";
import { ListView } from "react-nativescript";

type MyEvenItem = { textEven: string };
type MyOddItem = { textOdd: string };
type MyItem = MyEvenItem | MyOddItem;

const items: MyItem[] = [{ textEven: "apple" }, { textOdd: "orange" }];

function itemTemplateSelector(index): string {
  return index % 2 === 0 ? "even" : "odd";
}

const evenCellFactory = (item: MyEvenItem) => {
  return <label text={item.textEven} color="green" />;
};

const oddCellFactory = (item: MyOddItem) => {
  return <label text={item.textOdd} color="orange" />;
};

const cellFactories = new Map([
  [
    "odd",
    {
      placeholderItem: {
        text: "some odd text"
      },
      cellFactory: oddCellFactory
    }
  ],

[
    "even",
    {
      placeholderItem: {
        text: "some even text"
      },
      cellFactory: evenCellFactory
    }
  ],
]);

const onItemTap = (args) => {
  const index: number = args.index;
  const item: MyItem = items[index];
  const isEven: boolean = itemTemplateSelector(index) === "even";
  const itemText: string = isEven ?
    (item as MyEvenItem).textEven :
    (item as MyOddItem).textOdd;

console.log(`Tapped item index ${index} (${isEven ? "even" : "odd"}): "${itemText}".`);
};

export default function Greeting({ }) {
  return (
    <frame>
      <page>
        <actionBar title="Default Page Title" />
        <flexboxLayout justifyContent='center' >
          <ListView
            items={items}
            itemTemplateSelector={itemTemplateSelector}
            cellFactories={cellFactories}
            onItemTap={onItemTap}
          />
        </flexboxLayout>
      </page>
    </frame>
  );
}

We have the type annotations for the different types of items with the type declarations.

Then we have the itemTemplateSelector function to get the type of item displayed.

Next, we have the eventCellFactory and oddCellFactory functions to return the items that we want to display for the rows for each kind of item.

Then we add a Map to render each kind of item.

Next, we have the onItemTap function to log the item we tapped on.

And in Greeting , we have the ListView with the items prop to set the items we display.

itemTemplateSelector sets the template we want to use.

cellFactories sets the functions we want to use to render the rows.

onItemTap lets us render the rows.

Conclusion

We can add list views to add various kinds of data in our mobile app with React NativeScript.