0
0
React Nativemobile~5 mins

Default props in React Native

Choose your learning style9 modes available
Introduction

Default props let you set a fallback value for a component's property. This means your component still works even if no value is given.

When you want a button to have a default label if none is provided.
When an image component should show a placeholder if no image URL is passed.
When a text input should have a default placeholder text.
When you want to avoid errors from missing props in your components.
Syntax
React Native
function MyComponent({ title = 'Default Title' }) {
  return <Text>{title}</Text>;
}
You can set default values directly in the function parameter list using =.
This works only for functional components in React Native.
Examples
This component shows a greeting. If no name is given, it says "Hello, Friend!"
React Native
function Greeting({ name = 'Friend' }) {
  return <Text>Hello, {name}!</Text>;
}
The button shows "Click me" if no label prop is passed.
React Native
function Button({ label = 'Click me' }) {
  return <Text>{label}</Text>;
}
Using arrow function syntax, the text defaults to "No message".
React Native
const Message = ({ text = 'No message' }) => <Text>{text}</Text>;
Sample App

This app shows two welcome messages. The first uses the passed user "Alice". The second uses the default "Guest" because no user prop is given.

React Native
import React from 'react';
import { Text, View } from 'react-native';

function Welcome({ user = 'Guest' }) {
  return (
    <View style={{ padding: 20 }}>
      <Text>Welcome, {user}!</Text>
    </View>
  );
}

export default function App() {
  return (
    <>
      <Welcome user="Alice" />
      <Welcome />
    </>
  );
}
OutputSuccess
Important Notes

Default props help avoid errors when props are missing.

Setting defaults in the function parameters is simple and clean.

For class components, default props are set differently (not covered here).

Summary

Default props provide fallback values for component props.

Use = in function parameters to set defaults in React Native functional components.

This keeps your UI stable and user-friendly even if some props are missing.