Space-evenly display text in React Native - react-native

I want to display my text with even amount of space per line of text displayed similar to how eBooks display texts. I could only find resources regarding displaying many <View>s in space-evenly or space-between using flexbox justifyContent.
I have a <Text>a lot of text inside....</Text> and I want the text inside should be evenly spaced. How could I space my words inside the <Text>?
const TextDisplay = () => {
const part = part0004_split_010;
const text_example =
"fdkfjldjsfljsldfjlskdjflsdjf alkjgdlkjg lkdjgflkdjgkld kdjfauieghjknf uio 23jo1j kldanglk3tlk jasdn lskj jie hgihigehi anvmcnvmcn ,zmnmx nmf ei nvi nie 2 i2j42in42i n kd nk nskan lk lkdas j92al klkjr1l2or a;z;z;z; 9r3ur9j 39 091 jr1 j a,c n kn oian iong oien voin ow ni ei nwoinq ei n93 n99";
return (
<View style={styles.container}>
<ScrollView style={styles.scrollview}>
<Text style={styles.text_style}>{text_example}</Text>
</ScrollView>
</View>
);
};
export default TextDisplay;
const styles = StyleSheet.create({
container: {
flex: 1,
borderColor: "red",
borderWidth: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "grey",
width: "80%",
},
scrollview: {
flex: 1,
justifyContent: 'space-evenly'
},
text_style: {
fontSize: 20,
color: "black",
},
});
I tried using justifyContent: 'space-evenly' on my scrollView but it doesn't change anything

You can use textAlign:"justify" in the styles of a <Text> to make the text justified.

Related

React Native: Warning: Each child in a list should have a unique "key" prop

