Does React Native have a font-relative size units? - react-native

I have to set a width of a View in term of the current font size. So I am wondering if React Native have an analogue of the Web's 1em?
I have found a solution with PixelRatio:
import { PixelRatio } from 'react-native';
// ...
<View style={{ width: 100 * PixelRatio.getFontScale() }} />
But it is too complicated and obscure, in my opinion.
Is there a more simple and clean way to solve the problem?
Thank you.

After a long search, I eventually found an answer in the React Native API Reference:
width sets the width of this component.
It works similarly to width in CSS, but in React Native you must use points or percentages. Ems and other units are not supported.
So the getFontScale() is the only possible solution.

Related

React native responsive units

I have been watching Rect Native tutorials on youtube and everyone uses units like padding:20 or fontSize:18 etc
Is that how you do in a professional app too? What is the ideal practice? Is this automatically responsive?
No, this is not automatically responsive. If we set padding:20, then the padding of that component stays on 20 no matter what phone we use. The same holds for font sizes, even though they are scaled depending on what pixel density we are dealing with.
A responsive design must be implemented by hand which could be done by using Dimensions as follows.
import { Dimensions } from 'react-native'
const width = Dimensions.get('window').width
const height = Dimensions.get('window').height
We can now use a different padding depending on the width of our device.
padding: width > 320 ? 20 : 15
When it comes to general layouting, then flexbox takes care of responsiveness, e.g. imagine that we have three elements on the screen with flexDirection: 'row' and we set flex:1 for all of them, then the available space will be divided equally between them no matter what our screen width is. The same applies for height.
It might be advised to create a separate Fonts file which holds font sizes and similar constants in a common place, so we only need to change them once.
import { Dimensions } from 'react-native'
const width = Dimensions.get('window').width
const height = Dimensions.get('window').height
export Fonts = {
h1: width > 320 ? 18 : 15,
h2: width > 320 ? 16 : 14,
...
}
The above takes care of responsive font sizes and we can use it in all other screens, e.g.
<Text style={{fontSize: Fonts.h1}}>I am a header</Text>

'borderBottomStyle : dashed' is not working in the react native. Can anyone suggest better way to do that?

BorderBottomStyle is not working in the React native and as well as styled-components. BorderStyle is working fine. But BorderBottomStyle-dashed is not working and getting Component Exception.
<LocationText>BORDERBOTTOMSTYLE</LocationText>
LocationText = styled.Text`
margin-left:2%;
font-family:metropolisRegular;
font-size:20px;
padding-left:2px;
border-bottom-color:rgba(0,0,0,0.3);
border-bottom-width:2px;
border-bottom-style:dashed;
`;
https://i.stack.imgur.com/GzzUU.png
Any Better idea to style only the border Bottom with dashed in React native??
In react-native, you can't style many components directly as this is not necessary. Often times the better approach is to put the component inside a container and then style the container.
If you're a beginner, then how you attach the styles to the "View" is something you can google and not important, but this is an example of just showing the one style attached inline.
<View style={{ border-bottom-style: "dashed"}}>
<LocationText>BORDERBOTTOMSTYLE</LocationText>
</View>

How do I handle scaling issues in a React Native app between tvOS and Android TV?

Native resolution for Apple TV seems to be 1920x1080 (as expected) but for Android TV / Fire TV it seems to be 961.5022957581195x540.8450413639423 (according to Dimensions.get('window')).
So, when I run my app on Apple TV everything looks fine. But when I run it on an Android TV nothing fits on the screen.
Is there a way to force the Android TV to shrink everything? Or do I have to create two different style sheets for the different devices to change font sizes and dimensions of all my components?
We use a different approach, on the base Application class for tv we add this
class TvApplication extends Application {
#Override
protected void attachBaseContext(Context base) {
Configuration configuration = new Configuration(base.getResources().getConfiguration());
configuration.densityDpi = configuration.densityDpi / 2;
Context newContext = base.createConfigurationContext(configuration);
super.attachBaseContext(newContext);
}
}
with this, we have consistent width & height when using dimensions, and we can use the same styling values on all platforms without doing any manipulation on the JS side.
it's not perfect, but it's more convenient when building for multiple platforms
Use Platform.OS to check for platform and use margin property in styles to get the content right on screen in android. This is normal behavior in android tv.
You have PixelRatio and Dimensions for this purpose in React Native. Along with this you need to use a RN module react-native-pixel-perfect, this keeps your app pixel perfect across all devices, quickly and easily
import {PixelRatio, Dimensions} from 'react-native';
import {create} from 'react-native-pixel-perfect';
let displayProps = {
width: PixelRatio.roundToNearestPixel(
Dimensions.get('window').width * PixelRatio.get(),
),
height: PixelRatio.roundToNearestPixel(
Dimensions.get('window').height * PixelRatio.get(),
),
};
let perfectSize = create(displayProps);
Now always pass your size in pixels to this method to get original device pixels based on the devices.
const styles = StyleSheet.create({
container: {
width: perfectSize(500),
height: perfectSize(300)
}
});
Your container will adapt to the devices correctly. Based on their screen resolution.
In case if you have a minimum height x width to support but some devices are less than the minimum screen resolution and you want to still achieve the same results in those devices. Then you can set the minimum screen resolution on this function like below.
let displayProps = {
width: PixelRatio.roundToNearestPixel(
Math.max(1920, Dimensions.get('window').width * PixelRatio.get()),
),
height: PixelRatio.roundToNearestPixel(
Math.max(1080, Dimensions.get('window').height * PixelRatio.get()),
),
};
So in my case if the screen resolution is less than 1920x1080 lets say 720p devices then this will help rendering the UI in 1920x1080.

