React Native Web/Expo: How to emulate focus-visible on a Pressable? - reactjs

I'm trying to manually recreate the focus-visible behaviour on a Pressable component in React Native Web. This artificial behaviour will be such that when you click the Pressable component, it will have one set of styles, but if you focus it with tab on the keyboard, it will have a different set of styles.
Thankfully Pressable on react-native-web has pressed, hovered, and focused variants built in. But the issue is, whenever Pressable is pressed, focused remains true thereafter.
Is there someway to make focused not true after being pressed?
Alternatively, is there some other trick to artificually recreate the focus-visible behaviour?
<Pressable
style={({pressed, hovered, focused}) => [
{
backgroundColor: pressed ? "orange" : hovered ? "green" : focused ? "red" : "lightgray",
padding: 20
}
]}>
{
({pressed, hovered, focused}) => (
<Text>
{pressed ? "Pressed" : hovered ? "Hovered" : focused ? "Focused" : "Default"}
</Text>
)
}
</Pressable>
Here is the Expo Snack. Not sure why hover doesn't work on this snack, but upon clicking, it stays red (focused). Any way to make it back to gray after clicking?

Figured it out.
Based on what you want, you need to use a combination of outline styles and box shadow.
return (
<Pressable style={(state) => [styles.default, state.focused && styles.focusOutline]}>
<Text style={{fontWeight: "bold"}}>
Outline styles only
</Text>
<Text>Tab: Colored offset outline</Text>
<Text>Press: n/a</Text>
</Pressable>
)
// styles
const styles = StyleSheet.create({
default: {
paddingHorizontal: 15,
paddingVertical: 10,
backgroundColor: "powderblue",
alignItems: "center",
borderRadius: 20,
},
focusOutline: {
outlineStyle: "solid",
outlineWidth: 4,
outlineColor: "skyblue",
outlineOffset: 2,
}
});
Expo Snack

Related

Text imbrication and style in React Native

I want to change style in part of Text in React Native.
I tried this :
<Text style={styles.parent}>
Dernier message : <Text style={[styles.children, {
color: 'red',
paddingLeft: 10,
borderWidth: 5,
borderColor: 'black',
}]}>Coucou</Text>
</Text>
const styles = StyleSheet.create({
parent: {
backgroundColor: 'yellow',
},
children: {
backgroundColor: 'blue',
},
})
Parent background color is changed - good
Children color and background color is changed - good
Children padding left and border is not changed
Can you help me ? Thanks
The <Text> element is special as far as layout is concerned. From the docs: "everything inside is no longer using the flexbox layout but using text layout. This means that elements inside of a <Text> are no longer rectangles, but wrap when they see the end of the line."
To achieve what you seem to be looking for, it's probably advisable to use a wrapping<View> with two inner <Text>s.
PFB the expo snack link. Hope it helps
Expo link

Detect active screen in React Native

