ImageBackground won't render react native - javascript

I'm doing a project in react native and my ImageBackgroud component does not want to render. The odd thing is I am already using ImageBackground in another component and it works there. I tried resizing the image but that didn't help.
Here is my component that renders child component with ImageBackground:
const DuringStay = () => {
return (
<View style={styles.container}>
<FlatList
data={test}
numColumns={2}
columnWrapperStyle={{
justifyContent: 'space-between',
marginBottom: 15,
}}
keyExtractor={item => item.id}
renderItem={({ item }) => (
<DuringStayTile item={item} />
)}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
paddingHorizontal: 20,
flex: 1,
},
});
export default DuringStay;
Here is my component that doesn't want to render ImageBackground. My data comes correctly to the component and inside Pressable i can render other components but ImageBackground won't show up
const DuringStayTile = ({item}) => {
const { title, uri } = item;
console.log(title,uri)
return (
<Pressable style={styles.container}>
<ImageBackground source={uri} resizeMode="cover" style={styles.image}>
<LinearGradient
style={styles.textBox}
colors={['transparent','rgba(0,0,0,0.6)']}>
<Text>
{title}
</Text>
</LinearGradient>
</ImageBackground>
</Pressable>
);
};
export default DuringStayTile;
const styles = StyleSheet.create({
container: {
width: '48%',
padding: 20,
borderRadius: 10,
padding:60,
backgroundColor:'pink'
},
title: {
fontWeight: 'bold',
fontSize: 16,
},
image: {
flex: 1,
overflow:'hidden',
justifyContent:'center'
},
textBox:{
position:'absolute',
right:0,
bottom:0,
width:'100%'
},
});
Data that is imported:
export const test = [
{
uri:require('../assets/f1.jpg'),
title: 'Zip Line',
id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba'
},
{
uri: require('../assets/during.jpeg'),
title: 'Blue Cave',
id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63',
},
{
uri: require('../assets/post.jpg'),
title: 'Rafting',
id: '58694a0f-3da1-471f-bd96-145571e29d72',
}
]

image: {
flex: 1,
overflow:'hidden',
justifyContent:'center',
padding:30
},

Related

Multiple Input Text handle in object and array in react native

