Why set dollar is not working? - react-native

If i just set require('../img/dest.png') the image is working, but when i try to use like
It will show error
calls to require expect exactly 1 string literal argument but this was found: require(""+item.img+"").(null)
Any one knows what happens in my dollar variable ?
Thanks in advance.
render() {
// Taken from https://flatuicolors.com/
const items = [
{ name: 'Name', code: '#1abc9c', url: 'yahoo.com.tw', img: '../img/dest.png' }
];
return (
<GridView
itemDimension={130}
items={items}
style={styles.gridView}
renderItem={item => {
console.log(`'${item.img}'`);
return (
<TouchableOpacity onPress={() => this.showLinkAlert(item.name, item.url)}>
<ImageBackground source={require(`'${item.img}'`)} style={[styles.itemContainer, { backgroundColor: '#bdc3c7' }]}>
<Text style={styles.itemName}>{item.name}</Text>
</ImageBackground>
</TouchableOpacity>
);
}}
/>
);
}
}

The string substitution happens at run time, but require happens at build time. So when require runs it doesn't substitute anything, it just tries to find a file called that.

Related

How to Get Multiple TextInput Values in single variable in React-Native?

How to get values from multiple TextInput fields coming from array passing by map function to single variable by entering text in them? When i try to enter text in second TextInput it replaces the value which i stored from first TextInput.
Secondly instead of this, if i use push() function, it doesn't give desired output. What I exactly want is that to get the values of these three InputText and to store in single variable using single OnChangeEvent (as I am using Map() function).
Below is the sample of code on which i am working in React-Native.
this.state={
checkboxAttCollection:[{"Id": 10, "AttibuteCollectionName": "PowerTest"}, {"Id": 22, "AttibuteCollectionName": "36W"}, {"Id": 23, "AttibuteCollectionName": "Test123"}],
getInputText:'',
getInputvariables:[],
onChangeTextComp=(TextValue,index)=>{
this.state.getInputText=TextValue
console.log("******",this.state.getInputvariables)
this.state.getInputvariables.push(this.state.getInputText)
console.log("******",this.state.getInputvariables)
{this.state.checkboxAttCollection.map((item, i) =>
return (<View key={item.AttibuteCollectionId} style={{ flexDirection: 'row',}}>
<TextInput style={{height:hp('5%'),width:wp('60%'),backgroundColor:'red',borderBottomWidth:2,paddingVertical:0}}
onChangeText={(text)=>this.onChangeTextComp(text,i)}
MultiInputText={true}/>
{/* </View> */}
</View>)
})}
Try this way
this.state={
......
inputVlaues: []
}
onChangeTextComp=(value,index)=>{
const inputData = [...this.state.inputVlaues];
inputData[index] = value;
this.setState(inputVlaues: inputData);
}
{this.state.checkboxAttCollection.map((item, i) =>
return
(<View key={item.AttibuteCollectionId} style={{ flexDirection: 'row',}}>
<TextInput
onChangeText={(text)=>this.onChangeTextComp(text,i)}
......
value={this.state.inputVlaues[i] || ""}
/>
</View>)
})}
as an option you can generate event handlers dynamically
const [form, setForm] = useState({})
const createHandler = (fieldName) => {
return (newFieldValue) => {
setForm((oldValue) => {
return {
...oldValue,
[fieldName]: newFieldValue
}
})
}
}
return (
<>
<TextInput onChange={createHandler('name')} />
<TextInput onChange={createHandler('surname')} />
</>
)

How to render local images according to the id of the items fetched from url?

I have created an images folder in assets and I have saved some pictures in it. And I wanted to render those pictures according to the id of the items that I have fetched from the url, I renamed all those picture according the id of the items fetched. But it is not working. Does anybody can help me to figure out or if you have another suggestion to do it I am open for suggestions. Here you can see what I am trying to do:
export default function App() {
const [material, setMateral] = useState([]);
useEffect(() => {
axios
.get("http://localhost:5000/materals/")
.then((products) => {
setMaterial(materials.data.response);
})
.catch((err) => {
console.error(err);
});
}, []);
return (
<View style={styles.container}>
{material.map((material) => {
console.log(material);
const { id, name, categories, genders, brands, price } = material;
<View style={styles.materialsContainer}>
<View style={styles.materialsItem}>
<Image
source={"../../assets/images/${id}.jpg"}
alt={id}
style={styles.thumbnail}
/>
<Text style={styles.box} numberOfLines={1}>
${id}
</Text>
<Text style={styles.box}${name}</Text>
<Text style={styles.box}${categories}</Text>
<Text style={styles.box}${genders}</Text>
<Text style={styles.box}${brands}</Text>
<Text style={styles.box}$ ${price}</Text>
</View>
</View>;
})}
);
}
Here is what I got in the console
Your problem is here:
<Image
source={"../../assets/images/${id}.jpg"}
alt={id}
style={styles.thumbnail}
/>
You should be using backticks (``) rather than double quotation to perform string interpolation.
<Image
source={`../../assets/images/${id}.jpg`}
alt={id}
style={styles.thumbnail}
/>
I'm also not sure what you're trying to do in your Text components
<Text style={styles.box}${name}</Text>
Are you trying to add a '$' as a string before the name? If you're trying to perform string interpolation, the ${} format only works when using backticks. But in this case, you could just do this.
<Text style={styles.box}>{name}</Text>

react-native "In this environment the sources for assign must be an Object" error with RNSwipeout

