31
loading...
This website collects cookies to deliver better user experience
expo init reactNativeCounterApp
(that's what I'm calling mine- you can call yours whatever you want).App
file, clear out the template code and then add Button
to the components destructured out of the React Native import. You should also import useState
from 'react' because that's what we're going to use to keep track of state in this app. Your imports should look like this:import { useState } from 'react';
import { Button, StyleSheet, Text, View } from 'react-native';
useState
to 0 with named variables counter
and setCounter
array-destructured out. Anyone who's familiar with React (you should be if you're trying to learn React Native) will know this is a standard state management hook included with React for functional components. So your useState should be initialized like so just inside your App component:export default function App() {
const [ counter, setCounter ] = useState(0);
...
<Text></Text>
component in the JSX somewhere. In between the brackets declare the counter
variable. Below this add two Button
components. These are React Native primitive components that are meant to be as simple of a button as can be, but they work. You should give each button a title
prop to display why they're there. I gave mine titles of "+" and "-" to show that they're going to be adding and subtracting, respectively.onPress
prop. This is where the only real logic happens in our application, because it's where we will change our counter
value held in the component's state.setCounter
method we created earlier. As you should know, we aren't supposed to try to change counter
itself, but we can use it in setCounter()
and just add 1 to the existing counter value.<Button title="+" onPress={ ()=> setCounter( counter + 1 ) } />
<Button title="-" onPress={ ()=> setCounter( counter - 1 ) } />