How to connect special symbols like ¥ in react-native - javascript

I want connect a string use " ` " , and wish " & yen; " will show as "¥", the code like below :
let str=`${period} per (money:¥${money})`
but did not work for me ,
by the way,I write it use react-native

To parse HTML Entities you can use the npm module html-entities.
Here is a working example:
import { Html5Entities } from 'html-entities';
render() {
const entities = new Html5Entities();
return (
<SafeAreaView style={styles.container}>
<View>
<Text> {entities.decode('&yen')} </Text>
</View>
</SafeAreaView>
);
}
Output:

you can use javascript native method like
let formattedMoney = new Intl.NumberFormat('ja-JP', { style: 'currency', currency: 'JPY' }).format(money);
let str=`${period} per (money:${formattedMoney})`

Related

How to properly use map() in a array?

Im pretty nub at react and JS, so, this is probably a stupid question, but, when I try to use the .map() in a array like this:
import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import { Constants } from 'expo';
export default class App extends React.Component {
productsArray = [
'Cajo T-shirt',
'Geometric Skull',
'Bavaria 350 mL',
'Inflatable Alien',
'R2D2 RC Car',
];
renderCategories(arrayDeProdutos) {
return arrayDeProdutos.map((index) => <Text key={index}></Text>);
}
render() {
return (
<View style={styles.container}>
{this.renderCategories()}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
},
});
I got the following error message: "arrayDeProdutos.map is not a object". I tryed to read the map documentation, but it did'n answered my question.
renderCategories methods expects a parameter but you pass none as can be seen here:
<View style={styles.container}>
{this.renderCategories()}
</View>
Here is what you need to do isntead.
renderCategories(arrayDeProdutos) {
return arrayDeProdutos.map((index) => <Text key={index}></Text>);
}
render() {
return (
<View style={styles.container}>
{this.renderCategories(this.productsArray)}
</View>
);
}
Your render function would look like the following :
render() {
return (
<View style={styles.container}>
{this.productsArray.map((prod, index) => <Text key={index}>{prod}</Text>)}
</View>
);
}
Be careful as map will return the index of your item as the second parameter and not the first one.
By putting your map in the render function there is no need for renderCategories to exist.
I would also recommend putting this array in your state if it can change at runtime. This will allow your app to re-render your text after any change is made to it.
Another thing, anything declared in a class is accessible via this. in this same class, no need to pass any parameter.
You need to pass argument to renderCategories(). So change
render() {
return (
<View style={styles.container}>
{this.renderCategories()}
</View>
);
}
to
render() {
return (
<View style={styles.container}>
// pass "this.productsArray" as an argument
{this.renderCategories(this.productsArray)}
</View>
);
}
Yes, the other answers are right, but I do not agree with using an index in this case. Also, I think in a real situation you will get your data from backend and most likely you will have an id. So you can use your id as an index. ( I prefer arrow functions )
const productsArray = [
"Cajo T-shirt",
"Geometric Skull",
"Bavaria 350 mL",
"Inflatable Alien",
"R2D2 RC Car"
];
export default class App extends React.Component {
//using arrow function
renderCategories = products => products.map(product => <Text key={product}>{product}</Text>);
render() {
return (
<div style={styles.container}>{this.renderCategories(productsArray)}</div>
);
}
}

Not able to dynamically build svg path react native

I'm building a custom bottomnavbar for my app, and I'm running into a problem with linking the svg icons. Here is my code:
// Imports
class MainTabNavigation extends React.Component {
render() {
const navigationOptions = ['Dashboard','Status','Referrals','More'];
return(
<View style={styles.navBar}>
{
navigationOptions.map(nav => {
const lowerCaseString = nav.toLowerCase();
const svgPath = `../../assets/icons/${lowerCaseString}.svg`;
if (this.props.navigation.isFocused(nav)) {
return(
<TouchableOpacity style={[styles.tab,styles.focused]} onPress={() => {this.props.navigation.navigate(nav)}}>
<SvgUri source={require(svgPath)} />
<Text style={styles.captionStyle}>nav</Text>
</TouchableOpacity>
);
} else {
return(
<TouchableOpacity style={styles.tab} onPress={() => {this.props.navigation.navigate({nav})}}>
<SvgUri source={require(svgPath)} />
<Text style={styles.captionStyle}>{nav}</Text>
</TouchableOpacity>
);
}
})
}
</View>
);
}
}
// Styles
const NavigationConnected = withNavigation( MainTabNavigation );
export { NavigationConnected as MainTabNavigation };
And the error message is very strange. The error message says:
calls to `require` expect exactly 1 string literal argument, but this was found: `require(svgPath)`.
What I can't understand is that svgPath is literally (excuse the pun) one string literal. I understand that I'm concatenating the string, but it is still just one string literal. So my question is two fold:
1. Why is the variable svgPath not one string literal?
2. How can I dynamically build my svg paths through my map() call?
In order for this to work, the image name in require has to be known statically.
// GOOD
<Image source={require('./my-icon.png')} />;
// BAD
var icon = this.props.active ? 'my-icon-active' : 'my-icon-inactive';
<Image source={require('./' + icon + '.png')} />;
// GOOD
var icon = this.props.active
? require('./my-icon-active.png')
: require('./my-icon-inactive.png');
<Image source={icon} />;
ref: https://facebook.github.io/react-native/docs/images.html

