React.createElement : type should not be null - ios

I copied the code from here.
This throws this warning:
.
How to fix this warning?
Code:
'use strict';
var React = require('react-native');
// I have import the ScrollView and RefreshControl
var{
StyleSheet,
Image,
ScrollView,
RefreshControl,
View,
} = React;
var Carousel = require('react-native-looped-carousel');
var Dimensions = require('Dimensions');
var {width, height} = Dimensions.get('window');
var NewsListView = React.createClass({
getInitialState: function () {
return {
isRefreshing: false,
loaded: 0,
};
},
componentDidMount: function () {
},
render: function () {
return (
// if I remove RefreshControl , the warming missing. how to fix this problem
<ScrollView
style={styles.scrollview}
refreshControl={
<RefreshControl
refreshing={this.state.isRefreshing}
onRefresh={this._onRefresh}
tintColor="#ff0000"
title="Loading..."
/>
}>
<View>
<Carousel delay={5000} style={{width: width, height: height/4 }}>
<Image
source={require('RT_XiaoYiSiGou/Image/img_banner.png')
}
style={{width: width, height: height/4}}
/>
<Image
source={require('RT_XiaoYiSiGou/Image/img_banner2.png')}
style={{width: width, height: height/4}}
/>
<Image
source={require('RT_XiaoYiSiGou/Image/img_banner3.png')}
style={{width: width, height: height/4}}
/>
</Carousel>
</View>
</ScrollView>
);
},
_onRefresh() {
this.setState({isRefreshing: true});
setTimeout(() => {
this.setState({
loaded: this.state.loaded + 10,
isRefreshing: false,
});
}, 5000);
},
});
var styles = StyleSheet.create({
scrollview: {
flex: 1,
},
});
module.exports = NewsListView;

What I "suggest" because I can't do more from your code is:
1) The error you get is because you do not call the React.createElement correctly. You should write your code in simple segments, I suggest chopping it up in three parts, definition, creation and render...
// define your element
var definitionObject = {
// a property called render which is a function which returns your markup.
render: function() {
return (
<h1 className="peterPan">
Peter Pan.
</h1>
);
}
}
// create the actual element
var PeterPanElement = React.createClass(definitionObject);
ReactDOM.render(
<PeterPanElement />,
document.getElementById('willBeReplacedByPeterPanElement')
);
I hope you agree I can't deduce more from your question, if you clean the question up we might be able to help you out more...

Related

React native listview add item not working

