What Is The Best Way To Have Typography Namespacing In React Native Apps - react-native

I'm working on large scale application where there are lots of font sizes are used. I want to set all type of typography style in the app which can easily reuse. Please suggest me how can i do that. Here is my code.
Is h6, bodyFont has meaningful namespacing if not please help me to define the typgraphy.
// global styles
'use strict';
import { StyleSheet } from "react-native";
import { colors, fontSize, font, fontWeight } from "./base";
const styles = StyleSheet.create({
// font color helepers styles
textPrimary: {
color: colors.primary
},
textMuted: {
color: colors.lightenGrey
},
// font helepers styles
bodyFont: {
color: colors.grey,
fontFamily: font
},
fontWeightBold: {
fontWeight: fontWeight.bold
},
fontWeightLight: {
fontWeight: fontWeight.light
},
fontSm: {
fontSize: fontSize.sm
},
fontXs: {
fontSize: fontSize.xs
},
fontMd: {
fontSize: fontSize.md
},
fontLg: {
fontSize: fontSize.lg
},
fontXl: {
fontSize: fontSize.xl
},
fontXxl: {
fontSize: fontSize.xxl
},
// text alignment helepers
textCenter: {
textAlign: "center"
},
// margin heleper styles
mb10: {
marginBottom: 10
},
mt30: {
marginTop: 30
},
mb30: {
marginBottom: 30
},
mr20: {
marginRight: 20
},
// typography
body: {
color: colors.grey,
fontFamily: font,
fontSize: fontSize.sm,
fontWeight: fontWeight.light,
marginBottom: 10
},
h6: {
color: colors.grey,
fontFamily: font,
fontSize: fontSize.sm,
fontWeight: fontWeight.bold,
marginBottom: 10
},
avatar: {
width: 60,
height: 60,
borderRadius: 30
}
});
export default styles;

I think that you have the right code. Now to use it just import that component where you want to use it.
For example:
import StylesText from 'yourpathhere';
.....
<Text style {StylesText.textPrimary}>{'Hello world'}</Text>

Related

TypeError: Cannot read property 'navigation' of undefined

I am using RN and would like to go back to the previous screen, but the debugging show: "C:\Users\DELL\Desktop\DGar\DGar\node_modules\react-native\Libraries\Core\ExceptionsManager.js:179 TypeError: Cannot read property 'navigation' of undefined". How can I do right now? Please help me!
import React, { Component } from 'react';
import {
Alert,
Dimensions,
ScrollView,
TextInput,
TouchableOpacity,
BackHandler,
} from 'react-native';
import { StyleSheet, View, Text, Image } from 'react-native';
const screenWidth = Dimensions.get('screen').width;
const screenHeight = Dimensions.get('screen').height;
import Icon from 'react-native-vector-icons/FontAwesome';
import ImagePicker from 'react-native-image-crop-picker';
import { NavigationUtils } from '../../navigations';
import { Navigation } from 'react-native-navigation';
export default class RecentReport extends Component {
constructor(props) {
super(props);
Navigation.events().bindComponent(this);
}
componentDidMount() {
BackHandler.addEventListener('hardwareBackPress', this.handleBackPress);
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.handleBackPress());
}
navigationButtonPressed({ buttonId }) {
switch (buttonId) {
case 'backPress': {
this.handleBackPress();
break;
}
}
}
handleBackPress = (props) => {
props.navigation.goBack(null);
return true;
};
render() {
return (
<View style={styles.container}>
<Text>Hi</Text>
</View>
);
}
}
RecentReport.options = {
topBar: {
animate: true,
elevation: 0,
title: {
text: 'Warning',
fontWeight: 'bold',
alignment: 'center',
},
leftButtons: [
{
id: 'backButton',
icon: require('../../assets/icons/back-button.png'),
color: '#5B7C56',
},
],
},
statusBar: {
backgroundColor: '#5B7C56',
},
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
imageItem: {
height: screenHeight / 4,
borderWidth: 1,
borderColor: '#5B7C56',
borderRadius: 20,
resizeMode: 'cover',
marginBottom: 10,
},
warningContainer: {
padding: 10,
},
spacingBetween: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
},
spacing: {
flexDirection: 'row',
alignItems: 'center',
},
contentContainer: {
padding: 10,
},
addWarningButton: {
height: 70,
width: 70,
borderRadius: 50,
borderColor: 'black',
backgroundColor: '#5B7C56',
borderWidth: 1,
alignItems: 'center',
justifyContent: 'space-around',
marginRight: 13,
marginTop: 13,
},
});