This is my code ....
react native
Multiple Input Text handle in object and array in react native...
Is it possible to share your code? Share the entire component where you have these groups of 5 inputs. You can just copy and paste it inside your question body. That way I can help you better
App.js
import {
StyleSheet,
Pressable,
View,
} from 'react-native';
import {
AntDesign,
FontAwesome
} from '#expo/vector-icons';
import { useState } from 'react';
import AddStudentProfile from './Pages/AddStudentProfile';
import StudentList from './Pages/StudentList';
export default function App() {
const [iconColor, setIconColor] = useState(['#ab09bf', '#A9A9A9']);
const [multiValues, setMultiValues] = useState([]);
const [screen, setScreen] = useState(<StudentList stuList={multiValues} />);
function changeIconColor(pressCheck) {
if (pressCheck) {
setIconColor([
'#ab09bf',
'#A9A9A9'
]
);
}
else {
setIconColor([
'#A9A9A9',
'#ab09bf'
]
);
}
}
// const [iconChangableColor, setIconChangableColor] = useState('#A9A9A9');
function changeScreen(scr) {
setScreen(
// < AddStudentProfile />
scr
);
// setIconChangableColor('#ab09bf');
// console.log(multiValues)
changeIconColor(true)
}
function appendData(inp, onsrcChange) {
setScreen(
// < AddStudentProfile />
onsrcChange
);
setMultiValues([
...multiValues,
inp]);
console.log(multiValues)
}
return (
< View style={styles.container} >
<View style={{ flex: 9 }}>{screen}
</View>
<View >
<View style={styles.bottomIconContainer}>
<Pressable onPress={() => [changeScreen(<StudentList />), changeIconColor(true)]}
android_ripple={{ color: 'black' }}>
<View style={styles.bottomIconInnerContainer}>
<FontAwesome
name="list-ul"
size={35}
color={iconColor[0]} />
</View></Pressable>
<Pressable onPress={() => [changeScreen(<AddStudentProfile onAppendData={appendData} returnToProfile={changeScreen} />), changeIconColor(false)]}
android_ripple={{ color: 'black' }}>
<View style={styles.bottomIconInnerContainer}>
<AntDesign name="adduser"
size={35}
color={iconColor[1]}
/></View></Pressable></View>
</View>
</View >
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
bottomIconContainer: {
flexDirection: 'row',
justifyContent: 'space-around',
alignItems: 'center',
},
bottomIconInnerContainer: {
marginVertical: 20,
marginHorizontal: 80
}
});
AddStudentProfile.js
import {
Text,
TextInput,
ImageBackground,
View,
Button,
ScrollView,
StatusBar,
StyleSheet
} from "react-native";
import { useState } from "react";
import { AntDesign } from '#expo/vector-icons';
import PrimaryButton from "../Componenets/PrimaryButton";
import ColorCode from "../Componenets/ColorCode.js";
export default function AddStudentProfile({ returnToProfile, onAppendData }) {
const [values, setValues] = useState({});
function inputHandler(name, value) {
setValues({
...values,
[name]: value
})
}
function inpValues(srcChange) {
onAppendData(values, srcChange)
console.log(values)
}
return (
<ScrollView>
<View style={styles.screenContainer}>
<View>
<Text style={styles.textContainer}>
Add Student Profile
</Text>
</View>
<View style={styles.iconOutterContainer}>
<View style={styles.iconContainer}>
<AntDesign
name="user"
size={80}
color='white'
/>
</View>
</View>
<View style={{ alignItems: 'center' }}>
<TextInput
style={styles.inputTextContainer}
placeholder="name"
placeholderTextColor={ColorCode.placeHolder}
onChangeText={(val) => inputHandler('sname', val)}
/>
<TextInput
style={styles.inputTextContainer}
placeholder="roll no"
placeholderTextColor={ColorCode.placeHolder}
onChangeText={(val) => inputHandler('rno', val)}
/>
<TextInput
style={styles.inputTextContainer}
placeholder="department"
placeholderTextColor={ColorCode.placeHolder}
onChangeText={(val) => inputHandler('dep', val)}
/>
<TextInput
style={styles.inputTextContainer}
placeholder="e-mail"
placeholderTextColor={ColorCode.placeHolder}
onChangeText={(val) => inputHandler('mail', val)}
/>
<TextInput
style={styles.inputTextContainer}
placeholder="Phone no"
placeholderTextColor={ColorCode.placeHolder}
onChangeText={(val) => inputHandler('phno', val)}
/>
</View>
<PrimaryButton
onreturnToProfile={returnToProfile}
inputValues={inpValues}
changeColor='#8a0896'
>Save</PrimaryButton>
</View>
</ScrollView>
);
}
const styles = StyleSheet.create({
iconContainer: {
height: 100,
width: 100,
borderRadius: 100,
backgroundColor: '#ab09bf',
alignItems: 'center',
justifyContent: 'center'
},
textContainer: {
marginVertical: 10,
textAlign: 'center',
fontSize: 20,
},
screenContainer: {
marginTop: StatusBar.currentHeight,
flex: 1,
padding: 20
},
iconOutterContainer: {
alignItems: 'center'
},
inputOutterContainer: {
padding: 10,
marginHorizontal: 5
},
inputTextContainer: {
padding: 10,
backgroundColor: '#fff',
marginVertical: 10,
width: '95%',
fontSize: 19,
elevation: 5,
borderRadius: 6,
shadowColor: '#ab09bf',
color: '#ab09bf'
},
buttonOutterContainer: {
width: '30%',
marginHorizontal: 10,
fontSize: 20
},
buttonInnerContainer: { fontSize: 23 }
});
PrimaryButton.js
import {
View,
Text,
Pressable,
StyleSheet
} from 'react-native';
import StudentList from '../Pages/StudentList';
export default function PrimaryButton({ children, inputValues, onreturnToProfile }) {
function pressHandler() {
//onreturnToProfile();
inputValues(<StudentList />)
}
return (
< View style={{ alignItems: 'center', marginTop: 15 }
}>
<View
style={styles.textOutterContainer}
>
<Pressable
onPress={pressHandler}
android_ripple={{ color: 'white' }}
>
<Text style={styles.textContainer}>{children}</Text>
</Pressable>
</View>
</View >
);
}
const styles = StyleSheet.create({
textContainer: {
fontSize: 23,
color: 'white',
textAlign: 'center'
},
textOutterContainer: {
backgroundColor: '#8a0896',
borderRadius: 22,
width: '20%',
height: 40,
alignItems: 'center',
justifyContent: 'center'
}
})
I have gone through your code and it seems to be right even though a bit complicated. What is the issue you are facing?
You are adding a set of student info(5 fields) on a button press to a parent component state. You are appending it to an empty array. Ideally, you should get something like the below. What seems to be the problem? Please explain.
multiValues = [
{
'sname': 'some sname',
'rno': 'some rno',
'dep': 'some dep',
'mail': 'some mail',
'phno': 'some phno'
},
{
'sname': 'some sname',
'rno': 'some rno',
'dep': 'some dep',
'mail': 'some mail',
'phno': 'some phno'
},
{
'sname': 'some sname',
'rno': 'some rno',
'dep': 'some dep',
'mail': 'some mail',
'phno': 'some phno'
},
{
'sname': 'some sname',
'rno': 'some rno',
'dep': 'some dep',
'mail': 'some mail',
'phno': 'some phno'
},
]
Will update this answer depending on your response so that it might be of help to someone else.