I'm quite new to React Native and have a question.
I get this warning: Each child in a list should have a unique "key" prop.
I've tried everything. Now I even have Math.random() as key and I still get the warning.
Home.js:
return(
<ScrollView style={styles.container}>
<StatusBar barStyle='light-content' />
<ImageBackground source={image} style={styles.image} imageStyle={styles.image2}>
<LinearGradient colors={['transparent', 'rgba(249,249,249,1)' ]} locations={[.4, 1]}
style={{
position: 'absolute',
left: 0,
right: 0,
top: 0,
height: 400
}} />
<TouchableOpacity activeOpacity={0.9} style={styles.topNews} onPress={()=> navigation.navigate('WebView')}>
<Text style={styles.topCategoryText}>ITALIAN LEAGUE</Text>
<Text style={styles.topTitleText}>Juventus legend: Ronaldo is natural to be criticized</Text>
<Text style={styles.topSourceText}>CNN Sport</Text>
</TouchableOpacity>
</ImageBackground>
<View style={{marginHorizontal: 10, flex: 1}}><RNMasonryScrollView
colums='2'
columnStyle={{flexDirection: 'column'}}
oddColumnStyle={{flex: 1, marginRight:15, marginLeft:10}}
evenColumnStyle={{flex:1,marginLeft:15}}
>
{[
<NewsDetail Key='1' title="Papers: Salah eager for Barca move" category='LA LIGA' imageSrc='https://en.as.com/en/imagenes/2020/06/11/football/1591881357_315795_noticia_normal.jpg'/>,
<NewsDetail Key='2' title="Man Utd struggles 'mentally impacting' Pogba, says France boss Deschamps" category='PREMIER LEAGUE' imageSrc='https://resources.premierleague.com/premierleague/photo/2019/06/20/88784d96-ef4b-4414-8b59-517c15b162a5/MW1-EditorialLead-new.png'/>,
<NewsDetail Key='3' title="Arsenal's complete player: The meteoric rise of Vivianne Miedema" category='PREMIER LEAGUE' imageSrc='https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcTupBTx2is9w3Z7pIhrorpPDMTFHmQhS1Ypmg&usqp=CAU'/>,
<NewsDetail Key='4' title="Mourinho hit with suspension by UEFA" category='SERIE A' imageSrc='https://www.telegraph.co.uk/content/dam/football/2018/02/13/TELEMMGLPICT000153853426_trans_NvBQzQNjv4BqwD2sfO9joeQ6RY-qlTATNB2cSHopZMn-aCc647VHTAY.jpeg'/>,
<NewsDetail Key='5' title="'Ronaldo is definitely faster than me!' – Bolt" category='LA LIGA' imageSrc='https://resources.premierleague.com/premierleague/photo/2018/08/10/bf1acdf0-7b10-4dfe-8844-06f0f18d5c38/2018-08-10T192712Z_1257041591_RC18CE142CA0_RTRMADP_3_SOCCER-ENGLAND-MUN-LEI.JPG'/>,
<NewsDetail Key='6' title="Southgate admits to fears over Maguire's career" category='LIGUE 1' imageSrc='https://images.daznservices.com/di/library/GOAL/a8/c9/vivianne-miedema-goal-50-gfx_nuhcgkr4tthu1kyux2ymq4y4l.jpg?t=-1147520971&quality=60&w=1200'/>,
]}
</RNMasonryScrollView></View>
</ScrollView>
)
NewsDetail.js
import React, {useState, useEffect} from 'react';
import {View, Text, StyleSheet, Image, Dimensions } from 'react-native';
const NewsDetail = (props) => {
const random = Math.random()
const ViewWidth = 157.5
// const [imageSize, setImageSize] = useState({width: 0, height: 0});
// const [viewSize, setViewSize] = useState({width: 0, height: 0});
const [imageHeight, setHeight] = useState(0);
const myUri = props.imageSrc;
useEffect(() => {
Image.getSize(myUri, (width, height) => {
setHeight(height / (width / ViewWidth));
});
}, [])
if(imageHeight > 0){
console.log(random)
return (
<View style={styles.newsDetail} key={`${random}`}>
<Image
resizeMode='cover'
style={{
width: ViewWidth,
height: imageHeight,
borderTopLeftRadius: 7,
borderTopRightRadius: 7,
}}
source={{ uri: myUri,}}
/>
<Text style={styles.textOne}>{props.category}</Text>
<Text style={styles.textTwo}>{props.title}</Text>
</View>)
} else return null;
}
const styles = StyleSheet.create({
image:{
width: '100%',
borderTopLeftRadius: 7,
borderTopRightRadius: 7
},
newsDetail:{
backgroundColor: "white",
marginTop: 10,
borderRadius: 7,
opacity: 0.9,
shadowColor: "grey",
shadowRadius: 5,
shadowOffset: {width: 0, height: 0},
shadowOpacity: 0.3
},
textOne:{
fontSize: 10,
color: '#7A7F82',
fontWeight: 'bold',
paddingTop: 10,
paddingHorizontal: 10,
paddingBottom:3
},
textTwo:{
fontSize: 14,
color: '#2D3041',
fontWeight: 'bold',
paddingHorizontal: 10,
paddingBottom:10
}
});
export default NewsDetail;
I dont know what to do. Any help? Also, is there any websites where I can pay to get quick help on questions I have about React Native? Similar to StackOverflow just you pay to get quick answers on all questions?
A proper way to generate a list is to create an array of objects, then you use map to display. In your codes, it's almost correct. You should use key instead of Key.
const articles = [
{ id: 1, title: "Papers: Salah eager for Barca move", category: 'LA LIGA', imageSrc: 'https://en.as.com/en/imagenes/2020/06/11/football/1591881357_315795_noticia_normal.jpg' },
{id: '2', title: "Man Utd struggles 'mentally impacting' Pogba, says France boss Deschamps", category: 'PREMIER LEAGUE', imageSrc: 'https://resources.premierleague.com/premierleague/photo/2019/06/20/88784d96-ef4b-4414-8b59-517c15b162a5/MW1-EditorialLead-new.png'},
{ id:'3',title: "Arsenal's complete player: The meteoric rise of Vivianne Miedema", category: 'PREMIER LEAGUE', imageSrc: 'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcTupBTx2is9w3Z7pIhrorpPDMTFHmQhS1Ypmg&usqp=CAU'}]
<RNMasonryScrollView
colums='2'
columnStyle={{flexDirection: 'column'}}
oddColumnStyle={{flex: 1, marginRight:15, marginLeft:10}}
evenColumnStyle={{flex:1,marginLeft:15}}
>
{ articles.map((article) => {
return <NewsDetail key={article.id} title={article.title} imageSrc={article.imageSrc} />
})}
</RNMasonryScrollView>

