Putting one Component in front of another (higher zIndex) dynamically - react-native

So there are two components sort of like this:
<View>
<Component1 />
<Component2 />
</View>
Both, Component1 & Component2 can be dragged and dropped within the View. By default, Component2 will render above the Component1 (since it is above in the stack). I want to make it so that whenever I press Component1 (for drag and drop) it dynamically comes infront of Component2 (Higher zIndex) and if I press Component1 and drag and drop, Component1 comes infront of Component2.
Anyone has any idea on how this can be done?
Edit 1:
I'm using zIndex, but for some reason it's working on iOS but not working on Android. Here's the basic code:
<View>
<View style={{position:'absolute',zIndex:2,backgroundColor:'red',width:500,height:500}}/>
<View style={{position:'absolute',zIndex:1,backgroundColor:'green',width:500,height:500,marginLeft:50}}/>
</View>

Setting dynamic zIndex for child components looks like the way to go. (zIndex on docs)
I would store the zIndexes of each child in the state. And I would wrap Component1 and Component2 with a touchable component if they are not already. When dragging & dropping starts, I'd update the zIndex stored in the state so that the required child would have higher zIndex.
Since I don't exactly know how you structured the components and their layouts, I am unable to provide a example code piece.
EDIT
Workaround for missing zIndex implementation on Android
I'd go something like this, if nothing else works:
import React from 'react';
import {
StyleSheet,
View,
} from 'react-native';
const style = StyleSheet.create({
wrapper: {
flex: 1,
position: 'relative',
},
child: {
position: 'absolute',
width: 500,
height: 500,
},
});
class MyComponent extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
reverseOrderOfChildren: false,
};
}
render() {
const firstChild = <View style={[style.child, {backgroundColor: 'red'}]} />
const secondChild = <View style={[style.child, {backgroundColor: 'green'}]} />
if (this.state.reverseOrderOfChildren) {
return (
<View style={style.wrapper}>
{secondChild}
{firstChild}
</View>
);
}
return (
<View style={style.wrapper}>
{firstChild}
{secondChild}
</View>
);
}
}

Related

swiping on react-native-snap-carousel is not working as expected

I am trying to use react-native-snap-carousel but however, the swiping effect is not working as expected - it is often difficult to swipe left and right, it requires user to swipe harder to move to another picture (as illustrated in the link below).
Swiping issue with React Native Snap Carousel
I am not able to find any documented soluton but I found one possible prop - swipeThreshold. I try various value, but still the issue persist.
Does anyone know the solution to this?
I suggest you to use react-native-image-slider.
it's flexible and easy to use.
https://www.npmjs.com/package/react-native-image-slider
I made a component named slider.js:
import React, { Component } from 'react';
import {
View,
StyleSheet,
Image,
} from 'react-native';
import ImageSlider from 'react-native-image-slider';
export default class Slider extends Component {
render() {
return (
<ImageSlider
loop
autoPlayWithInterval={3000}
images={this.props.dataSource}
customSlide={({ index, item, style, width }) => (
<View key={index} style={[style, styles.customSlide]}>
<Image source={{ uri: item }} style={styles.customImage} />
</View>
)}
/>
);
}
}
const styles = StyleSheet.create({
customImage: {
height: 180,
marginRight: 20,
marginLeft: 20,
borderWidth: 1,
borderRadius: 10,
marginTop: 8,
},
customSlide: {
backgroundColor: '#eee',
},
});
you can add this to your project and use it wherever you need it like this:
import Slider from '../component/slider';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
images: [
'https://placeimg.com/640/480/nature',
'https://placeimg.com/640/480/tech',
'https://placeimg.com/640/480/animals',
'https://placeimg.com/640/480/tech',
],
}
render() {
return (
<View style={{flex: 1, backgroundColor: '#eee'}}>
<Slider dataSource={this.state.images} />
</View>
);
}
}

{flex:1} is not working properly in React Native