I am new to react native and I was implemented a simple idea in my head. Basically, I am doing a 'todo list' like component which theres a add button below and items can be added. The problem arises after clicking on the add button and the list gets updated and the following xcode warning message appears. And I have realised, after implementing the ListView, that the app in the simulator slows down so much i couldn't even inspect. The alert popup would freeze the UI after some text are entered too, and the entire app needs to be built again since I couldn't do anything. Thanks for all the help!
Main component: SurveyQn
'use strict'
import React, {
Component,
StyleSheet,
Text,
TouchableHighlight,
TextInput,
View,
ListView,
AlertIOS
} from 'react-native';
var LongButton = require('./LongButton.js');
class SurveyQn extends Component {
constructor(props) {
super(props);
this.state = {
options: [{option: 'Pizza'}],
};
}
componentWillMount() {
this.dataSource = new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2
})
}
_renderItem(item) {
return (
<LongButton
text={item.option}
onPress={() => {}}
//btnViewStyle={styles.buttonView}
//btnTextStyle={styles.buttonText}
/>
);
}
_addItem() {
AlertIOS.alert(
'Add new option',
null,
[
{
text: 'Add',
onPress: (text) => {
var options = this.state.options;
options.push({option: text})
this.setState({ options: options})
}
},
],
'plain-text'
);
}
render(){
var dataSource = this.dataSource.cloneWithRows(this.state.options);
return (
<View style={styles.container}>
<TextInput
style={styles.question}
placeholder="Question title"
placeholderTextColor="#4B667B"
selectionColor="#4B667B"
onChangeText={(text) => this.setState({text})}/>
<View style={styles.listView}>
<ListView
dataSource={dataSource}
renderRow={this._renderItem.bind(this)}/>
</View>
<TouchableHighlight
onPress={this._addItem.bind(this)}
style={styles.buttonView}
underlayColor='rgba(0,0,0,0)'>
<Text style={styles.buttonText}>
Add option
</Text>
</TouchableHighlight>
</View>
);
}
}
var styles = StyleSheet.create({
container: {
width: 300,
flex :1,
},
listView: {
flex: 1,
},
question: {
height: 30,
fontSize: 20,
fontWeight: "100",
color: '#4B667B',
marginTop: 10,
marginBottom: 10,
},
buttonView: {
width: 300,
paddingVertical: 9,
borderWidth: 1,
borderColor: '#F868AF',
marginBottom: 13,
},
buttonText: {
textAlign: 'center',
fontSize: 25,
color: '#F868AF',
fontWeight: '500'
},
});
ListView item: LongButton
'use strict'
import React, {
Component,
StyleSheet,
Text,
TouchableHighlight,
View,
} from 'react-native';
class LongButton extends Component {
render(){
return (
<TouchableHighlight
onPress={this.props.onPress}
style={this.props.btnViewStyle}
underlayColor='rgba(0,0,0,0)'>
<Text style={this.props.btnTextStyle}>
{this.props.text}
</Text>
</TouchableHighlight>
);
}
}
module.exports = LongButton;
Xcode warning message upon adding item on alert
app[27881:11151280] the behavior of the UICollectionViewFlowLayout is not defined because:
app[27881:11151280] the item height must be less than the height of the UICollectionView minus the section insets top and bottom values, minus the content insets top and bottom values.
app[27881:11151280] The relevant UICollectionViewFlowLayout instance is <_UIAlertControllerCollectionViewFlowLayout: 0x7ff0685b1770>, and it is attached to ; layer = ; contentOffset: {0, 0}; contentSize: {0, 0}> collection view layout: <_UIAlertControllerCollectionViewFlowLayout: 0x7ff0685b1770>.
2016-04-06 07:50:01.545 decisionapp[27881:11151280] Make a symbolic breakpoint at UICollectionViewFlowLayoutBreakForInvalidSizes to catch this in the debugger.
Updates:
I tried this but its not working either. Could it be the alert causing these problems? Its just taking forever to render the alert after clicking on the btn.
class SurveyQn extends Component {
constructor(props) {
super(props);
this.state = {
options: [{option: 'Pizza'}],
dataSource : new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2
})
};
}
componentWillMount() {
var data = this.state.options;
this.state.dataSource.cloneWithRows(data);
}
_renderItem(item) {
return (
{item.option}
);
}
_addItem() {
AlertIOS.alert(
'Add new option',
null,
[
{
text: 'Add',
onPress: (text) => {
var options = this.state.options;
options.push({option: text})
this.setState({ options: options})
}
},
],
'plain-text'
);
}
render(){
return (
<View style={styles.listView}>
<ListView
dataSource={this.state.dataSource}
renderRow={this._renderItem.bind(this)}/>
</View>
<TouchableHighlight
onPress={this._addItem.bind(this)}
style={styles.buttonView}
underlayColor='rgba(0,0,0,0)'>
<Text style={styles.buttonText}>
Add option
</Text>
</TouchableHighlight>
</View>
);
}
}
Before diving into complex EcmaScript notation, you can use simple notation. Here is a simple example of ListView. Please go through it and understand how it works.
var API = require('./API');
module.exports = React.createClass({
getInitialState: function(){
return {
rawData: [],
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2
}),
loaded: false,
}
},
componentWillMount: function(){
this.loadData();
},
loadData: function(){
API.getItems()
.then((data) => {
this.setState({
rawData: this.state.rawData.concat(data),
dataSource: this.state.dataSource.cloneWithRows(data),
loaded: true,
});
});
},
render: function(){
return(
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderItem}
style={styles.listView}>
</ListView>
);
},
renderItem: function(item){
return (
<View>
<Text>Custom Item</Text>
</View>
);
},
}
In API.js, I am fetching data from an API.
getItems: function(){
var REQUEST_URL = 'http://api.example.org/item/get?api_key=xxxx;
return fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseData) => {
return responseData.results.sort(sortByDate);
});
}
The code may not work, since I have not tested. But you can refer my sample project on github. Repo

