here is code: and i want to know if it is a issue? or , whether it is a universal phenomenon.
'use strict';
import React, {Component} from 'react';
import {
View,
Text,
StyleSheet,
TouchableOpacity,
Modal
} from 'react-native';
import NavActivity from '../components/NavActivity';
class TestPage extends Component {
constructor(props) {
super(props);
this.state = {
modalVisible: false
}
}
_setModalVisible(param) {
this.setState({modalVisible: param});
}
render() {
return (
<View style={Styles.wrap}>
<NavActivity
navigator={this.props.navigator}
title={{
title: '测试页面'
}}/>
<TouchableOpacity
onPress={() => this.setState({modalVisible: true})}>
<Text>show modal</Text>
</TouchableOpacity>
<Modal
animationType={'fade'}
transparent={true}
visible={this.state.modalVisible}
onRequestClose={() => {
this._setModalVisible(false)
}}>
<View style={Styles.container}>
<Text>Modal!!!</Text>
</View>
</Modal>
</View>
)
}
}
const Styles = StyleSheet.create({
wrap: {
flex: 1,
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
},
container: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'rgba(0,0,0,0.7)'
},
});
export default TestPage;
environment:
react native version: 0.40
android version: 7.1.1
the gif explain everything, and this phenomenon confuse me whether should i continue to use Modal component.
Use This 'react-native-modal' library.
import React, { Component } from 'react'
import { Text, TouchableOpacity, View } from 'react-native'
import Modal from 'react-native-modal'
export default class ModalTester extends Component {
state = {
isModalVisible: false
}
_showModal = () => this.setState({ isModalVisible: true })
_hideModal = () => this.setState({ isModalVisible: false })
render () {
return (
<View style={{ flex: 1 }}>
<TouchableOpacity onPress={this._showModal}>
<Text>Show Modal</Text>
</TouchableOpacity>
<Modal isVisible={this.state.isModalVisible}>
<View style={{ flex: 1 }}>
<Text>Hello!</Text>
</View>
</Modal>
</View>
)
}
}
For more docs read from here:-
https://github.com/react-native-community/react-native-modal
this issue fixed in RN 0.45, see the release doc enter link description here
bug fixed.
Related
I'm trying to update an app I've developed using react-navigation v4.
Using react-navigation v4 I could get the id using something like console.log(navigation.getParam('id'));
But when I tried the same after updating to v5 of react-navigation it shows me an error and I can't find the right way to get the param id
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
export default function ShowScreen({ navigation }) {
console.log(navigation.getParam('id'));
return (
<View style={styles.container}>
<Text>Show Screen</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
}
});
The other screen where the id is located is it:
import React, { useContext } from 'react';
import { View, Text, StyleSheet, Button } from 'react-native';
import { FlatList, TouchableOpacity } from 'react-native-gesture-handler';
import { Context } from '../../context/BlogContext';
import Icon from 'react-native-vector-icons/Feather'
export default function IndexScreen({ navigation }) {
const { state, addBlogPost, deleteBlogPost } = useContext(Context);
return (
<View style={styles.container}>
<Button
title="Add Post"
onPress={addBlogPost}
/>
<FlatList
data={state}
keyExtractor={(blogPost) => blogPost.title}
renderItem={({ item }) => {
return (
<TouchableOpacity onPress={
() => navigation.navigate('ShowScreen',
{ id: item.id })}>
<View style={styles.row}>
<Text style={styles.title}>
{item.title} -
{item.id}
</Text>
<TouchableOpacity onPress={() => deleteBlogPost(item.id)}>
<Icon style={styles.icon}
name="trash"
/>
</TouchableOpacity>
</View>
</TouchableOpacity>
);
}}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: 30,
justifyContent: 'center',
alignItems: 'center'
},
row: {
flexDirection: 'row',
justifyContent: 'space-between',
paddingHorizontal: 10,
paddingVertical: 20,
borderTopWidth: 1,
borderColor: '#333'
},
title: {
fontSize: 18
},
icon: {
fontSize: 24
}
});
You can get params using route.params in react navigation v5 more on that read here
just update your code to this
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
export default function ShowScreen({ navigation,route }) {
const {id} =route.params; //you will get id here via route
return (
<View style={styles.container}>
<Text>Show Screen</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
}
});
you can simply access your parameters like this
const id = this.props.route.params.id
inside this.props.route.params you will get all paramaters :)
I have a HomeScreen component which has button. I am trying to popup a modelview(Seperate component ie PopUpView) on the button click. In PopUpView i am sending its visibility as prop (isVisible).On the click of the button i am trying to change the state value popUpIsVisible from false to true. Hoping that this would re-render and popup my model view(Note this is working fine if i explicitly pass true). However with the state change it look like the render function is not being called and the popUp is not being displayed. Thanks for your help in advance
import React from 'react';
import { View, StyleSheet, Text, Button, TouchableHighlight, Alert, Dimensions} from 'react-native';
import { createStackNavigator, createAppContainer } from 'react-navigation';
import PopUpView from './src/PopUpView';
class HomeScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
popUpIsVisible: false,
};
}
setPopUpIsVisible(isVisible){
this.setState({popUpIsVisible: isVisible });
}
render() {
this.setPopUpIsVisible = this.setPopUpIsVisible.bind(this);
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor:"blue" }}>
<Text>Home Screen</Text>
<PopUpView isVisible={this.state.popUpIsVisible}/>
<Button onPress={() => {this.setPopUpIsVisible(true)}} title="Open PopUp Screen"/>
</View>
);
}
}
const RootStack = createStackNavigator(
{
Home: HomeScreen
},
{
initialRouteName: 'Home',
}
);
const AppContainer = createAppContainer(RootStack);
export default class App extends React.Component {
render() {
return <AppContainer />;
}
}
PopUpView.js
import React from 'react';
import { View, Modal,StyleSheet, Text, TouchableOpacity, Dimensions} from 'react-native';
import { TabView, TabBar,SceneMap } from 'react-native-tab-view';
import Icon from 'react-native-vector-icons/SimpleLineIcons';
const FirstRoute = () => (
<View style={{ flex: 1, backgroundColor: '#ff4081' }} />
);
const SecondRoute = () => (
<View style={{ flex: 1, backgroundColor: '#673ab7' }} />
);
const ThirdRoute = () => (
<View style={{ flex: 1, backgroundColor: '#673ab7' }} />
);
export default class PopUpView extends React.Component {
constructor(props) {
super(props);
this.state = {
modalVisible:this.props.isVisible,
index: 0,
routes: [
{ key: 'first', title: 'HIGHLIGHTS' },
{ key: 'second', title: 'AMENITIES' },
{ key: 'third', title: 'FACILITIES' },
],
};
}
setModalVisible(visible) {
this.setState({modalVisible: visible});
}
renderHeader = props => <TabBar
{...props}
indicatorStyle={{backgroundColor: 'red'}}
tabStyle={styles.bubble}
labelStyle={styles.noLabel}
/>;
render() {
return (
<Modal
animationType="slide"
transparent={true}
visible={this.state.modalVisible}
onRequestClose={() => {
Alert.alert('Modal has been closed.');
}}>
<View style={styles.container}>
<View style={styles.navBar}>
<Text style={styles.navBarTitle}>Test</Text>
<TouchableOpacity
onPress={() => {
this.setModalVisible(!this.state.modalVisible);
}}>
<Icon style={styles.closeButton} name="close" size={35} color="grey" />
</TouchableOpacity>
</View>
<TabView
navigationState={this.state}
renderScene={SceneMap({
first: FirstRoute,
second: SecondRoute,
third: ThirdRoute,
})}
onIndexChange={index => this.setState({ index })}
initialLayout={{ width: Dimensions.get('window').width }}
renderTabBar={props =>
<TabBar
{...props}
style={{ backgroundColor: 'white' }}
indicatorStyle={{backgroundColor: 'black'}}
tabStyle={styles.bubble}
labelStyle={styles.label}
/>
}
/>
</View>
</Modal>
);
}
}
const styles = StyleSheet.create({
container: {
flex:1,
margin: 50,
marginLeft: 20,
marginRight: 20,
marginBottom: 20,
backgroundColor: "white",
borderWidth: 1,
borderColor: "grey",
flexDirection: 'column'
},
navBar:{
height:70,
justifyContent: 'space-between',
alignItems: 'center',
flexDirection: 'row',
borderBottomColor: 'lightgrey',
borderBottomWidth: 1,
},
navBarTitle:{
fontSize: 25,
fontFamily: 'Optima',
paddingLeft:15,
},
closeButton:{
paddingRight:12,
},
label: {
color: 'black'
}
})
The problem with your code is that you are using the state inside the PopUpView which does not change when you change the external prop. to fix this you should use the componentwillreceiveprops and update your state accordingly.
componentWillReceiveProps(nextProps){
if(this.props.isVisible!=nextProps.isVisible){
this.setState({modalVisible:nextProps.isVisible})
}
}
The better approach will be using the this.props.isVisible as the visible prop for the Model.
In this scenario you will have to pass a function as a prop to popupview which will set the popUpIsVisible to false.
Something like below
<PopUpView isVisible={this.state.popUpIsVisible}
onDismiss={()=>{this.setState({popUpIsVisible:false})}}/>
You can call the onDismiss inside the child as
<Modal visible={this.props.isVisible}>
<TouchableHighlight
onPress={() => {
this.props.onDismiss();
}}>
<Text>Hide Modal</Text>
</TouchableHighlight>
</Modal>
The second approach is better as the visibility of the child is controlled by the parent.
Add below line into constructor after state defining
this.setPopUpIsVisible = this.setPopUpIsVisible.bind(this);
I am completely new to React Native. So please apologize me for very naive questions.
I have a main screen which has a button. When the button is pressed I want to fetch data thru another component and display on the screen.
I have App.js
import React from 'react';
import { Button, View, Text } from 'react-native';
import { createAppContainer, createStackNavigator } from 'react-navigation'; // Version can be specified in package.json
import {getMovies} from "./fetchmenu.js";
class HomeScreen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
<View style={{ flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'center' }}>
<Button
title="Menu"
onPress={() => {
<getMovies /> // I want to display data as a result of button press
}}
/>
</View>
</View>
);
}
}
const AppContainer = createAppContainer(RootStack);
export default class App extends React.Component {
render() {
return <AppContainer />;
}
}
And fetchmenu.js
import React from 'react';
import { FlatList, ActivityIndicator, Text, View } from 'react-native';
export default class getMovies extends React.Component {
constructor(props){
super(props);
this.state ={ isLoading: true}
}
componentDidMount(){
return fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson.movies,
}, function(){
});
})
.catch((error) =>{
console.error(error);
});
}
render(){
if(this.state.isLoading){
return(
<View style={{flex: 1, padding: 20}}>
<ActivityIndicator/>
</View>
)
}
return(
<View style={{flex: 1, paddingTop:20}}>
<FlatList
data={this.state.dataSource}
renderItem={({item}) => <Text>{item.title}, {item.releaseYear}</Text>}
keyExtractor={({id}, index) => id}
/>
</View>
);
}
}
How do I display the FlatList created by getMovies on HomeScreen
when the button is pressed?
In your HomeScreen set your state like this:
state={showMovies:false}
Then on Button click setState to {showMovies:true}. And in your render function in App.js:
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
<View style={{ flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'center' }}>
<Button
title="Menu"
onPress={() => {
this.setState({showMovies:true});
}}
/>
{this.state.showMovies&&<GetMovies/>}
</View>
</View>
);
}
Since you are exporting getMovies class as default export (not named) do the same with importing:
WRONG: import {getMovies} from "./fetchmenu.js";
CORRECT: import GetMovies from "./fetchmenu.js";
I strongly recommend you to watch some tutorials before getting into real projects.
EDIT
As #Milore stated Component names in React must start with capital letter. See this for further information
constructor(props){
super(props);
this.state ={ isLoading: true}
}
I don't see dataSource in this.state but you are using
this.setState({
isLoading: false,
dataSource: responseJson.movies,
}, function(){
});
Here is the code, I'm not able to invoke removeItem function while clicking on Icon tag.Please help me out I'm a beginner in react native.I'm stuck for 3 days.
Please help me out in proper way of calling function.Thanks in advanced
import React from 'react';
import { StyleSheet, Text, View,TextInput,KeyboardAvoidingView,Dimensions,ScrollView,Alert,TouchableOpacity,Button,TouchableHighlight } from 'react-native';
import Icon from 'react-native-vector-icons/Entypo';
var {height, width} = Dimensions.get('window');
var d = new Date();
export default class App extends React.Component {
constructor(props){
super(props);
this.state = {
noteList: [],
noteText: ''
}
}
addItems(){
var a = this.state.noteText;
this.state.noteList.push(a)
this.setState({
noteText:''
})
console.log(this.state.noteList)
}
removeItem(key) {
console.log('removeItem is working',key);
}
render() {
return (
<KeyboardAvoidingView style={styles.container} behavior="padding" enabled>
<View style={styles.header}>
<Text style={{fontSize: 20}}>NOTE APPLICATION</Text>
</View>
<View style={styles.body}>
<ScrollView>
{this.state.noteList.map(function(value,key){
return(
<View key={key} style={styles.bodyElements} >
<Text>{key}</Text>
<Text>{value}</Text>
<Text>{d.toDateString()}</Text>
<Icon onPress={(key) => this.removeItem(key)} name="cross" color="white" size={40}/>
</View>
)
})}
</ScrollView>
</View>
<View style={styles.footer}>
<TextInput style={{marginTop:10,marginLeft:10}}
placeholder="Jot down your thoughts before they vanish :)"
width={width/1.2}
underlineColorAndroid="transparent"
onChangeText={(noteText) => this.setState({noteText})}
value={this.state.noteText}
/>
<Icon style={{marginTop:15}} name="add-to-list" color="white" size={40} onPress={this.addItems.bind(this)}/>
</View>
</KeyboardAvoidingView>
);
}
}
I do not have your array data so i use a,b values. but mamy issue with map functionis here, you need to pass this as params . check in the code
import React from 'react';
import { StyleSheet, Text, View, TextInput, KeyboardAvoidingView, Dimensions, ScrollView, Alert, TouchableOpacity, Button, TouchableHighlight } from 'react-native';
// import Icon from 'react-native-vector-icons/Entypo';
var { height, width } = Dimensions.get('window');
var d = new Date();
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
noteList: ['a','b'],
noteText: ''
}
}
addItems() {
var a = this.state.noteText;
this.state.noteList.push(a)
this.setState({
noteText: ''
})
console.log(this.state.noteList)
}
removeItem(key) {
console.warn('removeItem is working');
}
render() {
return (
<View >
<View style={styles.header}>
<Text style={{ fontSize: 20 }}>NOTE APPLICATION</Text>
<Button title="try" onPress={(key) => this.removeItem()} name="cross"
size={40} />
</View>
<View style={styles.body}>
{this.state.noteList.map(function(value,key){
return(
<View key={key} style={styles.bodyElements} >
<Text>{key}</Text>
<Text>{value}</Text>
<Text>{d.toDateString()}</Text>
<Button title="try"
onPress={() => this.removeItem()}
name="cross"
color="white"
size={40}/>
</View>
)
},this)}
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 25,
textAlign: 'center',
margin: 10,
},
child: {
fontSize: 18,
textAlign: 'center',
margin: 10,
backgroundColor: 'green',
height: 100,
width: 200,
},
});
I followed the doc of the react-native-elements library but I get this.search as an undefined object...
searchbar react-native-elements
class SearchBarTest extends Component {
componentDidMount()
{
this.search.focus()//search is undefined
}
render(){
<SearchBar
ref={search => this.search = search}
...
/>
}
}
Any idea how to make this working?
EDIT:
Adding full context of the code.
The idea is having a component with a header and body. The header has an optional search bar or a title and two buttons depending on the props search.
If search props is true, then I display the searchBar.
PARENT COMPONENT:
import React, {Component} from 'react';
import {StyleSheet, View, Text, TouchableWithoutFeedback, Keyboard} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import DismissableKeyboardContainer from '../../components/DismissableKeyboardContainer';
export default class Search extends Component {
static navigationOptions = () => {
return {
tabBarIcon: ({tintColor}) => (
<Icon name="ios-search-outline" size={25} color={tintColor}/>
)
}
};
render() {
someMethod = () => {
console.log('hello');
}
return (
<DismissableKeyboardContainer search={true}>
<View style={{flex: 1, alignItems: 'center'}}>
<Text>Hello world</Text>
</View>
</DismissableKeyboardContainer>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
}
});
COMPONENT where the actual searchBar component is used:
import React, { Component} from 'react';
import { Keyboard, TouchableWithoutFeedback, TouchableOpacity, View, Text, StyleSheet} from 'react-native';
import { SearchBar } from 'react-native-elements'
import Icon from 'react-native-vector-icons/Ionicons';
import PropTypes from 'prop-types';
class DismissableKeyboardContainer extends Component {
static defaultProps = {
title: '',
search: false,
buttonLeft: '',
buttonRight: '',
borderShadow: true,
headerStyle:{}
};
componentDidMount()
{
}
render() {
let { title, search, buttonLeft, buttonRight, headerStyle, borderShadow } = this.props;
return (
<TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
<View style={{ flex: 1 }}>
<View style={[styles.headerContainer, borderShadow ? styles.borderShadow : '', headerStyle]}>
{
!search && <View style={{position: 'absolute', padding: 10, bottom: 0, flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'center'}}>
<TouchableOpacity style={{ flex: 0.2, alignItems: 'center'}}>
{
buttonLeft != "" && <Icon name={buttonLeft} size={25} color="grey" />
}
</TouchableOpacity>
<View style={{ flex: 1, alignItems: 'center' }}>
<Text style={styles.title}>{title}</Text>
</View>
<TouchableOpacity style={{ flex: 0.2, alignItems: 'center' }}>
{
buttonRight != "" && <Icon name={buttonRight} size={25} color="grey" />
}
</TouchableOpacity>
</View>
}
{
search && <SearchBar
ref={search => this.search = search}
containerStyle={{ backgroundColor: 'transparent', borderTopWidth: 0, borderBottomWidth: 0 }}
inputStyle={{ backgroundColor: 'white' }}
lightTheme
onChangeText={someMethod}
placeholder='Type Here...'
/>
}
</View>
<View style={{ flex: 1, backgroundColor: 'transparent'}}>
{this.props.children}
</View>
</View>
</TouchableWithoutFeedback>
);
}
}
const styles = StyleSheet.create({
headerContainer: {
flex: 0.12,
justifyContent: 'flex-end',
backgroundColor: 'white' ,
},
borderShadow: {
borderColor: '#ddd',
borderBottomWidth: 0,
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.2,
shadowRadius: 1,
elevation: 1,
},
title: {
fontSize: 18,
fontWeight: 'bold'
}
});
DismissableKeyboardContainer.propTypes = {
title: PropTypes.string.isRequired,
search: PropTypes.bool.isRequired,
buttonLeft: PropTypes.string.isRequired,
buttonRight: PropTypes.string.isRequired,
headerStyle: PropTypes.any,
};
export default DismissableKeyboardContainer;
I think I found the issue. As my SearchScreen is part of a TabBar from react-navigation, this.search.focus() error was appearing at the initial loading of the app. The Search screen being the second tab of the tabBar, I guess this is the reason why search couldn't be found as the screen was not active.
Found this answer: Trigger event on tabBar screen display
Which helped me to launch the this.search.focus() only when the screen Search is called under the componentDidUpdate() method
Please see code below:
1- First on my root navigator, I track react-navigation screen changes with onNavigationStateChange and screenProps
<Root
onNavigationStateChange={(prevState, currentState, action) => {
let currentScreen = action.routeName;
this.setState({ currentScreen })
}}
screenProps={{ currentScreen: this.state.currentScreen }}
/>
2- Then on my Parent component, I pass the currentScreen prop from I setup above in react-navigation
<DismissableKeyboardContainer search={true} currentScreen={this.props.screenProps.currentScreen}>
<View style={{flex: 1, alignItems: 'center'}}>
<Text>Hello world</Text>
</View>
</DismissableKeyboardContainer>
3- Now, I'm checking the screen being displayed and launch this.search.focus() only if the screen Search is displayed inside my DismissableKeyboardContainer child component.
componentDidUpdate() {
this.props.currentScreen === "Search" ? this.search.focus() : ''
}