In react native I want to display some texts at some custom positions like in the following image:
custom location react native
How can I achieve this?
I've been playing with the following example:
import React, { Component } from 'react';
import { Text, StyleSheet } from 'react-native';
export default class TextInANest extends Component {
constructor(props) {
super(props);
this.state = {
titleText: "Bird's Nest",
bodyText: 'This is not really a bird nest.'
};
}
render() {
return (
<Text style={styles.baseText}>
<Text style={styles.titleText} onPress={this.onPressTitle}>
{this.state.titleText}{'\n'}{'\n'}
</Text>
<Text numberOfLines={5}>
{this.state.bodyText}
</Text>
</Text>
);
}
}
const styles = StyleSheet.create({
baseText: {
fontFamily: 'Cochin',
},
titleText: {
fontSize: 20,
fontWeight: 'bold',
},
});
trying to set titleText position to absolute and adding some top and leftvalues but it doesn't seem to work.
Any ideas?
From your screenshot, we could say that :
Go to Jane's profile takes 1/11 of the screen height, and is vertically centered
Bird's Nest takes 5/11 of the screen height
This is not... takes 5/11 of the screen height
As in React Native, the main axis is the vertical one (items are positionned below each others by default), you should use justifyContent to vertically centered a Text in a View.
So something like the follow should do the trick.
<View style={{ flex: 1 }}>
<Text>Go to Jane's profile</Text>
</View>
<View style={{ flex: 5, justifyContent: "center" }}>
<Text>Bird's Nest</Text>
</View>
<View style={{ flex: 5 }}>
<Text>This is not...</Text>
</View>
Improved code with working live demo https://snack.expo.io/#akhtarvahid/demo
export default class TextInANest extends React.Component {
constructor(props) {
super(props);
this.state = {
titleText: "Bird's Nest",
bodyText: 'This is not really a bird nest.'
};
}
render() {
return (
<Text style={styles.baseText}>
<Text style={styles.titleText} onPress={this.onPressTitle}>
{this.state.titleText}{'\n'}{'\n'}
</Text>
<Text numberOfLines={5} style={styles.bodyText}>
{this.state.bodyText}
</Text>
</Text>
);
}
}
const styles = StyleSheet.create({
baseText: {
fontFamily: 'Cochin',
},
titleText: {
fontSize: 20,
fontWeight: 'bold'
},
bodyText:{
position:'absolute',
left:10,
top:'50%'
}
});
Related
I am trying to get my ScrollView to scroll down so I can see all my views but it keeps bouncing back up to the top.
What it looks like
The White panels below Physiological Classification are in the ScrollView and are supposed to scroll but it just bounces back to the top.
Here is where my ScrollView is
_renderContent = (section) => {
section.arrow = !(section.arrow);
return (
<ScrollView>
<QuestionPanels
Questions={section.Questions}
pickerDefaultValues={section.pickerDefaultValues}
pickerItemNames={section.pickerItemNames}
/>
</ScrollView>
);
};
Question Panels is just a component that generates Views based on a json file. If relevant here is the code for that as well.
import React, { Component, useState, setState} from 'react';
import { ScrollView, View, Text } from 'react-native'
import styles from '../../Styles/GeneralStyles';
import Picker from '../Picker/Picker'
import appData from '../../DataSheet/appData.json';
const Panel = (props) => {
return (
<View style={styles.dropDownCardPanel}>
<View style={styles.QuestionPanel}>
<Text style={styles.QuestionText}>{props.Question}</Text>
</View>
<View style={styles.AnswerPanel}>
<Picker
defaultVal= {props.pickerDefaultValues}
showButton={false}
pickerItemNames={props.pickerItemNames}
/>
</View>
</View>
);
}
export default class QuestionairePanels extends Component {
constructor(props){
super(props)
}
render() {
var panelList = [];
for(let i = 0; i < this.props.Questions.length; i++){
panelList.push(
<Panel
key={i}
Question={this.props.Questions[i]}
pickerDefaultValues ={this.props.pickerDefaultValues[i]}
pickerItemNames = {this.props.pickerItemNames[i]}
/>
);
}
return(
<View>
{panelList}
</View>
);
}
}
Here are the styles that matter for this
dropDownCardPanel: {
height: 200,
flexDirection: "row",
backgroundColor: '#faf2f2',
paddingTop: 5,
paddingBottom: 5,
borderBottomWidth: 1,
borderColor: 'black',
},
dropDownCardPanelText: {
fontSize: 15,
color: "black",
marginLeft: 10
},
icon: {
left: 20,
},
QuestionPanel: {
height: "100%",
width: "60%",
borderRightWidth: 1,
borderColor: 'black',
left: 3,
marginRight: 5,
alignItems: "center",
justifyContent:'center'
},
QuestionText: {
fontSize: 20,
},
AnswerPanel: {
height: "100%",
width: "40%",
right: 3
}
The reason why I was not able to scroll was that the tag needs a specific height for it to render for a scroll. So to fix this I had to put a view around the and set it to a specific height.
Corrected Code
section.arrow = !(section.arrow);
var scrollHeight = (section.Questions.length > 2) ? 600 : 400;
var headerDisplay = (section.name.match("Physiologic")) ? section.name + " Variables" : "Select Dominant Final Diagnosis";
return (
<View style={{height: scrollHeight}}>
<ScrollView>
<View style={styles.dropDownCardPanelHeader}>
<Text style={styles.dropDownCardPanelHeaderText}>
{headerDisplay}
</Text>
</View>
<QuestionPanels
Questions={section.Questions}
pickerItemNames={section.pickerItemNames}
/>
</ScrollView>
</View>
Later I will try to use Flex to set the height so the react native project can scale to all screens but so far it works for iOS
I am trying to change the background color of my button but nothing seems to work, I tried the raised property, maybe i am using it incorrectly. Do any of you have any ideas?
import React from 'react';
import { StyleSheet, Text, View, Button, TouchableHighlight } from 'react-native';
export default class App extends React.Component {
state={
name: "Mamadou"
};
myPress = () => {
this.setState({
name: "Coulibaly"
});
};
render() {
return (
<View style={styles.container}>
<Button
title={this.state.name}
color="red"
onPress={this.myPress}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
Use this for adding the background color to the button in iOS:
Styles:
loginScreenButton:{
marginRight:40,
marginLeft:40,
marginTop:10,
paddingTop:10,
paddingBottom:10,
backgroundColor:'#1E6738',
borderRadius:10,
borderWidth: 1,
borderColor: '#fff'
},
loginText:{
color:'#fff',
textAlign:'center',
paddingLeft : 10,
paddingRight : 10
}
Button:
<TouchableOpacity
style={styles.loginScreenButton}
onPress={() => navigate('HomeScreen')}
underlayColor='#fff'>
<Text style={styles.loginText}>Login</Text>
</TouchableOpacity>
For Android it simply works with Button color property only:
<Button onPress={onPressAction} title="Login" color="#1E6738" accessibilityLabel="Learn more about this button" />
I suggest to use React Native Elements package, which allow to insert styles throught buttonStyle property.
styles:
const styles = StyleSheet.create({
container: {
flex: 1
},
button: {
backgroundColor: '#00aeef',
borderColor: 'red',
borderWidth: 5,
borderRadius: 15
}
})
render()
render() {
return (
<View style={styles.container}>
<Button
buttonStyle={styles.button}
title="Example"
onPress={() => {}}/>
</View>
)
}
Effect:
Expo Snack: https://snack.expo.io/Bk3zI0u0G
"color" property applies to background only if you're building for android.
Other than that I personally find it easier to manage custom buttons. That is create your own component named button and have it as a view with text. This way its way more manageable and you can import it as easy as Button.
this answer is little bit late, but can be good for anothers.
To solve this problem it is better to use "Text" Component as a Button
fist make a component name it AppButton
function AppButton({children,style,onPress}) {
return (
<TouchableOpacity onPress={onPress}>
<Text
style={[styles.appButton,style]} >
{children}
</Text>
</TouchableOpacity>
);
}
export default AppButton;
then Import it in where that you want to use it
import AppButton from './AppButton';
and with this line you can call your custom Button that actually is a Text which you can customize it.
remember onPress Event have to calling in TouchableOpacity not Text:
<AppButton style={styles.appOk} onPress={()=> visibleFunc(false)} >Ok</AppButton>
Maybe Pressable is what you're looking for; it allows you to add style to a pressable component (like a button).Read more here
Sample code:
import React from 'react';
import { Text, View, StyleSheet, Pressable } from 'react-native';
export default function Button(props) {
const { onPress, title = 'Save' } = props;
return (
<Pressable style={styles.button} onPress={onPress}>
<Text style={styles.text}>{title}</Text>
</Pressable>
);
}
const styles = StyleSheet.create({
button: {
alignItems: 'center',
justifyContent: 'center',
paddingVertical: 12,
paddingHorizontal: 32,
borderRadius: 4,
elevation: 3,
backgroundColor: 'black',
},
text: {
fontSize: 16,
lineHeight: 21,
fontWeight: 'bold',
letterSpacing: 0.25,
color: 'white',
},
});
You should use the hex code backgroundColor="#FF0000" instead of color="red". Also please use raised={true} other wise background color is not override.
I am currently learning React Native.
I have built a view which should show a text Loading when the data is being fetched and should display the data once the data has been received by the app.
The app is hitting the backend server and is getting the URL(tried console.error on app and it does popup with ared screen showing the correct data details ).
The problem is the view is not being updated. Another thing that is weird is that the conditional view is showing the border which has been set for the container, but it does not display any text or data except that. Even if I put the correct data. Not sure if the condition is being validated correctly or not.
The border I mentioned is set in articleContainer in the stylesheet and is attached with the container which is with the condition this.state.hasResult
If i remove the style from that view the border dissappears obviously but even putting a static text inside the view is not being displayed(checked incase I parsed the json wrong.) Seems a bit confusing.
var constants = require("../constants")
var React = require('react');
var ReactNative = require('react-native');
var t = require('tcomb-form-native');
var authenticate = require("../services/authenticate")
var {
AppRegistry,
AsyncStorage,
StyleSheet,
Text,
View,
TouchableHighlight,
Alert,
ListView,
Image,
} = ReactNative;
const options = {}
class RecipePage extends React.Component{
constructor(props) {
super(props);
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1.id !== r2.id});
var getData = require("../services/get_featured");
var par = this;
var recipeId = props.recipeId;
this.state ={
hasResult: false,
noResult: false,
result: null,
isLoading: true,
}
getData(recipeId).then(function(data){
par.setState(
{
result:data,
hasResult:true,
noResult:false,
isLoading:false
}
)
}).catch(function(error) {
console.error(error);
});
}
goBack(){
this.props.navigator.pop();
}
render() {
return (
<View style={styles.container}>
<View style={styles.row}>
<Text style={styles.title}>Recipe</Text>
<TouchableHighlight onPress={this.goBack.bind(this)}>
<Image style={styles.back}
source={require("../static/images/back.png")}
/>
</TouchableHighlight>
</View>
{
this.state.hasResult &&
<View style={styles.article_container} >
<Text style={styles.article_title} >{this.state.result.id}</Text>
<Image style={styles.article_img}
source={{uri: this.state.result.image_link}}
/>
</View>
}
{
this.state.isLoading &&
<View style={styles.article_container} >
<Text style={styles.article_title} >Loading</Text>
</View>
}
</View>
);
}
}
var styles = StyleSheet.create({
container: {
justifyContent: 'center',
marginTop: 25,
padding: 20,
backgroundColor: '#ffffff',
},
title: {
fontSize: 30,
alignSelf: 'center',
marginBottom: 30
},
article_container: {
justifyContent: 'center',
marginTop: 5,
padding: 20,
backgroundColor: '#ffffff',
borderBottomColor: '#555555',
borderBottomWidth: 1,
flex:1
},
article_title: {
fontSize: 25,
alignSelf: 'center',
marginBottom: 3,
flex:2
},
article_img: {
width:200,
height:200,
alignSelf: 'center',
flex:1
},
article_description :{
fontSize:15,
flex:3
},
back:{
backgroundColor:'#ffffff',
width:20,
height:20
}
});
module.exports = RecipePage;
If you think I can improve the code not relating to this question, then feel free to comment and enlighten me :)
Edit:
I played around a bit more and found that if I change the attached styles as:-
<View style={styles.row} >
<Text style={styles.title} >{this.state.result.title}</Text>
<Image
source={{uri: this.state.result.image_link}}
/>
</View>
from
<View style={styles.article_container} >
<Text style={styles.article_title} >{this.state.result.id}</Text>
<Image style={styles.article_img}
source={{uri: this.state.result.image_link}}
/>
</View>
I am able to view the title after making this change, but image is still not displayed. And I am not sure why it was not showing for the other style.
Even if one of the style is attached -> article_title or article_container, its not being displayed.
Edit 2:
Even if I apply the style manually, it is not displayed like
<Text style={{fontSize: 25,alignSelf: 'center',marginBottom: 3,flex:2}} >{this.state.result.title}</Text>
I am navigating to this page from a parent which uses similar styles for a listview and it is showing there perfectly.
The problem seemed to be that I used flex property in styles without using ScrollView or ListView.
I would research more into that and update the answer.
I am trying to truncate a text in my reactnative app. I've decided to use the "ellipsizeMode" attribute, but I can't get it to work.
I wrote a demo of the problem :
'use strict';
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
} from 'react-native';
export class EllipsizeModeTest extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.text}>{'first part | '}</Text>
<Text style={styles.text} numberOfLines={1} ellipsizeMode={'tail'}>
{'a text too long to be displayed on the screen'}
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
},
text: {
fontSize: 20,
}
});
Now the text does not get truncated, any idea why ?
I had the same problem, it's enough to have the size of the element bound to a value. So if you define width, or add a flex value will work.
<View style={{width: 200}}><Text ellipsizeMode='tail' numberOfLines={1}></View>
You need to set a width on your Text element so it knows when to ... it
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
},
text: {
fontSize: 20,
width: 100
}
});
Try assigning a string to ellipsizeMode (remove the curly brackets):
<Text style={styles.text} numberOfLines={1} ellipsizeMode='tail'>
Try setting a width style property to the component
'use strict';
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
} from 'react-native';
export class EllipsizeModeTest extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.text}>{'first part | '}</Text>
<Text style={styles.text} numberOfLines={1} ellipsizeMode={'tail'}>
{'a text too long to be displayed on the screen'}
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
},
text: {
fontSize: 20,
width: 100
}
});
I'm trying to display the [DrawerLayoutAndroid][1] component of React Native:
/**
* Sample React Native App
* https://github.com/facebook/react-native
*/
'use strict'
import React, {
AppRegistry,
Component,
StyleSheet,
Text,
TextInput,
View,
ScrollView,
DrawerLayoutAndroid
} from 'react-native'
class Dictionary extends Component {
constructor(props) {
super(props)
this.state = {
movies: 'Test'
}
}
render() {
const navigationView = (
<View style={{flex: 1, backgroundColor: '#fff'}}>
<Text style={{margin: 10, fontSize: 15, textAlign: 'left'}}>Im in the Drawer!</Text>
</View>
)
return (
<ScrollView>
<DrawerLayoutAndroid
drawerWidth={300}
drawerPosition={DrawerLayoutAndroid.positions.Left}
renderNavigationView={() => navigationView}>
<View style={{flex: 1, alignItems: 'center'}}>
<Text style={{margin: 10, fontSize: 15, textAlign: 'right'}}>Hello</Text>
<Text style={{margin: 10, fontSize: 15, textAlign: 'right'}}>World!</Text>
</View>
</DrawerLayoutAndroid>
<View style={styles.parent}>
<Text>
Type something in English:
</Text>
<TextInput/>
<Text style={styles.germanLabel}>
Movies: { this.state.movies }
</Text>
</View>
</ScrollView>
)
}
}
const styles = StyleSheet.create({
parent: {
padding: 16
},
germanLabel: {
marginTop: 20,
fontWeight: 'bold'
},
germanWord: {
marginTop: 15,
fontSize: 30,
fontStyle: 'italic'
}
})
AppRegistry.registerComponent('Dictionary', () => Dictionary)
However, the app doesn't display anything:
What could be the cause? (There aren't any error messages either, seems like everything compiled just fine.)
Try to make your DrawerLayoutAndroid as a root node. There is no information about this in docs, but helped me. Does this helps you?