mediaQuery is not working in react-native

Media query is not working at some point.
I wrote media query twice already and when write third for the screen size "#media(max-device-width:360) and (max-device-height:640)" .it's not working.
I have just started coding and can't make it work. so any help will be great value to me.
import { MediaQueryStyleSheet } from "react-native-responsive";
...//code is here.
const styles = MediaQueryStyleSheet.create(
{
container: {
flex: 1
},
welcomeImage: {
width: null,
height: "83%",
opacity: 0.5,
position: "relative",
resizeMode: "cover",
alignSelf: "stretch",
backgroundColor: "#3B3B3B"
},
titleContainer: {
flexDirection: "column",
alignItems: "center",
position: "absolute",
},
logo: {
height: 92,
width: 252,
},
tagline: {
paddingTop: 13,
alignItems: "center",
fontSize: 20,
color: "#FBFBFB",
textAlign: "center",
fontFamily: "segoeUI"
},
},
{
"#media(max-device-width:374) and (max-device-height:811)": {
welcomeImage: {
height: "80%"
},
logo: {
width: 226.8,
height: 82.8,
},
}
},
{
"#media(min-device-width:375) and (max-device-height:811)": {
welcomeImage: {
height: "80%",
},
}
},
{
"#media(max-device-width:360) and (max-device-height:640)": {
tagline:{
fontSize:15,
},
}
},
);
//It doesn't show any error. but also not working.
Your problem in this line,
#media(max-device-width:360) and (max-device-height:640)
You are setting media query for max-width only.
Media query pattern should be min-width to max-height like,
#media (min-device-width : 360) and (max-device-height : 640)
Also make sure you have same pattern for all the media queries.
Ref

Reading the Latitude and longitude from Json and calculate driving directions

