Open screen is not working with the line below - android

I have one component, he open a modal...
App.js
import ScreenModal from './ScreenModal';
return (
<View>
<TouchableOpacity onPress={ScreenModal}>
<Text>Click</Text>
</TouchableOpacity>
</View>
);
ScreenModal.js
function getModal() {
return (
<Modal isVisible={true}>
<Text>Teste</Text>
</Modal>
)
}
He not open a modal (ScreenModal). where it is the error?
obs.: I have a custom modal

your code should be like this
//your modal component
const MyModalComponent = ({isVisible = true}) => {
return (
<Modal visible={isVisible}>
<Text>Teste</Text>
</Modal>
)
}
and use it like that
const App = () => {
const [isVisible, setVisible] = React.useState(false);
return(
<View>
<TouchableOpacity onPress={() => setVisible(true)}>
<Text>Click</Text>
</TouchableOpacity>
<MyModalComponent isVisible={isVisible} />
</View>
)
}
see docs example here

Related

How do I place an array into a checkbox and click on it according to the array id react native?

When I click 1 checkbox, all values checkbox are checked too, then my question is how to separate it according to the value of the array?
render () {
const { data } = this.props
const { checked, statusChecked, unhide } = this.state
const checkBoxCourier = data.map((item, index) => {
return (
<Card key={index} style={globalStyle.padDefault}>
<Item>
<Text>
{'[LOGO] '}
</Text>
<Text style={styles.bold}>{item.courier_name.toUpperCase()}</Text>
</Item>
{
item.services.map((item2, index) => (
<ListItem
key={index}
>
<CheckBox
checked={checked}
onPress={() => this.onCheckBoxPress(item2.courier_service_id, item2.status)}
/>
<View style={styles.row}>
<Body>
<Text style={styles.textStyle}>{item2.service_name}</Text>
<Text style={styles.textStyle}>{item2.service_description}</Text>
</Body>
</View>
</ListItem>
))
}
</Card>
)
})
return (
<Container>
<ScrollView>
{checkBoxCourier}
</ScrollView>
</Container>
)
you do by this way
checked={index+item2.courier_service_id == this.state.Selected ? checked :uncheck}
onPress={() => this.onCheckBoxPress(item2,index)}
/>
and in onCheckBoxPress
onCheckBoxPress(){
this.setState({Selected:index+item2.courier_service_id})
}
I hope this will help you
You need to pass a flag to the checkbox that is specific to the service item rather than the component, something like this:
render(){
const {data} = this.props
const {checked, statusChecked, unhide} = this.state
const checkBoxCourier = data.map((item, index) => {
return (
<Card key={index} style={globalStyle.padDefault}>
<Item>
<Text>
{'[LOGO] '}
</Text>
<Text style={styles.bold}>{item.courier_name.toUpperCase()}</Text>
</Item>
{
item.services.map((item2, index) => (
<ListItem
key={index}
>
<CheckBox
checked={item2.isChecked} // Save the value here
onPress={() => this.onCheckBoxPress(item2.courier_service_id, item2.status)}
/>
<View style={styles.row}>
<Body>
<Text style={styles.textStyle}>{item2.service_name}</Text>
<Text style={styles.textStyle}>{item2.service_description}</Text>
</Body>
</View>
</ListItem>
))
}
</Card>
)
})

How can i make DrawerLayout reusable?

I am new to ReactNavite. I am playing around with Android DrawerLayout.
I am using StackNavigator for screen redirection.
Do I have to put DrawerLayoutAndroid in each screen, because it does not seem logical? Can't I create a custom class and use it in every screen and some property like selected or unselected?
Screen1.js
export default class Screen1 extends Component<{}> {
static navigationOptions = {
header: null
};
onScreen1Click() {
this.refs["NAVDRAWER"].closeDrawer();
this.props.navigation.navigate("screen1");
}
onScreen2Click() {
this.refs["NAVDRAWER"].closeDrawer();
this.props.navigation.navigate("screen2");
}
render() {
return (
<DrawerLayoutAndroid
drawerWidth={300}
drawerPosition={DrawerLayoutAndroid.positions.Left}
renderNavigationView={() => {
return (
<ScrollView vertical={true}>
<View style={styles.drawerMenuSelectedView}>
<Text
style={styles.menuItemSelected}
onPress={() => this.onScreen1Click()}
>
Screen 1
</Text>
</View>
<View style={styles.drawerMenuUnselectedView}>
<Text
style={styles.menuItemUnselected}
onPress={() => this.onScreen2Click()}
>
Screen 2
</Text>
</View>
</ScrollView>
);
}}
ref={"NAVDRAWER"}
>
<View>
<Text> Screen 1 </Text>
</View>
</DrawerLayoutAndroid>
); }
}
Screen2.js
export default class Screen2 extends Component<{}> {
static navigationOptions = {
header: null
};
onScreen1Click() {
this.refs["NAVDRAWER"].closeDrawer();
this.props.navigation.navigate("screen1");
}
onScreen2Click() {
this.refs["NAVDRAWER"].closeDrawer();
this.props.navigation.navigate("screen2");
}
render() {
return (
<DrawerLayoutAndroid
drawerWidth={300}
drawerPosition={DrawerLayoutAndroid.positions.Left}
renderNavigationView={() => {
return (
<ScrollView vertical={true}>
<View style={styles.drawerMenuSelectedView}>
<Text
style={styles.menuItemUnselected}
onPress={() => this.onScreen1Click()}
>
Screen 1
</Text>
</View>
<View style={styles.drawerMenuUnselectedView}>
<Text
style={styles.menuItemSelected }
onPress={() => this.onScreen2Click()}
>
Screen 2
</Text>
</View>
</ScrollView>
);
}}
ref={"NAVDRAWER"}
>
<View>
<Text> Screen 2 </Text>
</View>
</DrawerLayoutAndroid>
); }
}
App.js
import React, { Component } from 'react';
import { StackNavigator } from "react-navigation";
import Screen1 from "./Screen1";
import Screen2 from "./Screen2";
export default class App extends Component<Props> {
render() {
return (
<MyApp />
);
}
}
const MyApp = StackNavigator({
screen1: { screen: Screen1 },
screen2: { screen: Screen2 },
});
After long time researching , I landed on this library for drawer navigation with reusable Drawer,
https://github.com/react-navigation/react-navigation
This lib provides DrawerNavigator , Which also helps us to make custom Drawer Design and you can add screens of Drawer in DrawerNavigator...
Also, I have used this blog for reference
https://codeburst.io/custom-drawer-using-react-navigation-80abbab489f7
I hope this helps you ...

Click event on words react native

I want to set different click listeners on different words of . Currently what i have is
<Text>Android iOS React Native<Text>
Now i want to know when user click on Android, iOS and React Native, i have to perform some analytics on that so need click listeners for seperate words.
Does any one have idea about it? I have checked this thread but i din't found it useful for my requirement.
Update
String i have given is just an example string, in real time i will be getting dynamic strings.
This is what i will be getting as dynamic string
{
"str":"Hi i am using React-Native, Earlier i was using Android and so on"
"tagWords":["React-Native","Android"]
}
And in output i want, "Hi i am using React-Native, Earlier i was using Android and so on"
with click event on "React-Native" and "Android". Is is possible?
The post you sent is the simplest way you can achieve the desired behavior. Sinse you need to have different listeners you need to implement different Text components.
Example
export default class App extends Component {
onTextPress(event, text) {
console.log(text);
}
render() {
return (
<View style={styles.container}>
<Text>
<Text onPress={(e) => this.onTextPress(e, 'Android')} style={styles.red}>{'Android '}</Text>
<Text onPress={(e) => this.onTextPress(e, 'iOS')} style={styles.purple}>{'iOS '}</Text>
<Text onPress={(e) => this.onTextPress(e, 'React Native')} style={styles.green}>{'React Native'}</Text>
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
},
red: {
fontSize: 20,
color: 'red'
},
purple: {
fontSize: 20,
color: 'purple'
},
green: {
fontSize: 20,
color: 'green'
}
});
Update 1 (Dynamic text)
render() {
const fixedString = 'I\'m a fixed string that slipleted';
const arrayOfStrings = ['These', 'are', 'strings', 'from', 'array'];
return (
<View style={styles.container}>
<Text style={styles.textContainer}>
{
fixedString.split(' ').map((str, index) => {
return (
<Text onPress={(e) => this.onTextPress(e, str)}>
{`${str}${index !== (fixedString.split(' ').lenght -1) && ' '}`}
</Text>
)
})
}
</Text>
<Text style={styles.textContainer}>
{
arrayOfStrings.map((str, index) => {
return (
<Text onPress={(e) => this.onTextPress(e, str)}>
{`${str}${index !== (arrayOfStrings.lenght -1) && ' '}`}
</Text>
)
})
}
</Text>
</View>
);
}
Update 2 (for example dynamic data)
removePunctuation = (text) => {
// this is a hack to remove comma from the text
// you may want to handle this different
return text.replace(/[.,\/#!$%\^&\*;:{}=\_`~()]/g,"");
}
render() {
const arrayOfObjects = [{
str: 'Hi i am using React-Native, Earlier i was using Android and so on',
tagWords: ['React-Native', 'Android']
}];
return (
<View style={styles.container}>
<Text style={styles.textContainer}>
{
arrayOfObjects.map((obj) => {
return obj.str.split(' ').map((s, index) => {
if ( obj.tagWords.indexOf(this.removePunctuation(s)) > -1 ) {
return (
<Text onPress={(e) => this.onTextPress(e, s)} style={styles.red}>
{`${s} ${index !== (obj.str.split(' ').lenght - 1) && ' '}`}
</Text>
)
} else return `${s} `;
})
})
}
</Text>
</View>
);
}
all you need to use is TouchableOpacity(for the tap effect and clicks), View for the alignment of texts. and certain styling. I am providing you the code snippet that will work for you , all other syntax will remain same
import {Text, View, TouchableOpacity} from 'react-native'
<View style={{flexDirection:'row'}}>
<TouchableOpacity onPress={{()=>doSomethingAndroid()}}>
<Text>Android</Text>
</TouchableOpacity>
<TouchableOpacity onPress={{()=>doSomethingiOS()}}><Text> iOS</Text>
</TouchableOpacity>
<TouchableOpacityonPress={{()=>doSomethingReactNative()}}><Text> React Native</Text>
</TouchableOpacity>
</View>
i hope this works, comment back if any issue happens
You can wrap each clickable words into 'TouchableOpacity' component, and tract the onPress event as follows
<View style={{flexDirection: 'row'}}>
<TouchableOpacity onPress={() => {
console.log('Android Clicked');
}}>
<Text>Android</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => {
console.log('iOS Clicked');
}}>
<Text>Ios</Text>
</TouchableOpacity>
</View>
Please do adjust the spacing between words.
Edit:
For dynamic string you can proceed as follows
...
handleWordClick(str, handler) {
var words = str.split(' '), // word separator goes here,
comp = [];
words.forEach((s, ind) =>{
comp.push(
<TouchableOpacity key={ind} onPress={() => handler.call(this, s)}>
<Text>{s}</Text>
</TouchableOpacity>
);
})
return comp;
}
render() {
var comp = this.handleWordClick('Android iOS React-Native', (word) => {
//handle analytics here...
console.log(word);
});
return (
<View>
...
<View style={{flexDirection: 'row'}}>
{comp}
</View>
...
</View>
)
}
I am not sure what will be your word separator as the example you have given has 'React Native' as single word. Please pay attention on this part.
Hope this will help you.

How focus the next field input in react native?

I need focus the next field input in react native, in android platform.
But the focus() function, not exists in android react native, only in IOS.
How make this ? I use react native with typescript.
The focus function works just fine.
<View style={{flexDirection: 'row'}}>
<Text style={{flex: 1}}>Enter Name: </Text>
<TextInput ref="name" onChangeText={(name) => this.setState({name})} style={{flex: 1}}
onSubmitEditing={() => this.refs.age.focus()}/>
</View>
<View style={{flexDirection: 'row'}}>
<Text style={{flex: 1}}>Enter Age: </Text>
<TextInput ref="age" keyboardType="numeric" onChangeText={(age) => this.setState({age})} style={{flex: 1}}
onSubmitEditing={() => this.refs.sport.focus()}/>
</View>
<View style={{flexDirection: 'row'}}>
<Text style={{flex: 1}}>Enter Favourite Sport: </Text>
<TextInput ref="sport" onChangeText={(sport) => this.setState({sport})} style={{flex: 1}}/>
</View>
Hope this helps. This is for android.
You have to user ref on Inputs where you want to focus on:
<Input
ref={(node) => { this.myInput = node }}
value={this.state.myInput.toString()}
onSubmitEditing={() => { this.myOtherInput.focus() }}/>
<Input
ref={(node) => { this.myOtherInput = node }}
value={this.state.myOtherInput.toString()}/>
You can see that when you submit the editing on the first input you will focus on the second one. you can use this.MY_CUSTOM_REF.focus() wherever you want.
This work for me:
<Input
blurOnSubmit={false}
returnKeyType="next"
onSubmitEditing={() => {
this.passwordInput.wrappedInstance.focus();
}}
/>
<Input
secureTextEntry
ref={(input) => {
this.passwordInput = input;
}}
/>
I insert the function in my customize component.
public focus(){
this.input.focus()
}
Have a look at this article, this might be handy react-native inputs
//Helper function
focusNextField(nextField) {
this.refs[nextField].focus();
}
<TextInput
ref='1'
style={styles.otpInputStyle}
keyboardType='numeric'
secureTextEntry
value={this.props.otp1}
maxLength={1}
onChangeText={(num) => {
this.props.otpCode1(num); //action call
if (num && num.length === 1) {
this.focusNextField('2'); //function call. '2' ref to next input ref
}
}}
/>
import React, { useRef } from 'react';
...
export default function YourFuctionalComponent() {
const input1 = useRef(null);
const imput2 = useRef(null);
const doSomething = () => {}
return(
<>
<TextInput
autoFocus
ref={input1}
onSubmitEditing={() => { imput2.current.focus(); }}
returnKeyType="next"
/>
<TextInput
ref={input2}
onSubmitEditing={() => doSomething()}
returnKeyType="done"
/>
</>
);
}
https://i.stack.imgur.com/W6dvs.gif

How can I findViewById() in react-native android

I'm referring to this in my index.android.js file..
<View>
<CustomView>
...
</CustomView>
</View>
This can be done by React.findNodeHandle.
In your case,
...
var { findNodeHandle } = React;
...
render: function() {
return (
<View>
<CustomView ref="customView">
...
</CustomView>
</View>
);
},
somethingLikeComponentDidMount: function() {
var customViewNativeID = findNodeHandle(this.refs.customView);
// Something else...
}
...
might do the work.
For a working example (natively binding two components), check out here as the JS part and here as the native Java part.
do use refs for the component which can act as the reference for the component
ex:
<View>
<TextInput style={styles.textInput}
ref={'usrname'}
placeholder={'Username'}
placeholderTextColor={'red'}
onChangeText={(userName) => this.setState({userName})}
value={this.state.userName} />
<TouchableOpacity onPress={this._onPressButton}>
<View style={styles.buttonContainer}>
<Text> Submit </Text>
</View>
</TouchableOpacity>
</View>
and onPress:
_onPressButton: function(e){
var x = this.state.userName;
alert(x); //we can also use alert(this.state.userName)
},

Categories

Resources