Why are my React Native View heights inconsistent?

I have the following code:
return (
<>
<View style={styles.dashboardListItemContainer}>
<View style={styles.listItemBorder} />
</View >
</>
)
const styles = StyleSheet.create({
dashboardListItemContainer: {
minHeight: 73,
backgroundColor: COL_DARK_BG,
display: "flex",
flexDirection: "column",
},
listItemBorder: {
minHeight: 0.5,
backgroundColor: 'white',
}
});
Which produces the following result:
My question is, why are the lines inconsistently bright / appear to be different heights?
Also when I change column to row here: flexDirection: "row", the line disappears completely. I can't tell if this is a bug or there are errors in my code?
TIA.
Update:
I cannot solve this problem on any device, and I've tried different methods for determining the height.
borderBottomWidth: StyleSheet.hairlineWidth, looks like this:
You can see in the above picture some lines do not even show up.
borderBottomWidth: StyleSheet.hairlineWidth * 2, looks like this:
And height: 0.5, looks like this on a white background:
The problem is consistent across devices, it is at the edge of an item in a <FlatList>.
Android Emulator has less resolution, try on a real device, sometimes i have the same error, and when I run on a real device it looks good.
We can use flex value.
import React, { Component } from "react";
import { View, FlatList } from "react-native";
import { StyleSheet } from "react-native";
class App extends Component {
render() {
return (
<FlatList
data={[1, 2, 3, 4, 5, 6, 7, 8, 9]}
extraData={[1, 2, 3, 4, 5, 6, 7, 8, 9]}
horizontal={false}
renderItem={({ item, index }) => {
return (
<View style={styles.dashboardListItemContainer}>
<View style={styles.listItemBorder} />
</View>
);
}}
key={({ item, index }) => index}
/>
);
}
}
export default App;
const styles = StyleSheet.create({
dashboardListItemContainer: {
backgroundColor: "red",
display: "flex",
flex: 1,
minHeight: 73,
flexDirection: "column"
},
listItemBorder: {
minHeight: 0.5,
backgroundColor: "yellow"
}
});

Access to style property and change it

I am new to React-Native. Say I have a styleSheet contains style for a green button:
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
},
greenB:{
padding: 5,
height: 80,
width: 80,
borderRadius:160,
backgroundColor:'green',
}, ........
And for some reason I need to change that colour in my code.
render(){
....
const {container, greenB}=styles; //Not sure, how else can I define greenB?
greenB.backgroundColor='black';
return (
<View style={styles.container}>
<View style={styles.greenB} >
....
How can I access backgroundColor from greenB and change that?
I'm getting a TypeError "Attempted to assign to readonly property",
which is reasonable cause styles is a const.
tried to read about state management but not sure how to use it in this case.
React Native's StyleSheet.create is used for better performance and clean code, It caches the style ids to reduce the amount of data that goes through the bridge, so that is why you cannot alter it but only use it .
But there're many solutions, You can use simple javascript object and alter the values as you want.
For example:-
let Styles= {
Text:{
color:'blue'
}
}
Styles.Text.color= 'green'
<Text style={Styles.Text} > </Text>
More over, For dynamic styling i recommend using states instead of variables .

Setting up a table layout in React Native

I'm transitioning a React project into React Native and need help setting up a grid layout in React Native. I want to set up a 5-col by x-row (number of rows may vary) view. I've played around with the react-native-tableview-simple package, but I can't specify the span of a cell. I've also tried the react-native-flexbox-grid package, which I'm able to set up columns, but I'm still not able to set the span-width of a specific cell. I wonder if there's anything I can use.
For reference, I would like my table to look something along the lines like this:
|Col 1|Col 2|Col 3|Col 4|Col 5|
|------------------------------
Row 1| Text | Yes | No |
|------------------------------
Row 2| Text | Yes | No |
|------------------------------
Row 3| Text | Dropdown |
You can do this without any packages. If each row is exactly the same doing the following should solve your problem;
export default class Table extends Component {
renderRow() {
return (
<View style={{ flex: 1, alignSelf: 'stretch', flexDirection: 'row' }}>
<View style={{ flex: 1, alignSelf: 'stretch' }} /> { /* Edit these as they are your cells. You may even take parameters to display different data / react elements etc. */}
<View style={{ flex: 1, alignSelf: 'stretch' }} />
<View style={{ flex: 1, alignSelf: 'stretch' }} />
<View style={{ flex: 1, alignSelf: 'stretch' }} />
<View style={{ flex: 1, alignSelf: 'stretch' }} />
</View>
);
}
render() {
const data = [1, 2, 3, 4, 5];
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
{
data.map((datum) => { // This will render a row for each data element.
return this.renderRow();
})
}
</View>
);
}
}
After looking here for answers I discovered a really great library that behaves much like Bootstrap tables. I have found layout with React Native very challenging but this library delivers predictable layout results.
React Native Easy Grid
I agree that basic flex tables should be built in to React Native but until they are this library worked great for me.
Though it is an old post but I was looking for something similar asked in the question,
I have brainstormed and havoked the internet for the solution and the best solution I got was to import the react-native-table-component package to my project and prepare a decent table layout for my application to display data. There might be many more souls figuring out a way to do this and may I recommend this link to all your answers:This link is the npm package installer link which have explanation to all the code and have examples
Using functional components:
(Specify the number of rows and columns in the array)
Create a Row component
function Row({ column }) {
return (
<View style={styles.rowStyle}>
{column.map((data) => (
<Cell data={data} />
))}
</View>
);
}
Create a Cell component
function Cell({ data }) {
return (
<View style={styles.cellStyle}>
<Text>{data}</Text>
</View>
);
}
Create a Grid component
function Grid() {
const data = [
[15, 14, 13, 12],
[11, 10, 9, 8],
[7, 6, 5, 4],
[0, 1, 2, 3],
];
return (
<View style={styles.gridContainer}>
{data.map((column) => (
<Row column={column} />
))}
</View>
);
}
Style the components:
const styles = StyleSheet.create({
gridContainer: {
width: 220,
},
rowStyle: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-around",
},
cellStyle: {
flex: 1,
margin: 10,
},
});