how to use for loop with JSX elements to print content of collection into multiple <Text> tags in React Native?

Basically I want to achieve the topology below within React Native render():
<View>
<Text>collection.key1</Text>
<Text>collection.key2</Text>
<Text>collection.key3</Text>
.
.
.
<Text>collection.keyN</Text>
</View>
But I struggle with using for loop with JSX tags since I'm very new to JSX.
Here's my code that's not working to give you more idea of what I'm trying to achieve:
collectionToView(collection, keys)
{
let rows = [];
for (key in keys)
{
rows.push(<Text> key + ": " + collection[key] </Text>);
}
return rows;
}
and later inside a scrollView I would like to render it like to render it like this somehow:
<View>
{this.collectionToView(userData, {'serial','product_id','product_name','status'})}
</View>
Can anyone show me how to achieve this in React Native?
renderItem() {
const list = [
{
price: '5,000',
text: 'April stay also',
},
{
price: '6,000',
text: 'May stay also',
},
]
return (
<View>
{list.map((val, key) =>
<View key={key} >
<Text>{val.price}</Text>
<Text>{val.text}</Text>
</View>
)}
</View>
);
}
use:
<View>
{this.renderItem()}
</View>

How to show images dynamically with react native

I want to build an album app with react native, the main idea is to use a sectionList and show the data in an array like this:
class CustomImage extends Component{
render(){
return(
<View>
<Image style={styles.Img} source={this.props.imageName} />
<Text style={styles.text}>{this.props.name}</Text>
</View>
);
}
}
export default class DisplayAnImage extends Component {
render() {
return (
<View>
<SectionList
sections={[
{titile: 'small soldier', data: ["./gifs/2.gif", "./gifs/3.gif", "./gifs/4.gif"]}
]}
renderItem={({item}) => <CustomImage name={item} fromWeb={false} imageName={require(item)} />}
renderSectionHeader={({section}) => <Text style={styles.sectionHeader}>{section.title}</Text>}
/>
</View>
);
}
}
Above code was indented to make it work inspirited by this answer
I have already put the gifs folder under the project folder, and if I using a static string as source={require(url)} in the Image component, things will work, but when the url came out of an array items iteration, it will not work.
How can I make this work with react native?
EDIT
Don't know if I could edit to make it more specificly, the really thing I want to do is to use a generated array like this:
function numberRange(start, end){
return new Array(end-start).fill().map((d,i) => {
var url = "./gifs/" + ( i+start) + ".gif";
return require(url)
});
}
export default class DisplayAnImage extends Component {
render() {
return (
<View>
<SectionList
sections={[
{title: 'small soldier', data: numberRange(2,30)},
{title: 'small soldier', data: numberRange(31,60)}
]}
renderItem={({item}) => <CustomImage name={item} fromWeb={false} imageName={item} />}
renderSectionHeader={({section}) => <Text style={styles.sectionHeader}>{section.title}</Text>}
/>
</View>
);
}
}
Don't know if have a way to use this array generator to make an array or I have to enter the path one by one on bare hand :-(
require is a javascript keyword with a preload nature.
And, images will not related to path at runtime --- provide a path to it will not get anything. it becomes bundle resources, so with console.log you can only see resource token related to bundle ex: _1 _2.
It will not work even change require("./gifs/1.gif") to require("./gifs/"+"1.gif").
Try this:
data: [require("./gifs/2.gif"), require("./gifs/3.gif"), require("./gifs/4.gif")]

React native mapping through array with object childs - working different as in react web?

I have this array which contains objects:
var tmp_array = [
{ headline: "Test", text: "Test text", send_at: "test date" }
];
Now in the web react environment I was able to map through this array and return its values to a variable which can then be rendered.
So I used the same approach:
var i = -1;
var WholeNews = tmp_array.map(function(news){
i++;
return(
<View key={i}>
<Text>{news.headline}</Text>
<View>
<Text>{news.text}</Text>
</View>
</View>);
});
After the mapping has finished it should be rendered as following:
return(
<View>
{WholeNews}
</View>
);
Unfortunately I receive a warning in my iOS Simulator which says:
Objects are not valid as a React child(found: object with keys {WholeNews}). If you meant to render a collection of children, use an array instead or wrap the object using createFrament(object) from the React-addons.
I am not sure whether I am missing out something completely or react native simply doesn't support a mapping through an array as in my example.
This should work:
WholeNews() {
return tmp_array.map(function(news, i){
return(
<View key={i}>
<Text>{news.headline}</Text>
<View>
<Text>{news.text}</Text>
</View>
</View>
);
});
}
render() {
return(
<View>
{this.WholeNews()}
</View>
)
}
Try forEach method instead of map:
var WholeNews =[];
tmp_array.forEach(function(news, i){
WholeNews.push(
<View key={i}>
<Text>{news.headline}</Text>
<View>
<Text>{news.text}</Text>
</View>
</View>);
});
And note from where you can get the i index..

Resources