Sorry for my bad English. I have built a navigation bar without using Tab Navigation from React Navigation, everything works fine except when I try to set an 'active' icon, I have handled it with states but the state restarts when I navigate to another window and render the bar again navigation.
I think I have complicated it a bit, but I need to capture the active screen to pass it as status and change the color of the icon to 'active' and the others disabled. I have tried with Detect active screen and onDidFocus but I only received information about the transition, I require the name or id of the screen.
I leave my code (this component is exported to each page where I wish to have the navigation bar). Please, the idea is to not use Tab Navigation from React Native Navigation.
export default class Navbar extends Component {
/** Navigation functions by clicking on the icon (image) */
_onPressHome() {
this.props.navigation.navigate('Main');
}
_onPressSearch() {
this.props.navigation.navigate('Main');
}
render() {
const { height, width } = Dimensions.get('window');
return (
<View style={{ flexDirection: 'row', height: height * .1, justifyContent: 'space-between', padding: height * .02 }}>
/** Icon section go Home screen */
<View style={{ height: height * .06, alignItems: 'center' }}>
<TouchableOpacity
onPress={() => this._onPressHome()}
style={styles.iconStyle}>
<Image
source={HOME_ICON}
style={{ width: height * .04, height: height * .04, }} />
<Text style={[styles.footerText, { color: this.state.colorA }]}>Inicio</Text>
</TouchableOpacity>
</View>
/** Icon section go Search screen */
<View style={{ height: height * .06, alignItems: 'center' }} >
<TouchableOpacity
onPress={() => this._onPressSearch()}
style={styles.iconStyle}>
<Image
source={SEARCH_ICON}
style={{ width: height * .04, height: height * .04, opacity: .6 }} />
<Text style={[styles.footerText, { color: this.state.colorB }]}>Inicio</Text>
</TouchableOpacity>
</View>
</View>
)
}
}
For the navigation I used createStackNavigator and also
const drawerNavigatorConfig = {
contentComponent: props => <CustomDrawerContentComponent {...props}
/>,
};
const AppDrawer = createDrawerNavigator(drawerRouteConfig,
drawerNavigatorConfig);
I do not know if createDrawerNavigator is interfering with something, I read that it generates additional keys. Please help me with this.
import { useIsFocused } from '#react-navigation/native';
function Profile() {
const isFocused = useIsFocused();
return <Text>{isFocused ? 'focused' : 'unfocused'}</Text>;
}
check documentation
https://reactnavigation.org/docs/use-is-focused/
You can use this inViewPort library for checking the view port of the user. This is how you can user the library
render(){
<InViewPort onChange={(isVisible) => this.checkVisible(isVisible)}>
<View style={{flex: 1, height: 200, backgroundColor: 'blue'}}>
<Text style={{color: 'white'}}>View is visible? {this.state.visible </Text>
</View>
</InViewPort>
}

Detect tap on the outside of the View in react native

How to detect tap on the outside of the View(View is a small one width and height are 200). For example, I have a custom View(which is like a modal) and it's visibility is controlled by state. But when clicking outside of it nothing is changed because there is no setState done for that, I need to catch users tap everywhere except inside the modal. How is that possible in React Native?
use a TouchableOpacity around your modal and check it's onPress. Look at this example.
const { opacity, open, scale, children,offset } = this.state;
let containerStyles = [ styles.absolute, styles.container, this.props.containerStyle ];
let backStyle= { flex: 1, opacity, backgroundColor: this.props.overlayBackground };
<View
pointerEvents={open ? 'auto' : 'none'}
style={containerStyles}>
<TouchableOpacity
style={styles.absolute}
disabled={!this.props.closeOnTouchOutside}
onPress={this.close.bind(this)}
activeOpacity={0.75}>
<Animated.View style={backStyle}/>
</TouchableOpacity>
<Animated.View>
{children}
</Animated.View>
</View>
const styles = StyleSheet.create({
absolute: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: 'transparent'
},
container: {
justifyContent: 'center',
elevation: 10,
}
});
<View
onStartShouldSetResponder={evt => {
evt.persist();
if (this.childrenIds && this.childrenIds.length) {
if (this.childrenIds.includes(evt.target)) {
return;
}
console.log('Tapped outside');
}
}}
>
// popover view - we want the user to be able to tap inside here
<View ref={component => {
this.childrenIds = component._children[0]._children.map(el => el._nativeTag)
}}>
<View>
<Text>Option 1</Text>
<Text>Option 2</Text>
</View>
</View>
// other view - we want the popover to close when this view is tapped
<View>
<Text>
Tapping in this view will trigger the console log, but tapping inside the
view above will not.
</Text>
</View>
</View>
https://www.jaygould.co.uk/2019-05-09-detecting-tap-outside-element-react-native/
I found these solution here, hope it helps
Wrap your view in TouchableOpacity/TouchableHighlight and add onPress Handler so that you can detect the touch outside your view.
Something like :
<TouchableOpacity onPress={() => {console.log('Touch outside view is detected')} }>
<View> Your View Goes Here </View>
</TouchableOpacity>

React Native ScrollView/FlatList not scrolling

