Course Content
Foundations of React Native
Foundations of React Native
Challenge: Props and State
Task
Create a component named Counter
that simulates a simple counter application. The component should display a counter value and include a button to increment that value. The initial counter value should be customizable by passing it as a prop when using the Counter
component.
Steps
- Create the Counter Component:
- Define a functional component named
Counter
in theCounter.js
file; - Use the
useState
hook to manage the state of the counter within the component.
- Define a functional component named
- Display the Counter Value:
- Display the current counter value on the screen.
- Implement a Button:
- Use the
TouchableOpacity
component from React Native to create a button; - Label the button with the text
"Increment"
.
- Use the
- Handle Incrementing:
- Implement a function, e.g.,
incrementCounter
, that increments the counter value by1
each time the button is pressed; - Attach this function to the button's
onPress
event.
- Implement a function, e.g.,
- Customizable Initial Value:
- Allow the
Counter
component to receive an initial counter value as a prop namedinitialValue
; - Use this prop to set the initial state of the counter.
- Allow the
We should see the following result after implementing those changes.
Repository with initial files and folders.
Initiate the Project
Begin the project by duplicating the initial files and data through the specified terminal command.
Access the newly generated folder containing the project files using the command:
Next, install the necessary packages with:
To launch the application and preview its initial interface, execute the following command in the terminal:
Hint
- For managing state, use the
useState
hook in theCounter
component; - Utilize the
Text
andTouchableOpacity
components for displaying text and creating a touchable button, respectively; - Pass the initial counter value as a prop to the
Counter
component when using it in another file.
In case you encounter any obstacles while carrying out the task, we recommend consulting the provided recording, which provides a detailed walkthrough on every aspect. Wishing you all the best!
In Practice
Thanks for your feedback!