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.

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