If I understand correctly -- making the outermost container as "flex: 1" should let the component span the whole screen.
However, the code I wrote is not working properly.
import React from 'react';
import { View, Text } from 'react-native';
export default function test() {
return (
<View style={{ flex: 1, borderColor: 'red', borderWidth: 5 }}>
<Text>test</Text>
</View>
);
}
The simulator screenshot is here
Can anyone please point out where I did wrong?
Thank a lot!
Where are you calling this component? Yes, the flex will expand, but it is dependent on that parent component container. It looks like your parent is the one restricting this component.
Ensure the parent is also flexing and filling the content. Here is some more details around flex layout: https://facebook.github.io/react-native/docs/flexbox
Change your code to import the Component as a class:
import React from 'react';
import { View, Text } from 'react-native';
export default test extends React.Component {
render() {
return (
<View style={{ flex: 1, borderColor: 'red', borderWidth: 5 }}>
<Text>test</Text>
</View>
);
}
}

Create a reusable React Native Modal Component

I'm going back to basics with React Native, as I feel overwhelmed. I have been looking for an implementation of a reusable modal component. I'm looking for examples of a reusable Modal component in RN? Thanks in advance
You can find many examples of this on StackOverflow. Still, if you need example I can help you with one example. You have mentioned modal component in your question, right?
Your component will look like this with props. let the name be ModalComponent for this file.
render() {
const { isVisible, message, textValue } = this.props;
return (
<Modal
animationType="slide"
transparent={false}
isVisible={isVisible}
backdropColor={"white"}
style={{ margin: 0 }}
onModalHide={() => {}}>
<View>
<Text>textValue</Text>
<Text>message</Text>
</View>
</Modal>
);
}
so now in your js file you need to import this modalComponent and after that, you need to write as
<ModalComponent
isVisible={true}
textValue={'hi there'}
message={'trying to make a basic component modal'}/>
Hope this will help for you
EDIT:
Create seperate components that you want to render inside modal. for Ex: component1.js, component2.js, component3.js with props
component1.js:
render(){
const { textVal, message } = this.props
return (
<View>
<Text>{textVal}</Text>
<Text>{message}</Text>
</View>
)
}
now in ModalComponent
render() {
const { first, second, third, isVisible, component1Text, component1Message } = this.props;
<Modal
animationType="slide"
transparent={false}
isVisible={isVisible}
backdropColor={"white"}
style={{ margin: 0 }}
onModalHide={() => {}}>
<View>
{first && <component1
textValue= component1Text
message= component1Message />}
{second && <Component2 />}
{third && <Component2 />}
</View>
</Modal>
In this way, you can achieve it within the single modal.
You will make a component like this giving the parent component all the liberty to change it through props.
render() {
const { isVisible, message, textValue, animationType, backDropColor, style, onModalHide, children } = this.props;
return (
<Modal
animationType= {animationType || 'slide'}
transparent={transparent || false}
isVisible={isVisible || false}
backdropColor={backdropColor || "white"}
style={[modalStyle, style]}
onModalHide={onModalHide}>
{children}
</Modal>
);
}
Then in your parent component, you need to import this component like this:
import ModalComponent from '../ModalComponent'; //path to your component
<ModalComponent isVisible={true}>
<View>
//any view you want to be rendered in the modal
</View>
</ModalComponent>
I had a lot of troubles using react-native modal, sometimes i started the app and could not close it even when i set the isVisible prop to false, it is even worst on IOs, i did a research and these packages are not being maintained properly.
You will save a lot of time by using a top-level navigator like is recommended in the modal docs: https://facebook.github.io/react-native/docs/modal.
I tried https://github.com/react-native-community/react-native-modal but had the same problems because its an extension of the original react-native modal.
I suggest you to use the react-navigation modal as described here: https://reactnavigation.org/docs/en/modal.html#docsNav
You can refer the following code to write Modal component once and use multiple times.
Write once:
import React, { Component } from 'react';
import { View, Text, Button, Modal, ScrollView, } from 'react-native';
export class MyOwnModal extends Component {
constructor(props) {
super(props);
this.state = {
}
render() {
return(
<Modal
key={this.props.modalKey}
transparent={this.props.istransparent !== undefined ? true : false}
visible={this.props.visible}
onRequestClose={this.props.onRequestClose}>
<View style={{
//your styles for modal here. Example:
marginHorizontal: width(10), marginVertical: '30%',
height: '40%', borderColor: 'rgba(0,0,0,0.38)', padding: 5,
alignItems: 'center',
backgroundColor: '#fff', elevation: 5, shadowRadius: 20, shadowOffset: { width: 3, height: 3 }
}}>
<ScrollView contentContainerStyle={{ flex: 1 }}>
{this.props.children}
</ScrollView>
</View>
</Modal>
);
}
}
Now,
You can call your Modal like following example: (By doing this, you avoid re-writing the Modal and its outer styles everytime!)
Example
<MyOwnModal modalKey={"01"} visible={true} onRequestClose={() =>
this.anyFunction()} istransparent = {true}>
<View>
// create your own view here!
</View>
</MyOwnModal>
Note: If you are in using different files don't forget to import , and also you can pass the styles as props.
(You can create/customise props too based on your requirement)
Hope this saves your time.
Happy coding!
I am a contributor of react-native-use-modal.
This is an example of creating a reusable modal in a general way and using react-native-use-modal: https://github.com/zeallat/creating-reusable-react-native-alert-modal-examples
With react-native-use-modal, you can make reusable modal more easily.
This is a comparison article with the general method: https://zeallat94.medium.com/creating-a-reusable-reactnative-alert-modal-db5cbe7e5c2b

React Native UI Component Wrap in Touchable

I'm trying to detect when a user presses on a custom UI component I have written (it displays a video feed). I've tried using all the touchable components, and would ideally want to use the TouchableWithoutFeedback component, but none of them detect presses on my component. Additionally, when I select my component with the inspector, I get the error Expected to find at least one React renderer but I'm not sure how to set up my component correctly to have a renderer.
The native UI component:
public class DroneVideoFeedManager extends SimpleViewManager<DroneVideoFeed> {
#Override
public String getName() {
return "DroneLiveVideo";
}
#Override
public DroneVideoFeed createViewInstance(ThemedReactContext context) {
return new DroneVideoFeed(context, null);
}
}
My UI component Javascript wrapper is as follows:
import PropTypes from 'prop-types';
import {
requireNativeComponent,
ViewPropTypes,
} from 'react-native';
const iface = {
name: 'DroneLiveVideo',
propTypes: {
resizeMode: PropTypes.oneOf(['cover', 'contain', 'stretch']),
...ViewPropTypes, // include the default view properties
},
};
module.exports = requireNativeComponent('DroneLiveVideo', iface);
And my attempt to detect a press:
<TouchableWithoutFeedback
onPress={() => console.log('pressed!')}
>
<DroneLiveView
style={{
width: '100%',
height: '100%',
}}
/>
</TouchableWithoutFeedback>
This is the first time I have attempted to implement a native UI component in React Native, so apologies in advance if I am doing things incorrectly.
I found a solution, it's perhaps a little convoluted and not the best way of doing things but it works!
I changed my javascript wrapper to return a view with my native UI component, and another view above it (using absolute positioning). This view appears to handle touches and allows touchables to work with my component.
My changed UI component wrapper is as follows:
import React, {
Component,
} from 'react';
import {
requireNativeComponent,
View,
} from 'react-native';
class DroneVideo extends Component<{}> {
constructor(props) {
super(props);
}
render() {
return (
<View
{...this.props}
>
<View
style={{
width: '100%',
height: '100%',
position: 'absolute',
zIndex: 2,
}}
></View>
<DroneVideoNative
style={{
width: '100%',
height: '100%',
position: 'absolute',
zIndex: 1,
}}
/>
</View>
);
}
}
let DroneVideoNative = requireNativeComponent('DroneLiveVideo', DroneVideo);
export default DroneVideo;

Want to change opacity with react native refs on click

Here is my code. I want to change the opacity of refs when i click on any TouchableOpacity component.Please guide me how i can change opacity or change colour in react native with refs.
When i click my redirect function calls so i wanna change the opacity of particular ref in redirect function, i am passing ref and routename is redirect function.
i
mport React, { Component } from 'react';
import {
View,
Text,
TouchableOpacity,
StyleSheet
} from 'react-native';
export default class Navigation extends Component {
redirect(routeName,ref)
{
console.log(this.refs[ref]]);
this.props.navigator.push({
ident: routeName
});
}
render() {
return (
<View style={style.navigation}>
<View style={[style.navBar,styles.greenBack]}>
<TouchableOpacity style={style.navPills} onPress={ this.redirect.bind(this,"AddItem","a")} ref="a">
<Text style={[style.navText,style.activeNav]}>HOME</Text></TouchableOpacity>
<TouchableOpacity style={style.navPills} onPress={ this.redirect.bind(this,"AddItem","b")} ref="b">
<Text style={style.navText}>ORDER</Text></TouchableOpacity>
<TouchableOpacity style={style.navPills} onPress={ this.redirect.bind(this,"ListItem","c")} ref="c">
<Text style={style.navText}>SHOP LIST</Text></TouchableOpacity>
<TouchableOpacity style={style.navPills} onPress={ this.redirect.bind(this,"ListItem","d")} ref="d">
<Text style={style.navText}>DUES</Text></TouchableOpacity>
</View>
<View style={style.titleBar}>
<Text style={style.titleBarText}>{this.props.title}</Text>
</View>
</View>
);
}
}
const style = StyleSheet.create({
navigation:{
top:0,
right:0,
left:0,
position:'absolute'
},
navBar:{
flexDirection:'row',
padding:10,
paddingTop:15,
paddingBottom:15,
},
navPills:{
flex:1,
alignItems:'center'
},
navText:{
flex:1,
textAlign:'center',
fontSize:16,
fontWeight:'bold',
color:'#ffffff',
opacity:0.7
},
titleBar:{
backgroundColor:'#ffffff',
flex:1,
padding:8,
alignItems:'center',
borderBottomWidth:1,
borderBottomColor:'#dddddd'
},
titleBarText:{
fontSize:18
},
activeNav:{
opacity:1
}
});
I am not exactly sure if the following is what u are searching:
If you want to change the opacity of the TouchableOpacity use the following
export default class Navigation extends Component {
state={
opacity: 0.1
}
handleOnPress = () => {
this.setState({
opacity: 0.5 //Anything u want
});
}
render(){
return(
<TouchableOpacity underlayColor={'rgba(0,0,0,this.state.opacity)'} onPress={this.handleOnPress}>
)
}
}
If you want to change the opacity of your text use the following
export default class Navigation extends Component {
state = {
opacity: 0.1
}
handleOnPress = () => {
this.setState({
opacity: 0.5 //Anything u want
});
}
render(){
return(
<TouchableOpacity onPress={this.handleOnPress}>
<Text style={[style.navText, {opacity: this.state.opacity}]}>DUES</Text>
</TouchableOpacity>
)
}
}
Using the Stylemethods in the render allows you to take variables from the state
Hope this is the answer you wanted. If One of both is the right let me know and i delete the other one.
Best Regards
Put your opacity value into state. Then make the button click change the value of that state. This will trigger a re-render and your view will update with the new opacity.
To expand on the answer from pomo...
With the styles as you currently have them, you can easily call setState within each of your onPress functions to change the opacity of the elements you need changed. You don't even need to pass a reference if you utilize a different key in the state for each item.
Then, in your styles you would use an array of styles to use the opacity value from the state.
style={[style.navPills, { opacity: this.state.opacityA }]}
I'm not a fan of inline styles at all. So, for my purposes in a recent project I set the style of an element using its 'ref' value, then triggered a state change merely to cause the render function to be called. This is what I believe you're asking for and this sample code should point you in the right direction, otherwise perhaps this will help someone else in the future.
toggleDisplay() {
if (this.refs.blah.style.display === "") { // currently visible
this.refs.blah.style.display = "none";
this.setState({showBlah = false});
} else { // currently not visible
this.refs.blah.style.display = "";
this.setState({showBlah: true});
}
}
render() {
// Some element defined with the ref value used above.
return (<div>
<div ref="blah">Now you see me...</div>
<button onClick="this.toggleDisplay">Toggle Me</button>
</div>);
}
Nothing in my render function changed by adding the toggle functionality, other than adding a button somewhere to call the function. As I already indicated, that state value is only used to trigger the render process.