React Native Props Basics
Lesson Introduction
Welcome to the very first lesson of the "Introduction to Props and Event Handlers in React Native" course! I’m excited to guide you as we begin our journey into building interactive and reusable mobile apps with React Native. In this lesson, we’ll focus on one of the most fundamental concepts: props. Props are the primary way to pass data from one component to another, making your components flexible and powerful. By the end of this lesson, you’ll understand how to use props to display dynamic content — using Cosmo’s Greatest Hits as our example — and you’ll be ready to apply these ideas in your own projects.
The Problem with Hardcoded Data
Let’s start by considering a common challenge: hardcoded data. Imagine you want to display information about an album in your app. You might create a component like this:
This works, but it’s not very flexible. If you want to show a different album, you’d have to change the code inside the component. If you want to show a list of albums, you’d have to copy and paste this component multiple times, changing the values each time. This approach quickly becomes unmanageable as your app grows.
The real world is dynamic. Data changes, and users expect to see different content without you having to rewrite your components every time. That’s where props come in.
What Are Props in React Native?
Props, short for “properties,” are a way to pass information from a parent component to a child component. Think of props as arguments you give to a function. In React Native, you can make your components reusable by allowing them to accept props and display different content based on the data they receive.
Let’s update our Album component to accept props:
Now, instead of hardcoding the album details, we define them as props. Notice that year is now optional (year?: number). Inside the component, we use const displayYear = year ?? "Unknown"; to show "Unknown" if no year is provided. This makes the component reusable for any album. You can use this component like so:
This example shows how props allow you to pass different data to the same component, making your code cleaner and more maintainable.