I have a list of data that I want to place inside a FlatList (i.e. ScrollView) and whenever I try to scroll down to view more of the list, the ScrollView just bounces back up to the top of the list so I cannot ever see the bottom of the list.
I am using Expo and the strange thing is that if I just create a new project or copy/paste some code into Snack then the scrolling works just fine. It is only in my current project that I cannot get the list to scroll. I have even gone into the main.js file and just pasted my example code in there and the issue still persists.
My example code is located here: https://snack.expo.io/ryDPtO5-b
I have pasted this exact code into my project and it is not working as expected.
Versions:
RN 0.44 /
Expo SDK 17.0.0 /
React: 16.0.0-alpha.6
My actual use case for my project involves placing a FlatList component at the bottom-third of the screen to show a list of jobs. This is where I discovered the error and when I started to try and debug the issue. In my project I have a parent View with a style of {flex: 1 with a child of List that contains the FlatList... List comes from react-native-elements
EDIT
Here is the code I am actually trying to use:
<View style={styles.container}>
<View style={containerStyles.headerContainerStyle}>
<Text style={[textStyles.h2, { textAlign: "center" }]}>
Territory: {this.props.currentTerritory}
</Text>
</View>
<View style={styles.mapContainer}>
<MapView
provider="google"
onRegionChangeComplete={this.onRegionChangeComplete}
region={this.state.region}
style={{ flex: 1 }}
>
{this.renderMapMarkers()}
</MapView>
</View>
<Badge containerStyle={styles.badgeStyle}>
<Text>Orders Remaining: {this.props.jobsList.length}</Text>
</Badge>
<List containerStyle={{ flex: 1 }}>
<FlatList
data={this.props.jobsList}
keyExtractor={item => item.id}
renderItem={this.renderJobs}
removeClippedSubviews={false}
/>
</List>
</View>;
And all my styles
const styles = StyleSheet.create({
container: {
flex: 1,
},
mapContainer: {
height: 300,
},
badgeStyle: {
backgroundColor: 'green',
alignSelf: 'center',
marginTop: 15,
width: 300,
height: 35,
},
});
and lastly, my renderItem function:
renderJobs = ({ item }) => {
const { fullAddress, pickupTime } = item;
return (
<ListItem
containerStyle={
item.status === "active" && { backgroundColor: "#7fbf7f" }
}
title={fullAddress}
titleStyle={{ fontSize: 14 }}
subtitle={pickupTime}
subtitleStyle={{ fontSize: 12, color: "black" }}
onPress={() =>
this.props.navigation.navigate("jobActions", { job: item })
}
/>
);
};
I was able to solve this problem.
The Solution is to use flatlist component <View style={{flex:1}}> after renderRow return component <View style={{flex:1}}>
I am confused - are you using a FlatList or a ScrollView - these two elements have completely different lifecycle events (a FlatList requires you to define how individual rows will render and their keys, whereas a ScrollView expects the children to be rendered inline with the component).
Regardless, I think the issue is in your structure, it sounds like the List element requires a height attribute as well ({flex: 1}) as the absolute parent is filling it's space, but the List component is not having a pre-defined height.
So after debugging this a bit more today and I ended up just creating a brand new Expo project and copy/pasting all my source code into the new project, changing my Github project name to the new name, and setting the remote origin to my github repo (the one where I changed the name) on my new local project.
For some reason there appeared to be a problem with the Expo project. It almost seemed like the actual NAME of the project was causing issues as I attempted to change the NEW project's name to that of the original project, but it didn't work. It only worked when doing a brand new project, but using the exact same source code.

React-Native Button style not work

Import_this
import {AppRegistry, Text, View, Button, StyleSheet} from 'react-native';
This my React Button code But style not working Hare ...
<Button
onPress={this.onPress.bind(this)}
title={"Go Back"}
style={{color: 'red', marginTop: 10, padding: 10}}
/>
Also I was try by this code
<Button
containerStyle={{padding:10, height:45, overflow:'hidden',
borderRadius:4, backgroundColor: 'white'}}
style={{fontSize: 20, color: 'green'}}
onPress={this.onPress.bind(this)} title={"Go Back"}
> Press me!
</Button>
Update Question:
Also I was try by This way..
<Button
onPress={this.onPress.bind(this)}
title={"Go Back"}
style={styles.buttonStyle}
>ku ka</Button>
Style
const styles = StyleSheet.create({
buttonStyle: {
color: 'red',
marginTop: 20,
padding: 20,
backgroundColor: 'green'
}
});
But No out put:
Screenshot of my phone:-
The React Native Button is very limited in what you can do, see; Button
It does not have a style prop, and you don't set text the "web-way" like <Button>txt</Button> but via the title property <Button title="txt" />
If you want to have more control over the appearance you should use one of the TouchableXXXX' components like TouchableOpacity
They are really easy to use :-)
I had an issue with margin and padding with a Button. I added Button inside a View component and apply your properties to the View.
<View style={{margin:10}}>
<Button
title="Decrypt Data"
color="orange"
accessibilityLabel="Tap to Decrypt Data"
onPress={() => {
Alert.alert('You tapped the Decrypt button!');
}}
/>
</View>
React Native buttons are very limited in the option they provide.You can use TouchableHighlight or TouchableOpacity by styling these element and wrapping your buttons with it like this
<TouchableHighlight
style ={{
height: 40,
width:160,
borderRadius:10,
backgroundColor : "yellow",
marginLeft :50,
marginRight:50,
marginTop :20
}}>
<Button onPress={this._onPressButton}
title="SAVE"
accessibilityLabel="Learn more about this button"
/>
</TouchableHighlight>
You can also use react library for customised button .One nice library is react-native-button (https://www.npmjs.com/package/react-native-button)
If you do not want to create your own button component, a quick and dirty solution is to wrap the button in a view, which allows you to at least apply layout styling.
For example this would create a row of buttons:
<View style={{flexDirection: 'row'}}>
<View style={{flex:1 , marginRight:10}} >
<Button title="Save" onPress={() => {}}></Button>
</View>
<View style={{flex:1}} >
<Button title="Cancel" onPress={() => {}}></Button>
</View>
</View>
Instead of using button . you can use Text in react native and then make in touchable
<TouchableOpacity onPress={this._onPressButton}>
<Text style = {'your custome style'}>
button name
</Text>
</TouchableOpacity >
Style in button will not work, You have to give style to the view.
<View style={styles.styleLoginBtn}>
<Button
color="orange" //button color
onPress={this.onPressButton}
title="Login"
/>
</View>
Give this style to view
const styles = StyleSheet.create({
styleLoginBtn: {
marginTop: 30,
marginLeft: 50,
marginRight: 50,
borderWidth: 2,
borderRadius: 20,
borderColor: "black", //button background/border color
overflow: "hidden",
marginBottom: 10,
},
});
Only learning myself, but wrapping in a View may allow you to add styles around the button.
const Stack = StackNavigator({
Home: {
screen: HomeView,
navigationOptions: {
title: 'Home View'
}
},
CoolView: {
screen: CoolView,
navigationOptions: ({navigation}) => ({
title: 'Cool View',
headerRight: (<View style={{marginRight: 16}}><Button
title="Cool"
onPress={() => alert('cool')}
/></View>
)
})
}
})
Try This one
<TouchableOpacity onPress={() => this._onPressAppoimentButton()} style={styles.Btn}>
<Button title="Order Online" style={styles.Btn} > </Button>
</TouchableOpacity>
You can use Pressable with Text instead of button.
import { StyleSheet, Text, View, Pressable } from 'react-native';
<Pressable style={styles.button} onPress = {() => console.log("button pressed")}>
<Text style={styles.text}>Press me</Text>
</Pressable>
Example Style:
const styles = StyleSheet.create({
button: {
alignItems: 'center',
justifyContent: 'center',
paddingVertical: 12,
paddingHorizontal: 32,
borderRadius: 4,
elevation: 3,
backgroundColor: 'red'
},
text: {
fontSize: 16,
lineHeight: 21,
fontWeight: 'bold',
letterSpacing: 0.25,
color: 'white',
},
});
We can use buttonStyle prop now.
https://react-native-training.github.io/react-native-elements/docs/button.html#buttonstyle
React-native button is very limited, it won't allow styling. use react native elements button or create custom button
button styles does'nt work in react-native, to style your button in react-native easy way is to put it inside the View block like this:
<View
style={styles.buttonStyle}>
<Button
title={"Sign Up"}
color={"#F31801"}/>
</View>
style.buttonStyle be like this:
style.buttonStyle{
marginTop:30,
marginLeft:50,
marginRight:50,
borderWidth:2,
borderRadius:20,
borderColor:'#F31801',
overflow:"hidden",
marginBottom:10,
}
, it will make you able to use designs with buttons
As the answer by #plaul mentions TouchableOpacity, here is an example of how you can use that;
<TouchableOpacity
style={someStyles}
onPress={doSomething}
>
<Text>Press Here</Text>
</TouchableOpacity>
SUGGESTION:
I will recommend using react-native-paper components as they are modified and can be modified much more than react-native components.
To install;
npm install react-native-paper
Then you can simply import them and use.
More details here Here
Wrap the button component inside a view component and change the styles of the view component, it should work. Please refer to the snippet below
<View style={{width: 150, alignSelf: 'center'}}>
<Button onPress={demoFunction} title="clickMe!!" />
</View>
I know this is necro-posting, but I found a real easy way to just add the margin-top and margin-bottom to the button itself without having to build anything else.
When you create the styles, whether inline or by creating an object to pass, you can do this:
var buttonStyle = {
marginTop: "1px",
marginBottom: "1px"
}
It seems that adding the quotes around the value makes it work. I don't know if this is because it's a later version of React versus what was posted two years ago, but I know that it works now.

Resources