Show List
React Native Coding Questions
- Write a function to create a simple calculator app in React Native.
javascriptCopy code
import React, {useState} from 'react';
import {View, Text, Button, TextInput} from 'react-native';
export default function Calculator() {
const [num1, setNum1] = useState('');
const [num2, setNum2] = useState('');
const [result, setResult] = useState('');
const add = () => {
setResult(Number(num1) + Number(num2));
};
const subtract = () => {
setResult(Number(num1) - Number(num2));
};
const multiply = () => {
setResult(Number(num1) * Number(num2));
};
const divide = () => {
setResult(Number(num1) / Number(num2));
};
return (
<View>
<TextInput
value={num1}
onChangeText={setNum1}
placeholder="Enter number 1"
/>
<TextInput
value={num2}
onChangeText={setNum2}
placeholder="Enter number 2"
/>
<Button title="+" onPress={add} />
<Button title="-" onPress={subtract} />
<Button title="x" onPress={multiply} />
<Button title="/" onPress={divide} />
<Text>{result}</Text>
</View>
);
}
- Create a component that displays a list of items and allows the user to add new items.
javascriptCopy code
import React, {useState} from 'react';
import {View, Text, TextInput, Button, FlatList} from 'react-native';
export default function List() {
const [items, setItems] = useState([]);
const [text, setText] = useState('');
const addItem = () => {
setItems([...items, {key: text}]);
setText('');
};
return (
<View>
<TextInput
value={text}
onChangeText={setText}
placeholder="Enter item name"
/>
<Button title="Add Item" onPress={addItem} />
<FlatList
data={items}
renderItem={({item}) => <Text>{item.key}</Text>}
/>
</View>
);
}
- Write a function that fetches data from an API and displays it in a list.
javascriptCopy code
import React, {useState, useEffect} from 'react';
import {View, Text, FlatList} from 'react-native';
export default function APIList() {
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(json => setData(json))
.catch(error => console.error(error));
}, []);
return (
<View>
<FlatList
data={data}
renderItem={({item}) => <Text>{item.name}</Text>}
keyExtractor={item => item.id.toString()}
/>
</View>
);
}
- Create a component that displays an image and allows the user to change the image source.
javascriptCopy code
import React, {useState} from 'react';
import {View, Image, TextInput, Button} from 'react-native';
export default function ImageExample() {
const [source, setSource] = useState('');
return (
<View>
<Image source={{uri: source}} style={{width: 200, height: 200}} />
<TextInput
value={source}
onChangeText={setSource}
placeholder="Enter image URL"
/>
<Button title="Update Image" onPress={() => setSource(source)} />
</View>
);
}
- Write a function that allows the user to select an option from a dropdown menu.
javascriptCopy code
import React, {useState} from 'react';
import {View, Text, Picker} from 'react-native';
export default function Dropdown() {
const [selectedOption, setSelectedOption] = useState('option1');
return (
<View>
<Picker
selectedValue={selectedOption}
onValueChange={itemValue => setSelectedOption(itemValue)}>
<Picker.Item label="Option 1" value="option1" />
<Picker.Item label="Option 2" value="option2" />
<Picker.Item label="Option 3" value="option3" />
</Picker>
<Text>Selected option: {selectedOption}</Text>
</View>
);
}
- Create a component that displays a checkbox and allows the user to toggle its state.
javascriptCopy code
import React, {useState} from 'react';
import {View, Text, CheckBox} from 'react-native';
export default function CheckboxExample() {
const [checked, setChecked] = useState(false);
return (
<View>
<CheckBox value={checked} onValueChange={setChecked} />
<Text>{checked ? 'Checked' : 'Unchecked'}</Text>
</View>
);
}
- Write a function that fetches data from an API and displays it in a grid.
javascriptCopy code
import React, {useState, useEffect} from 'react';
import {View, Text, FlatList, Image, StyleSheet, Dimensions} from 'react-native';
const windowWidth = Dimensions.get('window').width;
export default function APIGrid() {
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/photos')
.then(response => response.json())
.then(json => setData(json))
.catch(error => console.error(error));
}, []);
return (
<View style={styles.container}>
<FlatList
data={data}
numColumns={3}
renderItem={({item}) => (
<View style={styles.item}>
<Image
source={{uri: item.url}}
style={{width: windowWidth / 3, height: windowWidth / 3}}
/>
<Text>{item.title}</Text>
</View>
)}
keyExtractor={item => item.id.toString()}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
item: {
alignItems: 'center',
justifyContent: 'center',
margin: 5,
},
});
- Write a function that allows the user to search for items in a list.
javascriptCopy code
import React, {useState} from 'react';
import {View, Text, FlatList, TextInput, StyleSheet} from 'react-native';
const data = [
{id: 1, name: 'Apple'},
{id: 2, name: 'Banana'},
{id: 3, name: 'Cherry'},
{id: 4, name: 'Durian'},
{id: 5, name: 'Elderberry'},
];
export default function SearchableList() {
const [searchText, setSearchText] = useState('');
const [filteredData, setFilteredData] = useState(data);
const handleSearch = text => {
setSearchText(text);
const newData = data.filter(item => {
const itemName = item.name.toLowerCase();
const searchQuery = text.toLowerCase();
return itemName.includes(searchQuery);
});
setFilteredData(newData);
};
return (
<View style={styles.container}>
<TextInput
style={styles.textInput}
value={searchText}
onChangeText={handleSearch}
placeholder="Search for an item"
/>
<FlatList
data={filteredData}
renderItem={({item}) => <Text>{item.name}</Text>}
keyExtractor={item => item.id.toString()}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
textInput: {
height: 40,
width: '80%',
borderWidth: 1,
borderColor: 'gray',
borderRadius: 5,
paddingHorizontal: 10,
marginBottom: 10,
},
});
- Create a component that displays a list of items and allows the user to add new items to the list.
javascriptCopy code
import React, {useState} from 'react';
import {View, Text, FlatList, TextInput, Button, StyleSheet} from 'react-native';
export default function ListWithAdd() {
const [items, setItems] = useState([]);
const [newItem, setNewItem] = useState('');
const handleAddItem = () => {
setItems(prevItems => [...prevItems, newItem]);
setNewItem('');
};
return (
<View style={styles.container}>
<View style={styles.inputContainer}>
<TextInput
style={styles.textInput}
value={newItem}
onChangeText={setNewItem}
placeholder="Enter a new item"
/>
<Button title="Add" onPress={handleAddItem} />
</View>
<FlatList
data={items}
renderItem={({item}) => <Text>{item}</Text>}
keyExtractor={(item, index) => index.toString()}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
inputContainer: {
flexDirection: 'row',
alignItems: 'center',
marginBottom: 10,
},
textInput: {
height: 40,
width: '80%',
borderWidth: 1,
borderColor: 'gray',
borderRadius: 5,
paddingHorizontal: 10,
marginRight: 10,
},
});
- Write a function that takes an array of numbers and returns the sum of the even numbers in the array.
javascriptCopy code
const sumOfEvenNumbers = numbers => {
return numbers.reduce((acc, curr) => {
if (curr % 2 === 0) {
return acc + curr;
}
return acc;
}, 0);
};
console.log(sumOfEvenNumbers([1, 2, 3, 4, 5, 6])); // Output: 12
console.log(sumOfEvenNumbers([1, 3, 5])); // Output: 0
console.log(sumOfEvenNumbers([2, 4, 6])); // Output: 12
- Create a component that displays a countdown timer.
javascriptCopy code
import React, {useState, useEffect} from 'react';
import {View, Text, Button, StyleSheet} from 'react-native';
export default function CountdownTimer({duration}) {
const [timeLeft, setTimeLeft] = useState(duration);
useEffect(() => {
const interval = setInterval(() => {
setTimeLeft(prevTimeLeft => prevTimeLeft - 1);
}, 1000);
return () => clearInterval(interval);
}, []);
useEffect(() => {
if (timeLeft === 0) {
clearInterval(interval);
}
}, [timeLeft]);
const minutes = Math.floor(timeLeft / 60);
const seconds = timeLeft % 60;
return (
<View style={styles.container}>
<Text style={styles.text}>{`${minutes
.toString()
.padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`}</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
alignItems: 'center',
justifyContent: 'center',
},
text: {
fontSize: 36,
},
});
- Write a function that takes a string and returns the number of words in the string.
javascriptCopy code
const countWords = str => {
return str.split(' ').length;
};
console.log(countWords('This is a test')); // Output: 4
console.log(countWords('React Native is awesome')); // Output: 4
console.log(countWords('')); // Output: 0
- Create a component that allows the user to upload an image from their device and display it on the screen.
javascriptCopy code
import React, {useState} from 'react';
import {View, Text, Image, Button, StyleSheet} from 'react-native';
import ImagePicker from 'react-native-image-picker';
export default function ImageUploader() {
const [image, setImage] = useState(null);
const handleSelectImage = () => {
ImagePicker.showImagePicker({}, response => {
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else {
setImage(response.uri);
}
});
};
return (
<View style={styles.container}>
{image ? (
<Image source={{uri: image}} style={styles.image} />
) : (
<Text>No image selected</Text>
)}
<Button title="Select Image" onPress={handleSelectImage} />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
image: {
width: 200,
height: 200,
resizeMode: 'contain',
marginBottom: 10,
},
});
- Write a function that takes a number and returns true if it is a prime number, false otherwise.
javascriptCopy code
const isPrime = num => {
if (num <= 1) {
return false;
}
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) {
return false;
}
}
return true;
};
console.log(isPrime(7)); // Output: true
console.log(isPrime(10)); // Output: false
console.log(isPrime(1)); // Output: false
Leave a Comment