react-native NumericInput component doesn't work on web browser - javascript

On the web browser, I have the + and - overlapping and clicking on them doesn't do anything. Also we can't see the number.
So I tried to run it on android and it worked properly.
But why isn't it working on the web browser ?
The code is however basic.
import React from 'react';
import { View, Text, Buttonn, FlatList } from 'react-native';
import NumericInput from 'react-native-numeric-input'
const style = require('#app/components/common/styles').style;
export default class HomeSettingsScreen extends React.Component {
constructor(props) {
super(props);
this.navigation = props.navigation;
this.state = {
homeCitiesNumber: 10,
}
}
render = () => {
return (
<View>
<View style={style.container}>
<View style={{ flexDirection: 'row', backgroundColor: 'black', width: '100%', fontFamily: 'DMSans-Regular' }}>
<Text style={style.titleContainer}>Settings</Text>
</View>
</View>
<NumericInput
value={this.state.homeCitiesNumber}
onChange={value => this.setState({homeCitiesNumber: value})}
minValue={0}
maxValue={25}
/>
<NumericInput onChange={value => console.log(value)} />
</View>
)
}
}

Related

React Native: How to call a function from another component

I am making a simple app to practice using modals. I have my modal component in a separate file from App.js. I have a button inside the modal and outside of the modal that should toggle the visibility of the modal. To handle the visibility toggle, I have a method in App.js, setVisibility, that takes in a boolean arg and sets the isVisibility state. When I had the modal component defined within App.js earlier everything was working fine, but I'm not sure about accessing and setting the state of a component from another file.
My modal component:
import React, { Component } from "react";
import { View, Modal, TouchableHighlight, Text } from 'react-native';
export default class AppModal extends Component {
constructor(props) {
super(props);
this.state = {
isVisible: this.props.isVisible
}
this.toggleVisibility = this.toggleVisibility.bind(this);
}
toggleVisibility(show) {
this.props.setVisibility(show);
}
render() {
return (
<View>
<Modal
animationType='slide'
visible={this.state.isVisible}
onRequestClose={() => this.toggleVisibility(false)}
>
<View style={{alignItems: 'center', justifyContent: 'center', flex: 1}}>
<Text>Inside the modal</Text>
<TouchableHighlight style={{padding: 10}} onPress={() => this.toggleVisibility(false)} >
<Text>Press me</Text>
</TouchableHighlight>
</View>
</Modal>
</View>
)
}
}
My app.js:
import React, { Component } from 'react';
import { Text, View, TouchableHighlight } from 'react-native';
import AppModal from './AppModal'
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
isVisible: false
}
this.setVisibility = this.setVisibility.bind(this);
}
setVisibility(show) {
this.setState({
isVisible: show
})
}
render() {
return (
<View style={{flex: 1}}>
<AppModal toggle={this.setVisibility} isVisible={this.state.isVisible} />
<View style={{justifyContent: 'center', alignItems: 'center', flex: 1}}>
<Text>Outside of the modal</Text>
<TouchableHighlight style={{padding: 10}} onPress={() => {this.setVisibility(true); console.log(this.state);}} >
<Text>Press me</Text>
</TouchableHighlight>
</View>
</View>
)
}
}
Now I get an error when I press the button in the modal which tells me that 'this.props.setVisibility is not a function'.
Please let me know if I can explain my question better. Thank you in advance!
You send the toggling callback method as toggle={this.setVisibility}, not setVisibility={this.setVisibility}, so your callback must be:
toggleVisibility(show) {
this.props.toggle(show);
}

React Native: Json not showing in Screen: Getting Error in Console

