React Native Programming Questions & Answers
1. Toggle Button Example
Create a toggle button that switches text between "ON" and "OFF".
Answer:
import React, { useState } from 'react';
import { View, Text, Button } from 'react-native';
const ToggleButton = () => {
const [isOn, setIsOn] = useState(false);
return (
<View>
<Text>{isOn ? "ON" : "OFF"}</Text>
<Button title="Toggle" onPress={() => setIsOn(prev => !prev)} />
</View>
);
};
export default ToggleButton;
2. Fetch Data from API
Write a component that fetches user data from an API and displays the name.
Answer:
import React, { useEffect, useState } from 'react';
import { View, Text, ActivityIndicator } from 'react-native';
const UserComponent = () => {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/users/1')
.then(res => res.json())
.then(data => {
setUser(data);
setLoading(false);
});
}, []);
if (loading) return <ActivityIndicator />;
return (
<View>
<Text>User: {user.name}</Text>
</View>
);
};
export default UserComponent;
3. FlatList Rendering
Create a list of items using FlatList.
Answer:
import React from 'react';
import { View, FlatList, Text } from 'react-native';
const data = [
{ id: '1', name: 'Apple' },
{ id: '2', name: 'Banana' },
{ id: '3', name: 'Cherry' },
];
const ListComponent = () => {
return (
<FlatList
data={data}
keyExtractor={item => item.id}
renderItem={({ item }) => <Text>{item.name}</Text>}
/>
);
};
export default ListComponent;
4. Form with Input and Button
Create a form with a TextInput and submit button. Alert the input value.
Answer:
import React, { useState } from 'react';
import { View, TextInput, Button, Alert } from 'react-native';
const FormComponent = () => {
const [input, setInput] = useState('');
const handleSubmit = () => {
Alert.alert("Submitted", input);
};
return (
<View>
<TextInput
placeholder="Enter text"
value={input}
onChangeText={setInput}
style={{ borderWidth: 1, marginBottom: 10 }}
/>
<Button title="Submit" onPress={handleSubmit} />
</View>
);
};
export default FormComponent;
5. Navigation Between Screens
How do you navigate from one screen to another?
Install dependencies:
npm install @react-navigation/native @react-navigation/native-stack
Answer:
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import Home from './Home';
import Profile from './Profile';
const Stack = createNativeStackNavigator();
export default function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={Home} />
<Stack.Screen name="Profile" component={Profile} />
</Stack.Navigator>
</NavigationContainer>
);
// Home.js
const Home = ({ navigation }) => (
<Button title="Go to Profile" onPress={() => navigation.navigate('Profile')} />
);
// Profile.js
const Profile = () => <Text>This is the Profile screen</Text>;