How to implement slider menu in react Native

I'm new to react.
I need to develop slider menu in React-native.
I follow below link but that is not I want
http://www.reactnative.com/a-slide-menu-inspired-from-android-for-react-native/
Actually I need image which I attached here.
Please help me..
This react native package is pretty extensive, and really nice to use:
https://github.com/root-two/react-native-drawer
This is just a snippet of my code, you could create a menu bar with a button that calls the openDrawer method, and using this drawer you can set the animation to be however you like, and include a scrollview inside the drawer itself. Hope this helps!
var React = require('react-native');
var {
StyleSheet,
Component,
View,
Text,
Navigator,
TouchableHighlight,
TouchableOpacity,
} = React;
var styles = require('./styles');
var Drawer = require('react-native-drawer')
var drawerStyles = {
drawer: {
shadowColor: "#000000",
shadowOpacity: 0.8,
shadowRadius: 0,
}
}
var MainPage = React.createClass({
getInitialState: function(){
return {
drawerType: 'overlay',
openDrawerOffset:.3,
closedDrawerOffset:0,
panOpenMask: .1,
panCloseMask: .9,
relativeDrag: false,
panStartCompensation: true,
openDrawerThreshold: .25,
tweenHandlerOn: false,
tweenDuration: 550,
tweenEasing: 'easeInOutQuad',
disabled: false,
tweenHandlerPreset: null,
acceptDoubleTap: true,
acceptTap: true,
acceptPan: true,
rightSide: false,
showView: true,
}
},
setDrawerType: function(type){
this.setState({
drawerType: type
});
},
openDrawer: function(){
this.refs.drawer.open();
},
closeDrawer: function(){
this.refs.drawer.close();
},
setStateFrag: function(frag){
this.setState(frag);
},
render: function() {
var menu = <Menu
closeDrawer={this.closeDrawer}
navigator={this.props.navigator} />;
return (
<Drawer
ref="drawer"
onClose={this.onClose}
type={this.state.drawerType}
animation={this.state.animation}
openDrawerOffset={this.state.openDrawerOffset}
closedDrawerOffset={this.state.closedDrawerOffset}
panOpenMask={this.state.panOpenMask}
panCloseMask={this.state.panCloseMask}
relativeDrag={this.state.relativeDrag}
panStartCompensation={this.state.panStartCompensation}
openDrawerThreshold={this.state.openDrawerThreshold}
content={**YOURCUSTOMENU**}
styles={drawerStyles}
disabled={this.state.disabled}
tweenHandler={this.tweenHandler}
tweenDuration={this.state.tweenDuration}
tweenEasing={this.state.tweenEasing}
acceptDoubleTap={this.state.acceptDoubleTap}
acceptTap={this.state.acceptTap}
acceptPan={this.state.acceptPan}
changeVal={this.state.changeVal}
negotiatePan={false}
side={this.state.rightSide ? 'right' : 'left'}
>
<View>
<**YOURTOOLBAR** onPress={this.openDrawer}/>
<**YOURCONTENT_VIEW**/>
</View>
</Drawer>
);
},
});
module.exports = MainPage;
I've added an example that implements react-native-router-flux component to react-native-drawer. In this way it presents an easy scaffolding as cross-platform.
From what I understand, you want to toogle the slider menu with the hamburger button.
Although react-native-navigation-drawer
That can be achieved with the toogleSlideMenu function of the SliderMenu.
A simple example might be:
import React, {
View,
Text,
ScrollView,
} from 'react-native';
import SlideMenu from 'react-native-navigation-drawer';
var BasicExample = React.createClass({
render() {
return (
<View style={styles.container}>
<View>
<Text onPress={() => this._slideMenu.toogleSlideMenu()}> Your status bar </Text>
</View>
<SlideMenu
ref={(c) => this._slideMenu = c}
menu={<Menu />}
>
<View>
<Text>Your content</Text>
</View>
</SlideMenu>
</View>
);
}
});
var Menu = React.createClass({
render() {
return (
<View style={styles.container}>
<ScrollView
contentContainerStyle={styles.contentContainer}
style={styles.scrollView}>
<Text>Gallery</Text>
<Text>Latest</Text>
<Text>Events</Text>
<Text>Update</Text>
</ScrollView>
</View>
);
}
});
You can check this complete sidemenu project on github. This project contains ToolbarAndroid, routes, DrawerLayoutAndroid, overflow menu and other components.
https://github.com/darde/react-native-sidemenu