I am getting this error when trying to bring JSON data from mongodb into screen of React Native Application. Screen is showing, just no data. Error is below with code. This is simple hello world app and I am trying to bring in some json data from mongodb to the screen. I am just not sure of the correct setup, though I do have the screen visible up to choose your listing in Listings.js file. for some reason the network is not working. Not sure if I need to proxy in package.json?
App.js
import React, {Component} from 'react';
import {StyleSheet, Text, View} from 'react-native';
import {Listings} from './src/Listings';
type Props = {};
export default class App extends Component<Props> {
render() {
return (
<View style={{flex: 1}}>
<Text style={styles.welcome}>Air BNB Data Screen</Text>
<View style={{flex: 1, borderWidth: 3, borderColor: 'blue'}}>
<Listings></Listings>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
});
src
Listings.js
import React from 'react';
import {StyleSheet, View, FlatList, Text} from 'react-native';
import axios from 'axios';
export class Listings extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
show: true,
};
}
componentDidMount = () => {
const options = {
headers: {'Content-Type': 'application/json'},
};
axios
.get('http://localhost:8080/api/Listings/10006546', options)
.then((response) => {
this.setState({
data: [],
});
console.log(data)
})
.catch((error) => {
console.log(error);
});
};
renderRow = ({item}) => {
return (
<View containerStyle={{ elevation: 1, borderRadius: 15 }}>
<View row>
<View flex={2}>
<Text h4>{item._id}</Text>
</View>
</View>
</View>
)
}
render() {
return (
<View style={styles.container}>
<Text h3 style={{ marginLeft: 10 }}>Choose your Listing!</Text>
<View>
<FlatList
style={{ marginHorizontal: 10, marginTop: 10 }}
data={this.state.data}
renderItem={this.renderRow}
keyExtractor={(item, index) => item._id}
/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
fontSize: 12,
textAlign: 'center',
margin: 5,
},
});
Error in console - This is the error that I am receiving in the console.
Error: Network Error at createError (C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\axios\lib\core\createError.js:16)
at EventTarget.handleError (C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\axios\lib\adapters\xhr.js:83)
at EventTarget.dispatchEvent (C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\event-target-shim\dist\event-target-shim.js:818)
at EventTarget.setReadyState (C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:575)
at EventTarget.__didCompleteResponse (C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:389)
at C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:502
at RCTDeviceEventEmitter.emit (C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:189)
at MessageQueue.__callFunction (C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:425)
at C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:112
at MessageQueue.__guard (C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:373
)
The solve for this was fairly simplistic. I ended up doing some searching, but I was able to find a fix. Instead of using localhost, I was able to use 10.0.2.2 instead. This fixed the network error, however, I do have a data is not defined error now.

there is a way to fix "Warning: Each child in a list should have a unique "key"?

Is there a way to fix this warning?
Warning: Each child in a list should have a unique "key
I got this warning every time and don't understand how to fix it.
I try to fix it but i realize that something wrong in my way .
hope to understand whats wrong because its so annoying.
import React, { Component } from 'react';
import { View, Text, StyleSheet, ActivityIndicator, Platform, FlatList, Dimensions, Image } from 'react-native';
import { HeaderButtons, Item } from 'react-navigation-header-buttons'
import HeaderButton from '../components/HeaderButton';
import axios from 'axios';
const { width, height } = Dimensions.get('window');
export default class PlacesListScreen extends Component {
constructor(props) {
super(props);
this.state = { isLoading: true, data: [] };
}
componentDidMount() {
axios.get('https://rallycoding.herokuapp.com/api/music_albums')
.then(res => {
this.setState({
isLoading: false,
data: res.data,
})
console.log(res.data);
})
}
renderItem(item) {
const { title, artist } = item.item;
return (
<View style={styles.itemView}>
<View style={styles.imgContainer}>
{/* <Image style={styles.imageStyle}
source={{ uri: image }}
/> */}
</View>
<View style={styles.itemInfo}>
<Text style={styles.name}>
{title+ ' ' + artist}
</Text>
<Text style={styles.vertical} numberOfLines={1}>{title} |</Text>
</View>
</View>
);
}
render() {
if (this.state.isLoading) {
return (
<View style={{ flex: 1, padding: 20 }}>
<Text style={{ alignSelf: 'center', fontWeight: 'bold', fontSize: 20 }}>loading...</Text>
<ActivityIndicator />
</View>
)
}
return (
<View style={styles.container}>
<FlatList
data={this.state.data}
renderItem={this.renderItem.bind(this)}
keyExtractor={item => item.id}
/>
</View>
);
}
}
Hope that you understand my problem and how can I fix it.
the example code above shows my try to get some data from API, but it returns a warning every time about
each child in a list should have a unique "key".
console.log the key of each item. It may be possible u have the same id for some items?

TypeError: undefined is not an object (evaluating '_this3.state.bind')