How to change all images by one click in react

import React, { Component } from "react";
import { StyleSheet, FlatList, View, Image, Text } from "react-native";
const n1 = require("../img/n1.png");
const n2 = require("../img/n2.png");
const n3 = require("../img/n3.png");
const n4 = require("../img/n4.png");
const n5 = require("../img/n5.png");
const n0 = require("../img/n0.png");
class Example extends Component {
constructor(props) {
super(props);
this.state = {
data: [
{ id: 1, image: n1, title: " n1 " },
{ id: 2, image: n2, title: " n2 " },
{ id: 3, image: n3, title: " n3" },
{ id: 4, image: n4, title: " n4 " },
{ id: 5, image: n5, title: " n5" },
],
};
}
render() {
return (
<FlatList
style={styles.container}
data={this.state.data}
keyExtractor={(item) => {
return item.id;
}}
renderItem={({ item }) => {
return (
<View style={styles.box}>
<View style={styles.info}>
<Text style={styles.name}>{item.title} </Text>
<Image style={styles.image} source={{ uri: item.image }} />
</View>
</View>
);
}}
/>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 30,
},
info: {
flex: 1,
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
},
image: {
width: 173,
height: 88,
},
title: {
color: "#707070",
opacity: 1,
},
box: {
marginLeft: -120,
marginTop: 10,
backgroundColor: "white",
flexDirection: "row",
marginBottom: 20,
},
});
This is part of the code that I have deleted some code not relevant to this question.
My question is how do I change all images(n1-n5) by one click to n0.
The page will show 5 different images(n1-n5) in a list, then after clicking a button, all images will be replaced by n0.
I got some idea about setState, but I am new to React and don't know how to make it work(or not state) even after search.
BTW, its a webpage, but I use react-native-web to get the images more pretty arranged.
This is a simple map operation.
handleClick = () =>
this.setState((prev) => ({
data: prev.data.map((item) => ({
...item,
image: n0,
title: "n0",
})),
}));
Start by adding extraData to the flat list to re render when button clicked
<FlatList
style={styles.container}
data={this.state.data}
extraData={this.state}
keyExtractor={(item) => {
return item.id;
}}
renderItem={({ item }) => {
return (
<View style={styles.box}>
<View style={styles.info}>
<Text style={styles.name}>{item.title} </Text>
<Image style={styles.image} source={{ uri: item.image }} />
</View>
</View>
);
}}
/>
....
//add function for button click:
onButtonClicked(){
//create the new data array
//replace it with the old array state
this.setState({data: new_data}); //flat list should re render when state changed
}

What's wrong with my FlatList? react-native

