Applying styles in react native with styled components - react-native

I have a component, Logo, where I'm trying to apply a width and a height:
import styledNative from "styled-components/native";
import {Image, View} from "react-native"
import companyIcon from "../svg/companyIcon.svg";
const Logo = () => (
<Image source={{uri: companyIcon}} />;
);
const StyledLogo = styledNative(Logo)`
width: 48px;
height: 48px;
`;
const Header = () => {
return (
<View>
<StyledLogo />
</View>
);
};
This leaves us with an invisible logo, with a width of 0. Styled-components docs seems to suggest using a passed in className property (https://www.styled-components.com/docs/advanced#existing-css), however this seems to be for standard styled-components, not react-native / react-native-web implementation, because it's just not passed to my component. When I examine the passed props for Logo (by console logging them), there is a style object, but this doesn't appear to be anything I can use and there's not much mention of it in the styled component documentation:
style: Array(2)
0: 91
1: undefined
length: 2
So I'm not really sure what to do with it. How can components be styled by styled-components?

You aren't applying your styles to the image.
What is happening now, is that your Logo component is receiving those style-props, but it's not passing them through.
const Logo = (props) => ( // <-- containing style props
<Image source={{uri: companyIcon}} />;
);
So what you would want to do is to spread your Logos props over your Image, so it gets the data it needs.
const Logo = (props) => ( // <-- containing style props
<Image {...props} source={{uri: companyIcon}} />; // <-- styles now applied to Image
);
Or alternatively you can pass through just the style-props.
const Logo = (props) => ( // <-- containing style props
<Image source={{uri: companyIcon}} style={props.style}/>;
);
Edit:
It also appears you are passing invalid styles. React Native expects the values you pass in to not have units. As such, your styles should be width: 48; instead, dropping the ...px.

Related

Dimesnion from React/native not working properly on Android device

I am trying to create an Instagram like reel functionality in react-native app.
I want to display a video element on entire screen available space.
For the purpose of it I am using a FlatList.
This code doesn't work on every device.
'const HomeScreen = ({navigation}) => {
const dataArray=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19];
const renderItem=({item,index})=>{
return(
<View style={[{height:Dimesnions.get('window').height-bottomtabBarHeight,borderBottomColor:'black'},]}>
<Text>{item}</Text>
</View>
)
}
return (
<SafeAreaView style={styles.container}>
<StatusBar />
<FlatList
data={dataArray}
renderItem={renderItem}
pagingEnabled
decelerationRate={'fast'}
/>
</SafeAreaView>
)
}
export default HomeScreen
const styles = StyleSheet.create({
container:{
flex:1,
}
})`
work for me
import dimansion from react native
const {height,width} = dimansion.get('window')
const Myfun=()=>{
return(
<View style={{flex:1}}>
<View style={{height:height}}></View>
</View>
)
}
actually what you need to do is make a state variable and assign dimension's value in it and then in useEffect make a listener which would be triggered every time your device rotates or dimensions of device gets changed
example below:
const [dim, setDim] = useState(Dimensions.get('screen');
useEffect(() => {
const subscription = Dimensions.addEventListener(
'change',
({ screen}) => {
setDim({ screen});
},
);
return () => subscription?.remove(); });
you can use dim.height for height and dim.width for width in your desired component
PS. I have made a complete and comprehensive tutorials regarding Dimensions API if you want to check it out then link is below(Tutorial is in Urdu/Hindi)
https://www.youtube.com/watch?v=mISuyh_8-Cs&t=605s&ab_channel=LearnByDill
I think it is because of typo which you used Dimesnions instead of Dimensions. You can get height or width of device as below:
const ScreenWidth = Dimensions.get('window').width;
const ScreenHeight = Dimensions.get('window').height;

Why is my text not being rendered within text components?

I am new to React Native and i am having trouble with the following error message:
text string must be rendered within a <Text> component
This is my component:
import React from "react";
import { Text, StyleSheet, View, Button } from "react-native";
const HomeScreen = () => {
return (
<View>
<Text style={styles.text}>Hey!</Text>
<Button title='Go components demo'/>
</View>
);
};
const styles = StyleSheet.create({
text: {
fontSize: 30,
},
});
export default HomeScreen;
My strings are wrapped within a Text component and the error message persists. Any typo am i not seeing or doing anything wrong?
Your error is likely somewhere else in your app. one way to test this is to comment out the component inside of your App component or wherever your Homescreen component is being called. It's more likely that wherever you're mounting HomeScreen, there is extraneous text. Perhaps something you missed when deleting the boilerplate code.
Give some width and height to your view ,or try give a flex of 1 :
Hope it helps.
<View style = {{flex:1}}>
<Text style={styles.text}>Hey!</Text>
<Button title='Go components demo'/>
</View>
or
<View style = {{width:'100%',height:'100%'}}>
<Text style={styles.text}>Hey!</Text>
<Button title='Go components demo'/>
</View>

React Navigation custom navigator transitions

I'm looking to create a Stack Navigator that can handle animating specific elements between 2 screens. Fluid Transitions looked like a library I could use, but it doesn't support react-navigation 5.X. If there's a package that has this functionality for react-navigation v5, that would be great.
However, if there is no current package for v5, I'd like to extend the StackNavigator to handle this kind of functionality. I've been able to remove the default animations for the StackNavigator with something similar to the following (where transition is a bool taken in the options prop for the Stack.Screen:
const CustomTransitionStackNavigator = ({
initialRouteName,
children,
screenOptions,
...rest
}) => {
if (descriptors[state.routes[state.index].key].options.transition) {
return (
<View style={{ flex: 1 }}>
{descriptors[state.routes[state.index].key].render()}
</View>
);
}
return (
<StackView
{...rest}
descriptors={descriptors}
navigation={navigation}
state={state}
/>
);
};
I'd like to be able to use a Context (or some other method) of passing the transition progress to the scene's descendants in order to handle the animations. Is there some way to get the transition progress in v5? Or would this CustomTransitionStackNavigator need to manage that state? Thanks!
You can use CardAnimationContext or useCardAnimation (which is just a convenience wrapper for the first one) to get transition progress in a stack navigator.
For example:
import { useCardAnimation } from '#react-navigation/stack';
import React from 'react';
import { Animated } from 'react-native';
export const SomeScreen = () => {
const { current } = useCardAnimation();
return (
<Animated.View
style={{
width: 200,
height: 200,
backgroundColor: 'red',
transform: [{ scale: current.progress }],
}}
/>
);
};
This feature seems to be undocumented at the moment, but you can check TypeScript definitions to get some more information.

Programatically hiding and showing individual tabs in React Native Router Flux Tabbar

I have a tabbar in my app using React Native Router Flux. There are a couple use cases where hiding or showing specific tabs based on the current user would be very helpful. The main ones I have run into are:
AB testing new tabs to specific users
Showing a special admin tab to certain users with certain privileges
The react-native-router-flux library does not support any options to do this from what I can see. How can I achieve this functionality?
The default tabbar component in react-native-router-flux is just the component from the react-navigation-tabs library. You can import this component directly into your code, customize as needed, and then pass it to react-native-router-flux through the tabBarComponent prop (documented here).
I created a new component, which you should be able to copy directly and just change the logic for actually hiding the tabs based on your state:
import React from 'react'
import { BottomTabBar } from 'react-navigation-tabs'
import { View, TouchableWithoutFeedback } from 'react-native'
import { connect } from 'react-redux'
const HiddenView = () => <View style={{ display: 'none' }} />
const TouchableWithoutFeedbackWrapper = ({
onPress,
onLongPress,
testID,
accessibilityLabel,
...props
}) => (
<TouchableWithoutFeedback
onPress={onPress}
onLongPress={onLongPress}
testID={testID}
hitSlop={{
left: 15,
right: 15,
top: 5,
bottom: 5,
}}
accessibilityLabel={accessibilityLabel}
>
<View {...props} />
</TouchableWithoutFeedback>
)
const TabBarComponent = props => (
<BottomTabBar
{...props}
getButtonComponent={({ route }) => {
if (
(route.key === 'newTab' && !props.showNewTab) ||
(route.key === 'oldTab' && props.hideOldTab)
) {
return HiddenView
}
return TouchableWithoutFeedbackWrapper
}}
/>
)
export default connect(
state => ({ /* state that you need */ }),
{},
)(TabBarComponent)
And then simply imported and used that in my Tabs component:
<Tabs
key="main"
tabBarComponent={TabBarComponent} // the component defined above
...
Detailed look at where these things are getting passed to
Looking at the line of the source of react-native-router-flux, it is using createBottomTabNavigator from the react-navigation library, and passing no component if you do not pass a custom tabBarComponent. The createBottomTabNavigator method in react-navigation comes from this line of the library, and is actually defined in react-navigation-tabs. Now, we can here see in react-navigation-tabs that if no tabBarComponent has been passed, it simply uses BottomTabBar, also defined in react-navigation-tabs. This BottomTabBar, in turn, takes a custom tab button renderer through props, called getButtonComponent.

React Native <ScrollView> persistent scrollbar

After perusing the React Native Documentation I couldn't seem to find out how to make a <ScrollView> have a persistent scrollbar that doesn't fade out. How would I achieve that?
iOS
The underlying iOS native component, UIScrollView (technically, RCTEnhancedScrollView), doesn't support keeping the scroll indicators visible. For this reason, the React Native wrapper around it won't either.
There is a hack to get this working with the native component (see this answer for one approach). To accomplish this in React Native, you'd need to implement this hack on the native side, and then either create your own Native Module or fork React Native and modify their ScrollView component.
That said, the iOS Scroll View interface guidelines discourage this, so you may want to leave the indicators' behavior alone.
Android
A few approaches:
set <item name="android:overScrollMode">always</item>,
set android:fadeScrollbars="false" in XML, or
set ScrollView.setScrollbarFadingEnabled(false) in Java (e.g. in your custom native bridge code)
This is similarly discouraged as nonstandard UI unless you have a strong reason for it.
Adding answer since none of the above worked for me.
Android now has the persistentScrollbar props.
iOS does not support this. So I created a JS solution that can be used as follows:
<SBScrollView persistentScrollbar={true}>...</SBScrollView>
Basically, this functional component will use persistentScrollbar when on Android, while add a bar when we are on iOS. It is not smooth for now, but it is functional.
// #flow
import React, {useState} from 'react';
import {Platform, View, ScrollView} from 'react-native';
type Props = {|
persistentScrollbar?: boolean,
children?: React$Node,
|} & View.propTypes;
export default function SBScrollView({
persistentScrollbar = false,
children,
...other
}: Props) {
const [nativeEvent, setNativeEvent] = useState();
if (Platform.OS === 'android' || !persistentScrollbar) {
// Abdroid supports the persistentScrollbar
return (
<ScrollView persistentScrollbar={persistentScrollbar} {...other}>
{children}
</ScrollView>
);
}
const top = nativeEvent
? nativeEvent.contentOffset.y +
(nativeEvent.contentOffset.y / nativeEvent.contentSize.height) *
nativeEvent.layoutMeasurement.height
: 0;
// iOS does not support persistentScrollbar, so
// lets simulate it with a view.
return (
<ScrollView
scrollEventThrottle={5}
showsVerticalScrollIndicator={false}
onScroll={event => setNativeEvent(event.nativeEvent)}
{...other}>
{children}
<View
style={{
position: 'absolute',
top,
right: 4,
height: 200,
width: 4,
borderRadius: 20,
backgroundColor: 'gray',
}}
/>
</ScrollView>
);
}
I hope this can help others.
I was looking for a solution but I didn't find nothing, then I created a solution, I hope can help you with it.
I created a view View with height and width and put it over my scrollview, after that I used the Props of scrollview like onMomentumScrollBegin, onMomentumScrollEnd, onContentSizeChange and onScroll
after that I make a condition with a boolean variable, if this variable is false, the View is visible, if is false the View is hide, How do I active this variable? with the Prop onMomentumScrollBegin that detect when you use the scrollView and the same way to set the variable in false with onMomentumScrollEnd that detects when the scroll ends.
The Prop onContentSizeChange allows me to get the height and width of my scrollview, this values I used to calculate where would be set the scrollbar/scrollIndicator
and finally with the Prop onScroll I get the position.
the example:
<ScrollView
onMomentumScrollBegin={() => {this.setvarScrollState()}}
onMomentumScrollEnd={() => {this.setvarScrollStateRev()}}
scrollEventThrottle={5}
onContentSizeChange={(w, h) => this.state.hScroll = h}
showsVerticalScrollIndicator={false}
onScroll={event => { this.state.wScroll = event.nativeEvent.contentOffset.y }}
style={{ marginVertical: 15, marginHorizontal:15, width: this.state.measurements3.width}}>
{
Mydata.map((value, index) => {
return <TouchableOpacity>
<Text>{ value.MyDataItem }</Text>
</TouchableOpacity>
})
}
the functions:
setvarScrollState() {
this.setState({VarScroll: true});
}
setvarScrollStateRev() {
this.setState({VarScroll: false});
}
and the variable
this.state = {VarScroll: false}
Then my condition is
!this.state.VarScroll ?
<View
style = {{
marginTop: 200*(this.state.wScroll / this.state.hScroll),
marginLeft:338.5,
height: 35,
width: 2,
backgroundColor: 'grey',
position:'absolute'
}}
/>
: null
Why 200? because is the maximum value that my marginTop can set
Check the picture
Final note:
the scrollView have to be inside a View with the another View (scrollbar)
something like this
<View>
{/*---- ScrollBar and conditions----*/}
<View>
<View>
<ScrollView>
</ScrollView>
</View>