Setting a border for react native TextInput

Using React native 0.26,
My component is something like this
const Search = () => {
return (
<View style={styles.backgroundImage}>
<TextInput style={styles.textInput} onChangeText={(text) => console.log(text)} placeholder={"Enter Search Term"}/>
</View>
)
}
And my styles :
const styles = StyleSheet.create({
backgroundImage: {
flex : 1,
flexDirection: "column",
justifyContent: 'center',
alignItems: 'center'
},
textInput: {
justifyContent: "center",
alignItems: "stretch",
borderRightWidth: 30,
borderLeftWidth: 30,
height: 50,
borderColor: "#FFFFFF",
}
})
The problems that I am facing are
The border right width and left width do not seem to have any effect and the placeholder text just begins on the left edge.
The background of TextInput is "grey" its the same as the View's background. I was expecting it to be white by default, (Feels transparent).
With iOS simulator how to bring up the keyboard, I would like to set returnKeyType and see how the keyboard looks (and have some code on onSubmitEditing and test).
Screenshot below :
1 You cannot declare a specific border directly on the TextInput unless multiline is enabled (For example borderLeftWidth will not work unless multiline={true} is enabled but borderWidth will work), but you can just wrap the TextInput in a View and give it a border.
inputContainer: {
borderLeftWidth: 4,
borderRightWidth: 4,
height: 70
},
input: {
height: 70,
backgroundColor: '#ffffff',
paddingLeft: 15,
paddingRight: 15
}
2 You need to declare a backgroundColor for the TextInput.
3 To make the native keyboard show up, you need to go to the simulator menu and disconnect your hardware. Go to Hardware -> Keyboard -> Connect Hardware Keyboard, toggle it off.
As of react-native: 0.61.5 you can directly set the borderBottomWidth on TextInput. Like below in inline style or if you want in separate style object.
style = {{borderBottomWidth : 1.0}}
By default the boderWidth will be set for 0. So use borderWidth : 5 defaults for (Top, Right, Bottom, Left).
If you want to asign width individually you have options like,
style = {{
borderStartWidth : 2
borderEndWidth : 3
borderTopWidth : 1
boderLeftWidth: 2
borderRightWidth: 3
borderBottomWidth : 4
}}