I'm trying to display a nested array containing numbers. The array has 6 elements (arrays). Each nested array contains 6 further elements/numbers. I'm trying to display each number in a Square component. I've got an error: this.props.inGrid.foreach is not a function.
import React, { Component, PropTypes } from 'react';
import { View, StyleSheet } from 'react-native';
import Square from './Square';
import * as globalStyles from '../styles/global';
export default class Grid extends Component {
render() {
const row = [];
this.props.inGrid.foreach((r, i) => {
row.push(
<Square key={i} sqValue={r[i]} />
);
});
return (
<View style={styles.grid}>
{row}
</View>
);
}
}
Grid.propTypes = {
numbers: PropTypes.object
};
const styles = StyleSheet.create({
grid: {
backgroundColor: globalStyles.BG_COLOR,
flexDirection: 'row',
padding: 20,
justifyContent: 'center'
}
});
Below is the Square component:
import React, { PropTypes } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import * as globalStyles from '../styles/global';
const Square = ({ sqValue }) => {
return (
<View style={styles.square}>
<Text>{sqValue}</Text>
</View>
);
};
Square.propTypes = {
sqValue: PropTypes.number
};
const styles = StyleSheet.create({
square: {
backgroundColor: globalStyles.BAR_COLOR,
width: 50,
height: 50,
borderWidth: 1,
borderStyle: 'solid',
borderColor: 'red'
}
});
export default Square;
What am I doing wrong?
It appears that you're calling:
this.props.inGrid.foreach
but the function is actually called forEach
Related
I'm trying to implement themes (dark | light) in my expo react-native app. I've been reading their documentation on the dark and light themes on the expo page, and that works inside App.js. However, whenever I declare a component and import it in App.js, it won't work. My thought process is trying to "extend" the current theme to my component.
Here's the App.js code:
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View, useColorScheme } from 'react-native';
//import firebase + config
import firebaseConfig from './config'
import firebase from 'firebase'
//initialize firebase application
if(!firebase.apps.length){
firebase.initializeApp(firebaseConfig)
} else{
firebase.app()
}
//import screens
import Overview from './screens/Overview'
export default function App() {
const colorScheme = useColorScheme();
const themeTextStyle = colorScheme === 'light' ? styles.lightThemeText : styles.darkThemeText;
const themeContainerStyle = colorScheme === 'light' ? styles.lightContainer : styles.darkContainer;
return (
<View style={[styles.container, themeContainerStyle]}>
<Overview />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
lightContainer: {
backgroundColor: '#fff',
},
darkContainer: {
backgroundColor: '#101010',
},
lightThemeText: {
color: '#000000',
},
darkThemeText: {
color: '#ffffff',
},
});
And here's my simple component:
import React from 'react'
import {View, Text, useColorScheme} from 'react-native'
export default class App extends React.Component{
render(){
return(
<View>
<Text>OverView</Text>
</View>
)
}
}
All I'm trying to do is get that Overview component to follow the theme rules instead of needing to declare the style that's already been declared in App.js.
Now it's not reflected in the code, but I did try a lot of stuff before posting this question.
Firstly, install react-native-appearance from here
Create a folder called context where your App.js is located then inside it create a file called ThemeContext.js inside which will look like this
import React from "react";
const ThemeContext = React.createContext();
export default ThemeContext;
Then your App.js should look like this
import React from 'react';
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View } from 'react-native';
import { AppearanceProvider, useColorScheme } from 'react-native-appearance';
//import firebase + config
import firebaseConfig from './config';
import firebase from 'firebase';
import ThemeContext from './context/ThemeContext'; // Imported Here
//initialize firebase application
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
} else {
firebase.app();
}
//import screens
import Overview from './screens/Overview';
export default function App() {
const colorScheme = useColorScheme();
const themeValue =
colorScheme === 'light' ? styles.lightThemeText : styles.darkThemeText;
const themeContainerStyle =
colorScheme === 'light' ? styles.lightContainer : styles.darkContainer;
return (
<AppearanceProvider>
<ThemeContext.Provider value={themeValue}> // Wrapped Here
<View style={[styles.container, themeContainerStyle]}>
<Overview />
</View>
</ThemeContext.Provider>
</AppearanceProvider>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
lightContainer: {
backgroundColor: '#fff',
},
darkContainer: {
backgroundColor: '#101010',
},
lightThemeText: {
color: '#000000',
},
darkThemeText: {
color: '#ffffff',
},
});
Your Overview.js should look like this
import React from 'react';
import { View, Text } from 'react-native';
import ThemeContext from '../context/ThemeContext';
function Overview() {
const themeContext = React.useContext(ThemeContext);
console.log(themeContext); // You will get styles logged into the console here
return (
<View>
<Text>OverView</Text>
</View>
);
}
export default Overview;
I am new to React-Native and its states, here I am stuck with a problem (using dummy data but my problem is same) all I want to achieve is get the latest JSONARRAY fetched from the state, based on button clicks when I click on button one it should only return [{"one":"oneKey"},{"key":"mutatedFruit"}] and similar approach for other buttons as well any help is appreciated
I have attached my
expo snack code here
hope the below code helps ,
import * as React from 'react';
import { Text, View,Button, StyleSheet } from 'react-native';
import Constants from 'expo-constants';
// You can import from local files
import AssetExample from './components/AssetExample';
const data = [
{"joinedUsers":[{"one":"oneKey"}],"key":"mango"}
,{"joinedUsers":[{"two":"twoKey"}],"key":"apple"}
,{"joinedUsers":[{"three":"threeKey"}],"key":"banana"}
,{"joinedUsers":[{"four":"fourKey"}],"key":"kiwi"}];
// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
export default class App extends React.Component {
constructor(props){
super(props);
this.state={
selectedPosition:0,
valueArr : []
}
}
componentDidMount(){
let newVal = [];
newVal.push(data[0].joinedUsers[0])
newVal.push({"key":"mutatedFruit"})
this.setState({valueArr:newVal})
}
setValues = (position) => {
let newVal = [];
newVal.push(data[position].joinedUsers[0])
newVal.push({"key":"mutatedFruit"})
this.setState({valueArr:newVal})
}
render() {
const value = data[this.state.selectedPosition].joinedUsers
value.push({"key":"mutatedFruit"})
return (
<View style={styles.container}>
<Button title='ONE'
onPress={()=>this.setValues(0)}></Button>
<Button title='TWO'
onPress={()=>this.setValues(1)}></Button>
<Button title='THREE'
onPress={()=>this.setValues(2)}></Button>
<Button title='FOUR'
onPress={()=>this.setValues(3)}></Button>
<Text>{JSON.stringify(this.state.valueArr)}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
flexDirection:'column'
},
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
},
});
EDIT: Based on your comment, it sounds like your issue is you don't want the same value added multiple times. In that case, this should fix it:
export default class App extends React.Component {
state= {
selectedPosition:0,
}
render() {
const value = data[this.state.selectedPosition].joinedUsers
value[0]["key"] = "mutatedFruit"
return (
<View style={styles.container}>
<Button title='ONE'
onPress={()=>this.setState({selectedPosition:0})}></Button>
<Button title='TWO'
onPress={()=>this.setState({selectedPosition:1})}></Button>
<Button title='THREE'
onPress={()=>this.setState({selectedPosition:2})}></Button>
<Button title='FOUR'
onPress={()=>this.setState({selectedPosition:3})}></Button>
<Text>{JSON.stringify(value)}</Text>
</View>
);
}
}
React native won't display any of my States in or . But they're working with functions.
That is in my Code:
import {
StyleSheet,
View,
Image,
Text, //Important
PanResponder,
Animated,
Dimensions,
Button,
Slider,
TouchableWithoutFeedback,
Alert,
TouchableOpacity,
TouchableHighlight,
Modal, // Important
} from 'react-native'
My Constructor:
constructor(props) {
super(props);
this.state = {ModalMenu: false};
this.state = {ModalKunst: false};
this.state = {ModalArtwork: false};
this.state = { viewRef: null };
this.state = { age: 150 };
this.state = { farbe: 'black'};
this.state = {ModalPrice: false};
this.state = {
TextInputName: '',
TextInputEmail: '',
}
this.state = {
TextInputName2: '',
TextInputEmail2: ''
}
}
To display the State:
render() {
const {birthday, name, bio, id, id2} = this.props.profile
const profileAge = this.calcAge(birthday)
var fbImage = require('./img/bild12.jpg')
const rotateCard = this.pan.x.interpolate({
inputRange: [-200, 0, 200],
outputRange: ['10deg', '0deg', '-10deg'],
})
const animatedStyle = {
transform: [
{translateX: this.pan.x},
{translateY: this.pan.y},
{rotate: rotateCard},
]
}
return (
<View><Text>{this.state.age}</Text></View>
);
}}
But its showing nothing :(
I also don't get an error
Would be very nice if someone could help me out with that.
I updated all the render code
In the constructor please do all your initialization at once. Every this.state = {} statement is overriding the previous this.state
replace your constructor with following code.
this.state = {
ModalMenu: false,
ModalKunst: false,
viewRef: null,
age: 150,
farbe: 'black',
ModalPrice: false
};
Heres a sample code try this..
import React, { Component } from 'react';
import { Text, View, StyleSheet } from 'react-native';
export default class App extends Component {
constructor(){
super();
this.state = {age: '25'};
}
render() {
return (
<View >
<Text style={styles.paragraph}>
{this.state.age}
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
paragraph: {
margin: 44,
fontSize: 20,
fontWeight: 'bold',
textAlign: 'center',
color: '#34495e',
},
});
Your render method doesn't return anything. Add return inside
render method.
change this:
render() {
*not important*
}
to:
render() {
return (
<View><Text>{this.state.age}</Text></View>
);
}
At the moment, you are continually overriding your state, I've tidied your code up a bit below, here are some points to note about what I've done...
You need to import React from 'react' to utilise 'Component' as your class needs to extend from this.
You need to use a class as you have state
You can import an image like I've done below with fbImage
It's good habit to have say what is your exported default in each component you make.
You don't need to call constructor and super, just simply doing state = {} will do this for you
Place all your state within one state object, don't keep recalling state
Think about your general code formatting (in terms of how it looks) easier code to read will help you identify errors more easily!
import React from 'react'
import {
StyleSheet,
View,
Image,
Text, //Important
PanResponder,
Animated,
Dimensions,
Button,
Slider,
TouchableWithoutFeedback,
Alert,
TouchableOpacity,
TouchableHighlight,
Modal, // Important
} from 'react-native'
import fbImage from './img/bild12.jpg'
export default class App extends React.Component {
state = {
age: 150,
farbe: 'black',
ModalArtwork: false,
ModalKunst: false,
ModalMenu: false,
ModalPrice: false,
TextInputName: '',
TextInputEmail: '',
TextInputName2: '',
TextInputEmail2: '',
viewRef: null,
}
render() {
const {birthday, name, bio, id, id2} = this.props.profile
const profileAge = this.calcAge(birthday)
const rotateCard = this.pan.x.interpolate(
{
inputRange: [-200, 0, 200],
outputRange: ['10deg', '0deg', '-10deg'],
}
)
const animatedStyle = {
transform: [
{translateX: this.pan.x},
{translateY: this.pan.y},
{rotate: rotateCard},
]
}
return (
<View>
<Text>
{this.state.age}
</Text>
</View>
)
}
}
I'm using ReactNative to create an iOS app. But I encountered an error I don't know how to fix.
I wanted to create a button for navigating to another scene. I followed Dark Army's tutorial on RN navigation and used the source code provided. I double checked everything and all seemed fine. But the error I mentioned pops up.
Here's the code I have done so far:
Index.ios.js:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
} from 'react-native';
var Navigation = require('./DARNNavigator');
class QayProject extends Component {
render() {
return (
<Navigation></Navigation>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#FFF5E7',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('QayProject', () => QayProject);
DARNNavigator:
'use strict';
import React , {Component} from 'react';
import{
View,
Navigator
} from 'react-native';
const FirstPage = require('./FirstPage');
const SecondPage = require('./SecondPage');
class DARNNavigator extends React.Component{
constructor(props) {
super(props);
}
render() {
var initialRouteID = 'first';
return (
<Navigator
style={{flex:1}}
initialRoute={{id: initialRouteID}}
renderScene={this.navigatorRenderScene}/>
);
}
navigatorRenderScene(route, navigator) {
switch (route.id) {
case 'first':
return (<FirstPage navigator={navigator} route={route} title="FirstPage"/>);
case 'second':
return (<SecondPage navigator={navigator} route={route} title="SecondPage"/>);
}
}
}
module.exports = DARNNavigator;
FirstPage:
import React, { Component } from 'react';
import{
View,
Navigator,
Button,
AppRegistry,
StyleSheet
} from 'react-native';
export default class FirstPage extends Component {
constructor(props) {
super(props);
this.state={ id:'first' }
}
render() {
return (
<View style={styles.container}>
<Button
onPress={this.props.navigator.push({ id:'second' })}
title="Next"
color="#FFB200"
/>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
module.exports = FirstPage;
SecondPage:
import React, { Component } from 'react';
import {
View,
Text,
Navigator,
StyleSheet
} from 'react-native';
export default class SecondPage extends Component {
constructor(props) {
super(props);
this.state={
id:'second'
}
}
render() {
return (
<View style={styles.container}>
<Text style={styles.title}>
Hello!
</Text>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
module.exports = SecondPage;
Don't use that library. They don't even have ONE single star on Github (not that it's the measure of a library's worth, I'm just saying there are more proven libraries available). The best and most straightforward I've found so far is "react-native-navigation" (https://github.com/wix/react-native-navigation). A lot of people like "react-native-router-flux" as well but I personally don't.
Sorry, I don't have time to read the code right now, I may later. But my suggestion for now is to try out react-native-navigation. It's seriously amazing.
I suggest to follow the official guide of React Native and use the built-in Navigator component.
Using Navigators React Native
I never saw that error, but if it will come after a lot of navigation steps, you should take a look at the resetTo function. It will clear the navigation stack. This makes sense for example when you are navigating back to the home screen of your app.
How to handle with zIndex?
I tried to specify the largest number from the scrollview, but it's still at the bottom(
Without ScrollView it looks like this, but I need to scroll up to image.
Thank you
This has been implemented in iOS as of 0.30 (see the commit changes) and in android in 0.31 (changes)
I have made a simple example component for how I have been using it:
'use-strict';
import React, { Component } from 'react';
const { View, StyleSheet } = require('react-native');
const styles = StyleSheet.create({
wrapper: {
flex:1,
},
back: {
width: 100,
height: 100,
backgroundColor: 'blue',
zIndex: 0
},
front: {
position: 'absolute',
top:25,
left:25,
width: 50,
height:50,
backgroundColor: 'red',
zIndex: 1
}
});
class Layers extends Component {
constructor(props) {
super(props);
}
render() {
return (
<View style={styles.wrapper}>
<View style={styles.back}></View>
<View style={styles.front}></View>
</View>
);
}
}
module.exports = Layers;