Interpolation helps you put variables or expressions inside text or styles easily. It makes your app show dynamic content that changes based on data.
0
0
Interpolation in React Native
Introduction
Showing a user's name inside a greeting message like "Hello, John!"
Displaying the current score in a game as part of a sentence
Changing colors or sizes in styles based on user actions or data
Building text that updates when the user types or selects something
Syntax
React Native
const message = `Hello, ${name}!`;
<Text>{message}</Text>Use backticks ` ` to create a template string for interpolation.
Place variables or expressions inside ${ } within the backticks.
Examples
Shows a greeting with the name Anna inside the text.
React Native
const name = 'Anna'; const greeting = `Hi, ${name}!`; <Text>{greeting}</Text>
Displays the score number inside a sentence.
React Native
const score = 42; <Text>{`Your score is ${score}`}</Text>
Uses interpolation to set the width style dynamically.
React Native
const width = 100; <View style={{width: width, height: 50, backgroundColor: 'blue'}} />
Sample App
This app shows two lines of text. The first line greets the user by name using interpolation. The second line tells how many new messages the user has, also using interpolation.
React Native
import React from 'react'; import { View, Text, StyleSheet } from 'react-native'; export default function App() { const userName = 'Sam'; const messagesCount = 5; return ( <View style={styles.container}> <Text style={styles.text}>{`Hello, ${userName}!`}</Text> <Text style={styles.text}>{`You have ${messagesCount} new messages.`}</Text> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#f0f0f0' }, text: { fontSize: 20, margin: 10 } });
OutputSuccess
Important Notes
Interpolation only works inside backtick strings (template literals).
You can put any JavaScript expression inside ${ }, like math or function calls.
In React Native, use curly braces { } to insert JavaScript expressions inside JSX.
Summary
Interpolation lets you mix variables and text easily using backticks and ${}.
Use it to create dynamic messages or styles that change with data.
Remember to wrap interpolated strings in curly braces when used in JSX.