-
Notifications
You must be signed in to change notification settings - Fork 0
Part 1: Starting from Scratch
- Open up your terminal (Git Bash for Windows users) and navigate to your designated code directory.
For me, it's
~/Code
. - Once there, clone this repo by running:
git clone https://github.com/NCSU-App-Development-Club/react-native-workshop-1.git
- Open the cloned repo in VSCode:
code react-native-workshop-1
- Once VSCode is open, press Ctrl+` to open up a terminal inside of VSCode.
- Run:
npm install npm run start
- Scan the QR code with your cell phone and it should open up a relatively bare preview app in Expo Go.
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:
-
If not already running, start your Expo Go preview:
npm run start
-
Update your imports to include
Platform
andButton
from'react-native'
, as well asuseState
from'react'
:import { StyleSheet, Text, View, Button, Platform } from 'react-native'; import { useState } from 'react';
-
Use
useState
to add a state variablecount
and its settersetCount
to your component.... export default function App() { const [count, setCount] = useState(0); // This line return ( <View style={styles.container}> ...
-
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 ¯\_(ツ)_/¯
- 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:
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