I am reading a json file to read the services provided in different cities. I am displaying the servics on a master page and when users click on the services, I redirect them to the page where the services are offered. I need to show them the driving directions to those services. Below is my services.Json file:
[
{
"id":1,
"ser": "Test Service",
"Location": "Orange County",
"Phone":"(777)-922-5151",
"SecondLoc": "Los Angeles",
"email":"test#test.com",
"sourceLat":"-33.8356372",
"sourceLong":"18.6947617",
"destLat":"-33.8600024",
"destLong":"18.697459"
}
]
Below is the screen shot of my service on the phone:
when I tap on Test Service. I am redirected to another page that shows the longitude , latitude of the source and destination and the cities where the service is offered. Below is the screen shot:
Below is my code to show the directions to the users:
/**
* Sample React Native App
* https://github.com/facebook/react-native
* #flow
*/
import React, { Component } from 'react';
import { Text, View, StyleSheet, Image, ScrollView, TouchableOpacity, Linking, Button } from 'react-native';
import { connect } from 'react-redux';
import { getTheme } from 'react-native-material-kit';
import EvilIcon from 'react-native-vector-icons/EvilIcons';
import MaterialIcon from 'react-native-vector-icons/MaterialIcons';
import SimpleIcon from 'react-native-vector-icons/SimpleLineIcons';
import * as actions from '../actions';
import getDirections from 'react-native-google-maps-directions'
const theme = getTheme();
const styles = StyleSheet.create({
card: {
marginTop: 10,
paddingBottom: 20,
marginBottom: 20,
borderColor: 'lightgrey',
borderWidth: 0.5,
},
title1: {
top: 10,
left: 80,
fontSize: 24,
},
title2: {
top: 35,
left: 82,
fontSize: 18,
},
image: {
flex: 0,
height: 100,
width: 333,
backgroundColor: 'transparent',
justifyContent: 'center',
alignItems: 'center',
},
closeIcon: {
position: 'absolute',
top: 5,
left: 295,
color: 'rgba(233,166,154,0.8)',
backgroundColor: 'rgba(255,255,255,0)',
},
icon: {
position: 'absolute',
top: 15,
left: 0,
color: 'white',
backgroundColor: 'rgba(255,255,255,0)',
},
textArea: {
flexDirection: 'row',
paddingLeft: 20,
paddingTop: 10,
width: 260,
},
textIcons: {
color: '#26a69a',
},
actionArea: {
paddingTop: 10,
flexDirection: 'row',
justifyContent: 'space-around',
alignItems: 'center',
},
title:{
justifyContent: 'center',
paddingTop: 10,
alignSelf:'center',
fontWeight: 'bold',
fontSize: 19,
},
SerContent:{
fontWeight: 'bold',
fontSize: 15,
paddingTop: 10,
alignSelf:'center',
},
underLineText: {
fontSize: 12,
textDecorationLine: 'underline',
color: 'red',
fontWeight: 'bold',
textAlign: 'center',
}
});
class ServiceDetail extends Component {
handleClick = (link) => {
Linking.canOpenURL(link).then(suppported => {
if (supported) {
Linking.openURL(link);
} else {
console.log('Don\'t know how to open URI: ' + link);
}
});
};
handleGetDirections = () => {
const data = {
source: {
latitude: -33.8356372,
longitude: 18.6947617
},
destination: {
latitude: -33.8600024,
longitude: 18.697459
},
params: [
{
key: "travelmode",
value: "driving" // may be "walking", "bicycling" or "transit" as well
},
{
key: "dir_action",
value: "navigate" // this instantly initializes navigation using the given travel mode
}
]
}
getDirections(data)
}
render() {
return (
<ScrollView showsVerticalScrollIndicator={false}>
<View style={[theme.cardStyle, styles.card]}>
<SimpleIcon name={'close'} size={30} style={styles.closeIcon}
onPress={() => this.props.noneSelected()} />
<Text style={styles.title}>{this.props.services.ser}</Text>
<Text style={styles.SerContent} >Service is available in the following locations:</Text>
<Text style={styles.SerContent}> {this.props.services.Location} </Text>
<Text style={styles.SerContent}> {this.props.services.sourceLat} </Text>
<Text style={styles.SerContent}> {this.props.services.sourceLong} </Text>
<Text style={styles.SerContent}> {this.props.services.destLat} </Text>
<Text style={styles.SerContent}> {this.props.services.destLong} </Text>
<TouchableOpacity onPress={this.handleGetDirections}>
<Text style={styles.underLineText}>directions</Text>
</TouchableOpacity>
<Text style={styles.SerContent}>{this.props.services.SecondLoc}</Text>
</View>
</ScrollView>
);
}
}
const mapStateToProps = state => {
return {
services: state.serviceSelected
};
};
export default connect(mapStateToProps, actions)(ServiceDetail);
I am not sure how to put these Longitude and Latitude data in that const data variable so that I don't have to hard code the Longitude and latitude like I did in my code. I can see the driving directions with the existing code, but Longitude and latitude are hard coded. I am very new to React Native. Right now when I click on driving directions, I see the below screen shot:
Any help will be highly appreciated.
I am not sure if I understand well your problem, if I didn't understand well please let me a comment.
So if you want to open navigation to a specific destination you can use this:
Android:
<TouchableOpacity onPress={() => Linking.openURL('google.navigation:q=55+57')}>
where q is the destination lat + long
IOS:
<TouchableOpacity onPress={() => Linking.openURL('maps://app?saddr=50+55&daddr=55+57')}>
where saddr is start address and daddr is destination address lat+long
To use it from JSON you should concatenate your URLs:
destUrl = 'google.navigation:q=' yourJson.lat + '+' + yourJson.long
<TouchableOpacity onPress={() => Linking.openURL(destUrl)}>

When we try to separate style files app doesn't render it shows spinner with background all time