React native button click move to another screen

I'm new to react native.I need simple scenario in here by click button go to new screen.
React native button click move to another screen
I tried this
<TouchableHighlight
onPress={this.register}
style={styles.button1}>
<Text style={styles.buttontext1}>
Registration
</Text>
</TouchableHighlight>
register(){
//What should I write in here to go to a new layout.
}
Example:
write next code to index.ios.js
'use strict';
import React, {
AppRegistry,
Component,
StyleSheet,
View,
NavigatorIOS
} from 'react-native';
var rootPage = require('./root.IOS')
var client = React.createClass({
render() {
return (
<NavigatorIOS
style = {styles.container}
initialRoute={{
title: "Root",
navigationBarHidden: true,
component:rootPage
}}/>
);
}
});
const styles = StyleSheet.create({
container: {
flex: 1,
}
});
AppRegistry.registerComponent('client', () => client);
in file "root.IOS.js"
'use strict';
import React, {
StyleSheet,
View,
TouchableHighlight,
Text,
Dimensions,
} from 'react-native';
var NextPage = require('./nextPage.IOS.js');
var rootPage = React.createClass({
goDerper: function() {
this.props.navigator.push({
title: 'nextPage',
component: NextPage,
navigationBarHidden: true,
passProps: {myElement: 'text'}
});
},
render: function(){
return(
<View style={styles.container}>
<TouchableHighlight
onPress={() => this.goDerper()}>
<Text>We must go derper</Text>
</TouchableHighlight>
</View>
);
}
})
var styles = StyleSheet.create({
container: {
flex: 1,
marginTop: 20
}
});
module.exports = rootPage;
this code in file "nextPage.IOS.js"
'use strict';
var React = require('react-native');
var {
StyleSheet,
View,
Text,
} = React;
var Register = React.createClass({
render: function() {
return (
<View style={styles.container}>
<Text style={styles.text}>My value: {this.props.myElement}</Text>
<Text>any text</Text>
</View>
);
}
})
var styles = StyleSheet.create({
container: {
flex: 1
}
});
module.exports = nextPage;
You need to set up a navigator component, and use the navigator.push function. This answer should walk you through it.
If you want it simple, you can use this package : https://github.com/react-native-simple-router-community/react-native-simple-router

React-native can't access Parse data

I'm trying to use Parse as the data provider for a ListView in a Reactive Native app. I have followed the Parse guide regarding subscribing to a query but for some unknown reason the the data source is empty. I have verified and writing a test object to Parse works fine.
It seems that observe() should be called before getInitialState() or am I missing something?
'use strict';
var React = require('react-native');
var Strings = require('./LocalizedStrings');
var Parse = require('parse').Parse;
var ParseReact = require('parse-react');
Parse.initialize("api_key_here", "api_key_here");
/*
var TestObject = Parse.Object.extend("TestObject");
var testObject = new TestObject();
testObject.save({foo: "bar"}).then(function(object) {
alert("yay! it worked");
});
*/
var {
View,
Text,
ListView,
StyleSheet
} = React;
var styles = StyleSheet.create({
mainContainer: {
flex: 1,
padding: 30,
marginTop: 65,
flexDirection: 'column',
justifyContent: 'center',
backgroundColor: '#fff'
},
title: {
marginBottom: 20,
fontSize: 22,
textAlign: 'center',
color: '#000'
},
});
var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}) // assumes immutable objects
var WorkoutList = React.createClass({
mixins: [ParseReact.Mixin],
observe: function() {
return {
workouts: (new Parse.Query("Workout")).descending("createdAt")
};
},
getInitialState: function() {
return {dataSource: ds.cloneWithRows(this.data.workouts)}
},
renderRow: function() {
return (<View><Text>Testing</Text></View>)
},
render: function() {
return (
<View style = {{flex: 1, flexDirection: 'column'}}>
{Strings.workoutsTabTitle}
<ListView
ref = "listview"
dataSource = {this.state.dataSource}
renderRow = {this.renderRow}
automaticallyAdjustContentInsets = {false}
keyboardDismissMode = "onDrag"
keyboardShouldPersistTaps = {true}
showsVerticalScrollIndicator = {true}
style = {styles.mainContainer}
/>
</View>
)
}
})
module.exports = WorkoutList;
I didn't use ParseReact but the Parse Rest API to fetch data from Parse. The following code is called from componentDidMount.
fetch("https://api.parse.com/1/classes/Workout", {
headers: {
"X-Parse-Application-Id": "Your application Id",
"X-Parse-REST-API-Key": "Your API Key"
}
})
.then((response) => response.json())
.then((responseData) => {
this.setState({
dataSource: this.state.dataSource.cloneWithRows(responseData.results),
loaded: true,
})
})
.catch(function(error) {
console.log(error)
})
.done();
Using this approach you need to wait until the data is loaded before displaying the ListView. Use this.state.loaded to know when this is the case.
This works too.
observe: function() {
return {
user: ParseReact.currentUser,
abc: (new Parse.Query('abc')).descending('createdAt')
};
},
getInitialState: function () {
return {
dataSource: new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}),
};
},
render: function() {
return (
<View style={styles.full}>
<ListView
dataSource={this.state.dataSource.cloneWithRows(this.data.abc)}
renderRow={this.renderRow}
/>
</View>
);
},
Hope it helps! Cheers!

