Skip to content

Part 1: Starting from Scratch

Abel Lu edited this page Sep 23, 2024 · 4 revisions

Getting Started

  1. Open up your terminal (Git Bash for Windows users) and navigate to your designated code directory. For me, it's ~/Code.
  2. Once there, clone this repo by running:
    git clone https://github.com/NCSU-App-Development-Club/react-native-workshop-1.git
    
  3. Open the cloned repo in VSCode:
    code react-native-workshop-1
    
  4. Once VSCode is open, press Ctrl+` to open up a terminal inside of VSCode.
  5. Run:
    npm install
    npm run start
    
  6. Scan the QR code with your cell phone and it should open up a relatively bare preview app in Expo Go.

drawing

The useState Hook

As per the React documentation:

"Hooks let you use different React features from your components."

React comes with many built-in hooks available to use (too many to cover here). To learn about them all, free free to peruse the aforementioned docs.

The useState hook allows you to add a state variable to a component. Calling useState returns a state variable with a value you initialize and a setter function to update the value.

Here's an example:

const [count, setCount] = useState(0);

In this example, count is the state variable with an initial value of 0 and setCount is its setter function.

Let's see it in action in our own code:

  1. If not already running, start your Expo Go preview:

    npm run start
    
  2. Update your imports to include Platform and Button from 'react-native', as well as useState from 'react':

    import { StyleSheet, Text, View, Button, Platform } from 'react-native';
    import { useState } from 'react';
  3. Use useState to add a state variable count and its setter setCount to your component.

    ...
    export default function App() {
    
      const [count, setCount] = useState(0); // This line
    
      return (
        <View style={styles.container}>
    ...
  4. Replace the current <Text/> element with this:

    <Text>Count: {count}{Platform.OS == "android" && ' '}</Text>

Note

{Platform.OS == "android" && ' '} is needed for Text elements to render correctly on Android devices. I don't make the rules ¯\_(ツ)_/¯

  1. Add some Buttons to increment and decrement the count. These should go below the <Text/> element:
    <Button title="Increase Count" onPress={() => setCount(count + 1)}/>
    <Button title="Decrease Count" onPress={() => setCount(count - 1)}/>

Now your Expo Go preview should look something like this, and pressing the buttons should increment/decrement the count appropriately:

drawing

Bonus:

Try implementing the same logic with regular JavaScript variables and see if it works (hint: it won't). If you're interested in why, read this.

Next up: Part 2

Clone this wiki locally