My Flatlist does not work for me, Some one please review and give me a solution
const data = [
'hai', 'hloooo'
]
class HotelList extends Component {
render() {
console.log('data==========', data)
return (
<View style = {{flex: 1, height: '100%', width: '100%'}}>
<Text>Hai</Text>
<FlatList
data = {data}
keyExtractor = {(item, index) => index.toString()}
renderItem = {itemData => {
console.log(itemData)
return (
<View style = {{width: '100%', height: 100, flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: 'yellow'}}>
<Text>Holaaaaaa</Text>
</View>
)
}}
/>
</View>
)
}
}
export default HotelList
Basically you have missed some basic theory about how to use a flat list in react native. See official documentation here
Solution :
You need to add id to your array in order to make keyExtractor work
const data = [
{
id: "1",
title: "First Item",
},
{
id: "2",
title: "Second Item",
},
{
id: "3",
title: "Third Item",
},
];
class HotelList extends Component {
render() {
console.log("data==========", data);
return (
<View style={{ flex: 1, height: "100%", width: "100%" }}>
<Text>Hai</Text>
<FlatList
data={data}
keyExtractor={(item) => item.id}
renderItem={(item) => {
console.log(item);
return (
<View
style={{
width: "100%",
height: 100,
flex: 1,
alignItems: "center",
justifyContent: "center",
backgroundColor: "yellow",
}}
>
<Text>{item.title}</Text>
</View>
);
}}
/>
</View>
);
}
}
export default HotelList;

react-native-draggable-flatlist not working inside ScrollView