I have look at a couple of places and have tried a few workarounds but none of them worked either.
With the following Code (A Flatlist with Swipeout to delete Listelements):
<FlatList data = {this.state.needList}
refreshing = {this.refreshing}
onRefresh = {this.refreshItems.bind(this)}
renderItem = {({item, index}) => {
let swipeoutBtns = [
{
text: 'Delete',
backgroundColor: 'red',
onPress: () => {
console.log(this.itemsRef.child(this.state.needList[index].key));
this.itemsRef.child(this.state.needList[index].key).remove();
this.getItems(this.itemsRef);
}
},
];
return(
<Swipeout right = {swipeoutBtns}
autoClose = {true}>
<View style = {[styles.flatListCss,
{backgroundColor: index %2 == 0 ? '#dbdbdb' : 'white'}]}>
<Text style = {styles.flatListCssText}>{item.item}</Text>
<Text style = {styles.flatListCssText}>{item.amount}
<Text style = {styles.flatListCssText}> {item.value}</Text>
</Text>
</View>
</Swipeout>
);
}}>
</FlatList>
I get the following Error message:
"TypeError: In this environment the sources for assign MUST be an object."
I have followed the example from here: https://github.com/dancormier/react-native-swipeout
For some reason it doesn´t work for me.
A fix would be perfect. A workaround would be great as well.
Thanks ahead!

undefined is not an object (evaluating '_this2.onRadioPressed')

I'm building radio buttons using my component and the buttons are built fine but the onPress is not working. I get the error in the title on click of the radio button. I suspect, based on the error, that 'this' is not what I think it is. Any help is appreciated. Here's the relevant code:
let radio_props = [
{label: 'forward', value: 0 },
{label: 'back', value: 1 }
];
<RadioBtn
radioGroupLabel={'Main Label'}
radioLabels={radio_props}
style={styles.radioElement}>
</RadioBtn>
Then in my RadioBtn.js file...
onRadioPressed = (val) => {
console.log('VAL:', val);
this.setState({selectedValue:val});
};
renderRadios(obj, i) {
console.log('OBJ:', obj);
return (
<View style={styles.firstRadioContainer}>
<TouchableOpacity
onPress={(value, index) => {
this.onRadioPressed(obj.value)
}}
underlayColor='#f1c40f'>
<Text value={obj.value} style={styles.radio}>{obj.label}</Text>
</TouchableOpacity>
</View>
)
};
render() {
let renderedRadios = this.props.radioLabels.map(this.renderRadios);
return (
<View>
<View style={styles.radioLabelContainer}>
<Text style={styles.radioLabel}>{this.props.radioGroupLabel}</Text>
</View>
<View style={styles.radioGrp}>
{renderedRadios}
</View>
</View>
);
};
You are right, this in renderRadios method is no longer pointing to RadioBtn class because of the way you invoke in the array's map method.
Try changing to the following by using arrow function expression:
let renderedRadios = this.props.radioLabels.map((o, i) => this.renderRadios(o, i));

Some images not showing up, linking not working in react native

EDIT: The image issue has been resolved, but still not sure about Linking.
Okay so I'm having two weird questions. And apologies ahead of time for the code.
First thing's first, some images will simply not display even though they're valid. When running this in my IOS simulator, the very first image will not display. But some images always work.
The second thing, and let me know if this should be two separate questions, is linking to an external site. It doesn't appear to be able to do the Linking.open in IOS. So I wondered what is the easiest way, through linking or otherwise, of simply opening an external URL in both android and IOS?
Thanks a lot!
openUrl(url) {
Linking.canOpenURL(url).then(supported => {
if (supported) {
Linking.open(url);
} else {
console.log('nope :: ' + url);
}
}).catch(err => console.error('An error occurred', err));
// browser.open(url);
},
renderImage(event, index) {
if (this.state.showBox && this.state.boxIndex == index) {
return (
<View>
<TouchableHighlight onPress={()=>this._clickImage(event, index)}>
<Image source={{ uri: event.image }} style={[styles.image, this.calculatedSize(), this.getImageStyles(event.featured), { height: 100 }]} />
</TouchableHighlight>
<View style={{ flexDirection:'row', padding: 15 }}>
<Text style={styles.price}>{event.price}</Text>
<Text style={styles.time}>{event.time}</Text>
<TouchableHighlight onPress={()=>this.openUrl(event.website)}>
<Text style={styles.btn}>Website</Text>
</TouchableHighlight>
</View>
{renderif(event.venue)(
<TouchableHighlight onPress={()=>this.openUrl(event.venue)}>
<Text style={styles.btn}>Venue</Text>
</TouchableHighlight>
)}
</View>
)
} else {
return (
<View>
<TouchableHighlight onPress={()=>this._clickImage(event, index)}>
<Image source={{ uri: event.image }} style={[styles.image, this.calculatedSize(), this.getImageStyles(event.featured)]} />
</TouchableHighlight>
</View>
)
}
},
That's because some of your images are trying to load image from http connection.IOS apps require you to use https for images.
For example in this
{
title: 'test',
image: 'http://www.piedmontpark.org/images/bird_pine_warbler_330.jpg',
featured: true,
category: 'Music',
price: '$8.00',
time: '7:00 PM-11:00 PM',
venue: '',
website: 'http://google.com'
}
Your 'image' is trying to load a jpg from http.
Check this out on how to configure your info.plist to accept http