image of CMD
Before doing it styles were on the same files. We cut all styles and pasted it on the separate file. Here is how it looks like.
import React, {Component} from "react";
import {Dimensions} from "react-native";
const win = Dimensions.get('window');
const styles={
content: {
justifyContent:'center'
},
img: {
flex: 1,
alignSelf: "stretch",
width: win.width,
height: win.height,
},
item:{
borderBottomColor: "#0dc49c"
},
icon:{
color: "#a4916c",
marginLeft: 10,
marginRight: 5
},
input:{
color: "#a4916c"
},
list:{
borderBottomWidth: 0,
borderTopWidth: 0,
borderBottomColor: "#a4916c",
},
contacticon: {
justifyContent: "center",
alignSelf: "center",
fontSize: 60,
fontWeight: "bold",
color: "#0dc49c",
marginBottom: 2,
},
contacttext: {
justifyContent: "center",
alignSelf: "center",
fontSize: 25,
color: "#0dc49c",
marginBottom: 180,
},
}
module.exports = styles;
When it was on the same files as components it was worked perfectly while because of duplicate styles we decided to separate them. What is wrong? How can it be fixed?
try using styles like this
import { StyleSheet } from "react-native";
const styles = StyleSheet.create({
content: {
justifyContent:'center'
},
});
module.exports = styles;
and import styles like this
import styles from "../styles/file

How to show text (YES/NO) inside a switch in react-native

I am new to react-native. In my app, I'm using a switch and changing the tint color to differentiate ON and OFF, but my actual requirement is to show "YES" or "NO" text inside the switch like below.
Here is my Code:
<Switch
onValueChange={this.change.bind(this)}
style={{marginBottom:10,width:90,marginRight:6,marginLeft:6}}
value={true}
thumbTintColor="#0000ff"
tintColor="#ff0000"
/>
Please give me suggestions to solve this issue, Any help much appreciated.
Finally I got the On off inside switch .......
install
npm install --save react-native-switch
import { Switch } from 'react-native-switch';
<Switch
value={true}
onValueChange={(val) => console.log(val)}
disabled={false}
activeText={'On'}
inActiveText={'Off'}
backgroundActive={'green'}
backgroundInactive={'gray'}
circleActiveColor={'#30a566'}
circleInActiveColor={'#000000'}/>
Refer this link...
https://github.com/shahen94/react-native-switch
I would start with something like this and then iterate and polish until it fulfills the requirements and looks good. This isn't a complete solution but should give you some ideas.
import React from 'react';
import { LayoutAnimation, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
const styles = StyleSheet.create({
container: {
width: 80,
height: 30,
backgroundColor: 'grey',
flexDirection: 'row',
overflow: 'visible',
borderRadius: 15,
shadowColor: 'black',
shadowOpacity: 1.0,
shadowOffset: {
width: -2,
height: 2,
},
},
circle: {
width: 34,
height: 34,
borderRadius: 17,
backgroundColor: 'white',
marginTop: -2,
shadowColor: 'black',
shadowOpacity: 1.0,
shadowOffset: {
width: 2,
height: 2,
},
},
activeContainer: {
backgroundColor: 'blue',
flexDirection: 'row-reverse',
},
label: {
alignSelf: 'center',
backgroundColor: 'transparent',
paddingHorizontal: 6,
fontWeight: 'bold',
},
});
class LabeledSwitch extends React.Component {
constructor(props) {
super(props);
this.state = {
value: props.value,
};
this.toggle = this.toggle.bind(this);
}
componentWillReceiveProps(nextProps) {
// update local state.value if props.value changes....
if (nextProps.value !== this.state.value) {
this.setState({ value: nextProps.value });
}
}
toggle() {
// define how we will use LayoutAnimation to give smooth transition between state change
LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);
const newValue = !this.state.value;
this.setState({
value: newValue,
});
// fire function if exists
if (typeof this.props.onValueChange === 'function') {
this.props.onValueChange(newValue);
}
}
render() {
const { value } = this.state;
return (
<TouchableOpacity onPress={this.toggle}>
<View style={[
styles.container,
value && styles.activeContainer]}
>
<View style={styles.circle} />
<Text style={styles.label}>
{ value ? 'YES' : 'NO' }
</Text>
</View>
</TouchableOpacity>
);
}
}
LabeledSwitch.propTypes = {
onValueChange: React.PropTypes.func,
value: React.PropTypes.bool,
};
LabeledSwitch.defaultProps = {
};
export default LabeledSwitch;