Buttons and state
Respond to a press and change what is on screen.
Your React Native code runs inside your browser tab on React Native for Web, shown on a phone-sized screen. Nothing to install.
A button
<Button> shows a button. Its words go in the title prop, and onPress is given a function to run when it is pressed.
A button on its own changes nothing you can see. For that, the component needs to remember something.
import { Button, View } from "react-native";
export default function App() {
return (
<View>
<Button title="Say hello" onPress={() => console.log("Hello")} />
</View>
);
}Remembering with state
useState gives a component a value it remembers between presses, and a function to change it. useState(0) starts the value at 0.
When the function is called with a new value, React Native draws the component again with it. You never change the screen yourself: you change the state and the screen follows.
import { useState } from "react";
import { Button, Text, View } from "react-native";
export default function App() {
const [cups, setCups] = useState(0);
return (
<View>
<Text>Cups ordered: {cups}</Text>
<Button title="One more" onPress={() => setCups(cups + 1)} />
</View>
);
}Your turn: a counter
State, a Text and a Button together.
Practice task
Show Count: 0 and a button titled Add. Each press of the button must add one to the count.
Your answer is run and checked in the lesson. Create a free account to try it.
Showing something only sometimes
State can also decide whether a component is shown at all.
{open && <Text>…</Text>} shows the Text only while open is true. !open means the opposite of open, so setOpen(!open) flips it.
import { useState } from "react";
import { Button, Text, View } from "react-native";
export default function App() {
const [open, setOpen] = useState(false);
return (
<View>
<Button title="Opening hours" onPress={() => setOpen(!open)} />
{open && <Text>7 am to 2 pm, every day</Text>}
</View>
);
}Your turn: reveal a message
Nothing should show until the press.
Practice task
Add a button titled Show. The word Secret must not be on screen at first, and must appear when the button is pressed.
Your answer is run and checked in the lesson. Create a free account to try it.
On a real phone
These lessons run your code with React Native for Web, the library that puts React Native apps in a browser. The components and their props are the same ones a phone uses.
A real phone draws them with its own buttons and fonts, so the look differs a little. To try your code on your own phone, paste it into Expo Snack at snack.expo.dev and scan the code it shows with the Expo Go app.