How to styles view to a ratio like 16:9 in React Native?

I want to let the red view keep ratio 16:9. I try but failed. I know React Native use Flexbox (Reimplement in Javascript), but I don't know how to do this. Thanks.
Here is my Javascript:
'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
View,
} = React;
var AwesomeProject = React.createClass({
render: function() {
return (
<View style={styles.container}>
<View style={styles.banner}>
</View>
<View style={styles.items}>
</View>
</View>
);
}
});
var styles = StyleSheet.create({
container: {
flex: 1,
},
banner: {
backgroundColor: 'red',
flex: 1,
},
items: {
backgroundColor: 'blue',
flex: 3,
},
});
AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);
Here is document about Flexbox in React Native:
http://facebook.github.io/react-native/docs/flexbox.html#content
Here is valid style props:
Valid style props: [
"width",
"height",
"top",
"left",
"right",
"bottom",
"margin",
"marginVertical",
"marginHorizontal",
"marginTop",
"marginBottom",
"marginLeft",
"marginRight",
"borderWidth",
"borderTopWidth",
"borderRightWidth",
"borderBottomWidth",
"borderLeftWidth",
"position",
"flexDirection",
"flexWrap",
"justifyContent",
"alignItems",
"alignSelf",
"flex",
"resizeMode",
"backgroundColor",
"borderColor",
"borderRadius",
"tintColor",
"opacity",
"fontFamily",
"fontSize",
"fontWeight",
"fontStyle",
"lineHeight",
"color",
"containerBackgroundColor",
"textAlign",
"writingDirection",
"padding",
"paddingVertical",
"paddingHorizontal",
"paddingTop",
"paddingBottom",
"paddingLeft",
"paddingRight",
"borderTopColor",
"borderRightColor",
"borderBottomColor",
"borderLeftColor",
"overflow",
"shadowColor",
"shadowOffset",
"shadowOpacity",
"shadowRadius",
"transformMatrix",
"rotation",
"scaleX",
"scaleY",
"translateX",
"translateY"
]"
React Native (since 0.40) supports the aspectRatio prop.
You can do:
style={{ aspectRatio: 16/9 }}
See Maintain aspect ratio of image with full width in React Native
You can use on layout function.
class AwesomeProject = extends React.Component<{}> {
constructor(props) {
super(props)
this.state = {width: 0,height:0}
}
onPageLayout = (event) => {
const {width, height} = event.nativeEvent.layout;
this.setState({
width,
height
})
};
render(){
return (
<View style={styles.container}>
<View style={[
styles.banner,
{
height:this.state.width*9/16
}
]}>
</View>
<View style={styles.items}>
</View>
</View>
);
}
});

Resources