I am struggling for last couple of months to achieve a requirement where I'm having a draggable flatlist and a flatlist in a single scrollview and I should able to scroll the whole content.
The draggable flatlist should have autoscroll as well, that means when the list is too long and I'm trying to drag it out of the viewport, the list should scroll automatically unless I drop it.
I know the requirement is pretty much tricky but I am not getting any clue to make it work completely.
I am using the below code and I am using 'react-native-draggable-flatlist'(https://github.com/computerjazz/react-native-draggable-flatlist) for this purpose.
Code:
import React from 'react';
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
StatusBar,
TouchableOpacity
} from 'react-native';
import {
Header,
LearnMoreLinks,
Colors,
DebugInstructions,
ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
import DraggableFlatList from 'react-native-draggable-flatlist'
import { Component } from 'react'
const exampleData = [...Array(20)].map((d, index) => ({
key: `item-${index}`, // For example only -- don't use index as your key!
label: index,
backgroundColor: `rgb(${Math.floor(Math.random() * 255)}, ${index *
5}, ${132})`
}));
class App extends Component {
state = {
data: exampleData,
scrollEnabled: true
};
onEnableScroll = (value: boolean) => {
this.setState({
enableScrollViewScroll: value,
});
};
renderItem = ({ item, index, drag, isActive }) => {
return (
<TouchableOpacity
style={{
height: 100,
backgroundColor: isActive ? "blue" : item.backgroundColor,
alignItems: "center",
justifyContent: "center"
}}
onLongPress={drag}
>
<Text
style={{
fontWeight: "bold",
color: "white",
fontSize: 32
}}
>
{item.label}
</Text>
</TouchableOpacity>
);
};
render() {
return (
<ScrollView
style={{ backgroundColor: '#000', flex: 1 }}
contentContainerStyle={{ paddingTop: 800, paddingBottom: 100 }}
scrollEnabled={this.state.scrollEnabled}
>
<DraggableFlatList
data={this.state.data}
renderItem={this.renderItem}
keyExtractor={(item, index) => `draggable-item-${item.key}`}
onMoveBegin={() => this.setState({ scrollEnabled: false })}
onMoveEnd={({ data }) => {
this.setState({ scrollEnabled: true, data });
}}
/>
<FlatList
data={this.state.data}
renderItem={this.renderItem}
keyExtractor={(item, index) => `draggable-item-${item.key}`}
/>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
scrollView: {
backgroundColor: Colors.lighter,
},
engine: {
position: 'absolute',
right: 0,
},
body: {
backgroundColor: Colors.white,
},
sectionContainer: {
marginTop: 32,
paddingHorizontal: 24,
},
sectionTitle: {
fontSize: 24,
fontWeight: '600',
color: Colors.black,
},
sectionDescription: {
marginTop: 8,
fontSize: 18,
fontWeight: '400',
color: Colors.dark,
},
highlight: {
fontWeight: '700',
},
footer: {
color: Colors.dark,
fontSize: 12,
fontWeight: '600',
padding: 4,
paddingRight: 12,
textAlign: 'right',
},
});
export default App;
You should use ListFooterComponent and ListHeaderComponent method to render items.
Please change your render method like below code.
render() {
return (
<View
style={{ backgroundColor: '#000', flex: 1 }}
>
<DraggableFlatList
data={this.state.data}
renderItem={this.renderItem}
keyExtractor={(item, index) => `draggable-item-${item.key}`}
onMoveBegin={() => this.setState({ scrollEnabled: false })}
onMoveEnd={({ data }) => {
this.setState({ scrollEnabled: true, data });
}}
ListFooterComponent={() => {
return <View>
<FlatList
data={this.state.data}
renderItem={this.renderItem}
keyExtractor={(item, index) => `draggable-item-${item.key}`}
/>
</View>
}}
/>
</View>
);
}
In my case, I have another ScrollView composition.
My solution was found in this repository:
React Native Draggable FlatList
I replaced:
ScrollView -> NestableScrollContainer
DraggableFlatList -> NestableDraggableFlatList
Initially there was one DraggableFlatList but in this case I was able to scroll via the DraggableFlatList

Declaring array for use in React Native AutoComplete search engine

Not sure where I go about declaring the array with which I want to search from, any assistance would be appreciated. I believe my issue is that I am declaring the "services' array in the incorrect area but I am not sure where else to put it! Or if the commas are the right character to be using in between strings/services
import React, { useState, Component } from 'react';
import { StyleSheet, StatusBar, View, Text, Button, TouchableOpacity } from 'react-native';
import AutoComplete from 'react-native-autocomplete-input';
class CareProviderSequenceScreen extends Component {
constructor (props) {
super (props);
this.state = {
services: [],
query: '',
}
}
render() {
const query = this.state;
const services = {
"Pick up my Prescription",
'Pick up groceries',
'Pick up dry cleaning',
'Pick up my pet',
}
return (
<View style={styles.container}>
<Autocomplete
autoCapitalize="none"
autoCorrect={false}
containerStyle={styles.autocompleteContainer}
//data to show in suggestion
data={services.length === 1 && comp(query, services[0].title) ? [] : services}
//default value if you want to set something in input
defaultValue={query}
/*onchange of the text changing the state of the query which will trigger
the findFilm method to show the suggestions*/
onChangeText={text => this.setState({ query: text })}
placeholder="Enter your need"
renderItem={({ item }) => (
//you can change the view you want to show in suggestion from here
<TouchableOpacity onPress={() => this.setState({ query: item.title })}>
<Text style={styles.itemText}>
{item.title} ({item.release_date})
</Text>
</TouchableOpacity>
)}
/>
<View style={styles.descriptionContainer}>
{services.length > 0 ? (
<Text style={styles.infoText}>{this.state.query}</Text>
) : (
<Text style={styles.infoText}>Enter The Film Title</Text>
)}
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: '#F5FCFF',
flex: 1,
padding: 16,
marginTop: 40,
},
autocompleteContainer: {
backgroundColor: '#ffffff',
borderWidth: 0,
},
descriptionContainer: {
flex: 1,
justifyContent: 'center',
},
itemText: {
fontSize: 15,
paddingTop: 5,
paddingBottom: 5,
margin: 2,
},
infoText: {
textAlign: 'center',
fontSize: 16,
},
});
export default CareProviderSequenceScreen ;
CareProviderSequenceScreen .navigationOptions = () => ({
title: "Home & Personal Care",
headerTintColor: '#9EBBD7',
headerStyle: {
height: 65,
backgroundColor: '#1E5797',
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 1,
},
shadowOpacity: 0.20,
shadowRadius: 1.41,
elevation: 2,}
});
First, you are assigning an object to services array.
Second, you are not accessing the query state properly. It should be
const { query } = this.state

Categories

Resources