Slower performance on iOS release than development

I've built a React Native iOS app which is fairly basic; it's a few screens which the user can click through to from a 'Home' component, and each one consists of basic components comprising solely Text/View/Image components.
In simulator the app is responsive and there aren't any JS console warnings, however when I do a release to my iPad (Air 2), there's a noticable lag between the home screen and certain other screens. These are notably the screens which have more images on.
I'm wondering if it's because I'm using larger images (the app was designed for the iPad Pro 2) and scaling the images down for use where I want them. The worst offender is a page which has a masonry-style grid of images. There's still only about 30 in a ScrollView there though. Once the component has been shown once the app is much more responsive.
I've already taken steps to optimise my components in terms of using extending PureComponent or using stateless functions wherever possible, and console logging shows me that the touchables are responding immediately, so the delay is definitely at the render time of the component.
N.B. All images are local (loaded via require('./path/to/file')), nothing is being loaded over the network.
Here's an example of the code that populates an array of items for display inside the ScrollView:
...
const items = mediaItems.map((item, index) => {
// scale desired width (1044 for video, 520 for images) based on designed width and device aspect ratio.
const imageWidth = item.video ? (1044/2732) * deviceWidth : (520/2732) * deviceWidth
return (
<TouchableHighlight key={index} onPress={() => onOpen(item)}>
<View style={[styles.gridImageView, { width: imageWidth }]}>
<Image style={styles.gridImage} source={item.image} />
</View>
</TouchableHighlight>
)
});
...
and the styles for the gridImageView and gridImage are as follows:
...
gridImageView: {
height: (460/2732) * width,
margin: (2/2732) * width,
position: 'relative'
},
gridImage: {
resizeMode: 'cover',
width: null,
height: null,
flex: 1,
alignItems: 'center',
justifyContent: 'center'
},
...
So my question is kind of multi-layered:
What is the best practice with regards to ensuring the component appears quickly?
Should I not be setting a width/height on the image itself at all?
Should I be doing some kind of pre-loading of the images in the sizes I want before I let the user begin to navigate around the app?
Should I be using JPG instead of PNG images?
Is there another trick I'm missing?
Should I not be setting a width/height on the image itself at all
You have to set a width and height. If you don‘t do so, your image won‘t display
Should I be doing some kind of pre-loading of the images in the sizes I want before I let the user begin to navigate around the app?
It is a good idea to downlod images beforehand. Huge images need a lot of performance. Probably your issues are gone, if you resize your images before displaying them. Therefore you could use react native image resizer
Should I be using JPG instead of PNG images?
You should use JPGs, because they provide a higher compression rate.

How to make React-Native "scrollTo" behave identically on Android than on iOS when ScrollView is small

Consider this simple ScrollView.
On iOS, clicking on the text will but the text to the top because scrollTo({ y: 250 }) scrolls even if end of scrollView is reached.
On Android, the text doesn't move.
How to get on Android the same behavior we have on iOS?
You can work around this by adding padding to the contentContainerStyle of the ScrollView. A good starting point would be to add padding equal to the height of the device's screen.
import { Dimensions } from 'react-native';
const ANDROID_SCREEN_HEIGHT_PADDING = Dimensions.get('window').height;
then, when rendering:
<ScrollView
contentContainerStyle={{paddingBottom: ANDROID_SCREEN_HEIGHT_PADDING}}>
...
</ScrollView>
You could use this for necessary extra Android padding in every direction. If you are using horizontal={true}, for example, you could add padding equal to the width of the screen and add it to the paddingLeft style property to get the intended scrolling behavior on Android.
This behavior is due to the underlying implementation of ScrollView on Android in React-Native. See also:
React native Android ScrollView scrollTo not working