App.js code:
import React from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
class HomeScreen extends React.Component {
constructor(props){
super(props);
this.state={count:0};
this.incrementCount=this.incrementCount.bind(this)
}
incrementCount(){
this.setState({
count: this.state.count + 1
})
}
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text style={styles.homeScreen}>Home Screen</Text>
<Button
title="Go to Details"
onPress={() => {
this.incrementCount();
this.props.navigation.navigate('Details');
}}
/>
</View>
);
}
}
class DetailsScreen extends React.Component {
constructor(props){
super(props);
this.state=this.state.bind(this)
this.incrementCount=this.incrementCount.bind(this)
}
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Hello </Text>
</View>
);
}
}
const AppNavigator = createStackNavigator(
{
Home: HomeScreen,
Details: DetailsScreen,
},
{
initialRouteName: 'Home',
}
);
const styles= StyleSheet.create({
homeScreen:{
}
});
export default createAppContainer(AppNavigator);
I wanted to increment a number (0), every time the user goes to the details(the second page) page. The incremented number should be displayed on the details(the second page) page.
I am a beginner in react native and I don't know how to use state in different classes. Do explain the concept of state along with the solution.
You have to send your count as prop to your DetailsPage. So in code it will look like this:
<Button
title="Go to Details"
onPress={() => {
this.incrementCount();
this.props.navigation.navigate('Details',{count:this.state.count});
}}/>
And in your DetailsScreen you have to access it like this:
class DetailsScreen extends React.Component {
constructor(props){
super(props);
//Remove these lines this is causing error and this is wrong
//this.state=this.state.bind(this)
//this.incrementCount=this.incrementCount.bind(this)
}
render() {
let count = this.props.navigation.getParam('count')
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>You were here {count} times </Text>
</View>
);
}
}

Conditional Rendering of child elements in React

I am trying to write a reusable Header Component in React-Native. I want to write it in a ways that the left and right button can be passed as child components. To know where to render which button I want to pass a prop like rightIcon or leftIcon. However I don't know how to access these props.
This is my App.js file
import React from 'react';
import {StyleSheet, TouchableHighlight, View} from 'react-native';
import Header from "./src/Header";
import {Ionicons} from '#expo/vector-icons';
export default class App extends React.Component {
render() {
return (
<View style={styles.container}>
<Header headerText={"Barcode Scanner"}>
<TouchableHighlight righticon>
<Ionicons name="md-barcode" size={36} color="white"></Ionicons>
</TouchableHighlight>
</Header>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
});
And this is the Header Component
import React from 'react';
import {Text, View} from 'react-native';
export default class Header extends React.Component {
render() {
const {textStyle, viewStyle, rightButton} = styles;
return (
<View style={viewStyle}>
<Text style={textStyle}>{this.props.headerText}</Text>
<View style={rightButton}>
{this.renderRightChild()}
</View>
</View>
);
}
renderRightChild = () => {
console.log("Check if rightIcon Prop is set");
}
}
const styles = {
viewStyle: {
backgroundColor: '#5161b8',
justifyContent: 'center',
alignItems: 'center',
height: 80,
paddingTop: 25,
shadowColor: '#000',
shadowOffset: {width: 0, height: 2},
shadowOpacity: 0.2,
elevation: 2,
position: 'relative'
},
textStyle: {
color: '#fff',
fontSize: 20
},
rightButton: {
position: 'absolute',
top:
35,
right:
20
}
}
;
I already tried to use React.Children.toArray but this always throws an error that the request entity is too large.
Thanks for all the answers
I guess you can always use a render prop that way you can not only decide whether to render left/right icon component but the component rendering the icon does not even have to know what to render:
The term “render prop” refers to a simple technique for sharing code
between React components using a prop whose value is a function.
return (
<View style={styles.container}>
<Header
headerText={"Barcode Scanner"}
renderRightIcon={() => (
<TouchableHighlight righticon>
<Ionicons name="md-barcode" size={36} color="white" />
</TouchableHighlight>
)}
/>
</View>
);
Then you can use call the right icon as a function:
return (
<View style={viewStyle}>
<Text style={textStyle}>{this.props.headerText}</Text>
{renderLeftIcon && (
<View style={leftButton}>
{renderLeftIcon()}
</View>)
}
{renderRightIcon && (
<View style={rightButton}>
{renderRightIcon()}
</View>)
}
</View>
);
You render both components, the right and left and you put an if condition inside state.
Header Component render method
render() {
const { leftOrRight } = this.props // right - true, left - false
return(
...
{ leftOrRight ? <RightIcon /> : <LeftIcon />}
);
}
Inside Component that calls Header
import Header from './somepath ...';
class Something extends React.Component {
this.state = { leftOrRight }
render() {
return(
<Header leftOrRight = {this.state.LeftOrRight}/>
);
}
}
You could have a function that sets leftOrRight in your parent class
One way to do this is write a Header Component and pass all the things, as props, which you can then access them in Header Components Props like..
<Header title="HeaderTitle"
leftButtonTitle="LeftButton"
rightButton={canBeAObjectWithSomeInfo}
leftButtonClick={handleClick} />
and then in your header component(can be class or a function)
const Header = ({}) => (
<View>
<View onPress={this.props.handleClick}>{this.props.leftButton}</View>
<View>{this.props.title}</View>
<View onPress={this.props.handleRightClick}>{this.props.rightButton}</View>
</View>
)
something like this you can have and then you can design header accordingly

Categories

Resources