import React, { Component } from 'react';
import { AppRegistry, Text, View, TouchableOpacity } from 'react-native';
class Check extends Component {
constructor(props){
super(props);
this.pressed = true
}
_callme = () => {
if(!this.pressed){
return ( <View>
<TouchableOpacity onPress={this._callMe}>
Show me TextBox
</TouchableOpacity>
</View>
)
}
else{
return (
<View>
<TextInput />
</View>)
}
}
showText = () => {
return (
<TouchableOpacity on Press={this._callMe}>
<Text>Show me TextBox</Text>
</TouchableOpacity>
)
}
render() {
return(
<View>
{this.pressed ? this._callMe : this.showText}
</View>
)
}
}
AppRegistry.registerComponent('Check', () => Check);
I am Newbie into the ReactNative, what I want is when ever a user clicks on a button user should get a popup box for comment, but I don't know where I am doing wrong?
Since you want to render the returned value, you need to call the function with ()
{this.pressed ? this._callMe() : this.showText()}
Also showText function return component <TouchableOpacity on Press={this._callMe}> has a space between on Press change to onPress.
Related
I've been trying to replace a view in React Native, but to no success. The app closes without errors whenever I try <TouchableOpacity onPress={() => {handleChangeMyView();}}> :
What am I doing wrong? How can I make it work?
Thank you all in advance.
import React, {
useState
} from 'react';
import {
SafeAreaView,
View,
TouchableOpacity,
} from 'react-native';
import MyInitialView from './MyInitialView';
const SiteContainer = () => {
let MyDynamicView = () => {
return (
<View></View>
);
};
const [MyDynamicViewArea, setMyDynamicViewArea] = useState(MyInitialView);
const handleChangeMyView = () => {
setMyDynamicViewArea(MyDynamicView);
};
return (
<SafeAreaView>
{MyDynamicViewArea}
<TouchableOpacity onPress={() => {handleChangeMyView();}}>
<View>
<FontAwesome name="quote-left"></FontAwesome>
</View>
</TouchableOpacity>
</SafeAreaView>
);
};
export default SiteContainer;
MyInitialView :
import React from 'react';
import {
View
} from 'react-native';
export default function MyInitialView() {
return (
<View></View>
);
}
You can use boolean value for viewing MyInitialView using useState
const [toViewMyInitialView, setToViewMyInitialView] = useState(false);
and in handleChangeMyView function set the above value as true
const handleChangeMyView = () => {
setToViewMyInitialView(true);
};
And in the SiteContainer
<SafeAreaView style={styles.siteContainer}>
// here I don't know a way to display a component in react-native, so
// you need to display the component MyInitialView if the
// toViewMyInitialView is true and when toViewMyInitialView id false it
// display MyDynamicViewArea
{toViewMyInitialView && <MyInitialView/>}
{!toViewMyInitialView && <MyDynamicViewArea/>}
<TouchableOpacity onPress={() => {handleChangeMyView()}}>
<View>
<FontAwesome name="quote-left"></FontAwesome>
</View>
</TouchableOpacity>
</SafeAreaView>
I am trying to render data from an API using a FlatList.
I can't get anywhere. I have a lot of trouble filling in the DATA and renderItem fields.
Could you help me ?
Thank you :)
import React from "react";
import { Text, ActivityIndicator, FlatList, View } from "react-native";
import axios from "axios";
export default class Results extends React.Component {
constructor(props) {
super(props);
//console.log('state',this.props)
this.state = {
city: "Montpellier", //this.props.city,
report: null, // Données de l'API
};
this.fetchWeather();
}
fetchWeather() {
axios
.get(
"https://api.openweathermap.org/data/2.5/weather?q=" +
this.state.city +
"&appid=9fce19ee0d267aa48afdf331bb1668da",
)
.then((response) => {
this.setState({ report: response.data });
//console.log(response.data)
});
}
render() {
const DATA = this.state.report;
if (this.state.report === null) {
return <ActivityIndicator size="large" color="red" />;
} else {
return (
<FlatList data={DATA} renderItem={<Text> {this.state.report.id} </Text>} keyExtractor={(item) => item.id} />
);
}
}
}
renderItem prop basically passes each item in your data to the function provided so that you can render them accordingly in the list. Changing you flatlist like this should work.
render() {
const {report} = this.state;
if (report === null) {
return <ActivityIndicator size="large" color="red" />;
} else {
return (
<FlatList
data={report}
renderItem={(reportItem) => <Text> {reportItem.id} </Text>}
keyExtractor={(item) => item.id} />
);
}
}
There are two mistakes in your Flatlist.
renderItem must be a function that returns all your JSX code
Since you already provided the Flatlist with data, you don't need to refer to this.state.report.id again, you can simply replace it with {item.id}.
So your Flatlist should look like this:
<FlatList
data={DATA}
keyExtractor={(item) => item.id}
renderItem={(item) => {
return (
<Text> {item.id} </Text>)
}}
</FlatList>
So the idea is that the FlatList will take in an array (<FlatList data={DATA} ...) and will automatically go through the items one by one. But it does not know how to render the actual UI for each item. For that we are giving a function which will transform each item into a UI element. This is the function that we are missing.
So
import React from "react";
import { Text, ActivityIndicator, FlatList, View } from "react-native";
import axios from "axios";
export default class Results extends React.Component {
.
.
.
render() {
const DATA = this.state.report;
if (this.state.report === null) {
return <ActivityIndicator size="large" color="red" />;
} else {
return (
<FlatList data={DATA} renderItem={function (item) {
return <Text> {item.id} </Text>
}} keyExtractor={(item) => item.id} />
);
}
}
}
As per the documentation, what they mean is that this function will be called and each item will be passed into it. The item shape will be of the same shape as DATA[0] (essentially any object in that array).
In the docs, they have this snippet,
const Item = ({ title }) => (
<View style={styles.item}>
<Text style={styles.title}>{title}</Text>
</View>
);
This essentially means that each object in the array is of shape
{
title: "some title"
}
That is called object destructuring, and it is easy to understand if you google for it :)
i have my app like this : https://i.gyazo.com/4cfe178d3a59bf4e7449a7aacd0f114e.png
It is a app for play to a drinking game :p. I want to save all of input already the four input and before and after the fields that the user has added
import React, { Component } from 'react';
import {
View,
Text,
Button,
ScrollView,
TextInput,
TouchableOpacity,
StatusBar
} from 'react-native';
import { createStackNavigator } from 'react-navigation';
import { style } from './style';
class Form extends Component {
constructor(props) {
super(props);
StatusBar.setBarStyle('light-content', true);
console.log(this.props);
state = {
users: [{
id:1,
prenom:''
}, {
id:2,
prenom:''
}, {
id:3,
prenom:''
}, {
id:4,
prenom:''
}]
}
}
saveUser = value => {
console.log('test');
};
showInput() {
return state.users.map((item) => {
console.log(item);
return (
<TextInput
key={item.id}
style={style.input}
placeholder={`Prénom ${item.id}`}
placeholderTextColor="#29235c"
/>
);
});
}
render() {
return this.props.fontLoaded ? (
<View style={style.bgWhite}>
<ScrollView>
{
this.showInput()
}
<View style={style.morePlayer}>
<Text style={style.morePlayerText}>+</Text>
</View>
</ScrollView>
<View style={style.center}>
<TouchableOpacity
activeOpacity={0.9}
onPress={() => this.props.navigation.navigate('Game')}
style={style.btnPlay}
>
<Text style={style.textPlay}>ON TEASE!</Text>
</TouchableOpacity>
<Button title="Go to Details" onPress={() => this.props.navigation.navigate('Game')} />
</View>
</View>
) : null;
}
}
export default Form;
Should I save this in the asyncstorage ? I want to pass the all value of input in the params to go in other screen.
Thanks,
If you just need to pass the params to another screen you can just pass an object as the second argument of navigate.
this.props.navigation.navigate('Game', {
users: this.state.users,
otherParam: 'anything you want here',
});
I have created a component called OrderGuideSelect and I am trying to render it in another area of our app. The problem is the OrderGuideSelect component is not rendering. When I set up breakpoints I am able to hit inside of the renderOrderGuideOptions function but it never makes it into the OrderGuideSelect.js file. I also tried putting 'export default' in front of the class declaration instead of the connection but it didn't make a difference. Does anyone know how to get the OrderGuideSelect component rendering properly?
Here is where I call the function that renders the OrderGuideSelect component:
<TouchableOpacity onPress={() => this.renderOrderGuideOptions()}>
<MBIcon name="ico-24-filter" size={30} style={styles.filterIcon}/>
</TouchableOpacity>
And here is the rendering function:
renderOrderGuideOptions = () => {
return (
<View>
<OrderGuideSelect />
</View>
)
}
Here is the OrderGuideSelect.js file:
import React, {Component} from 'react';
import {View, FlatList, ActivityIndicator, StyleSheet} from 'react-native';
import {connect} from 'react-redux';
import {fetchOrderGuides} from '../../actions/AppActions';
import {orderGuideSelected} from '../../actions/ProductAction';
import Header from '../../components/Header/Header';
import {createIconSetFromIcoMoon} from 'react-native-vector-icons';
import selection from '../../selection';
import OrderGuideOption from './OrderGuideOption';
const MBIcon = createIconSetFromIcoMoon(selection);
class OrderGuideSelect extends Component {
constructor(props) {
super(props);
}
componentWillMount() {
this.props.dispatch(fetchOrderGuides());
}
selectOrderGuide = id => {
this.props.dispatch(orderGuideSelected(id));
}
render() {
const {isLoading, orderGuides} = this.props.orderGuide;
return (
<View style={styles.wrapper}>
<Header />
<View style={styles.iconLine}>
<MBIcon name='ico-24-filter' style={styles.filterIcon} />
</View>
{isLoading &&
<ActivityIndicator
style={{alignSelf: 'center'}}
animating={true}
size='large'
/>
}
{!isLoading &&
<View style={styles.optionList}>
<FlatList
style={styles.optionList}
data={orderGuides}
keyExtractor={(item, index) => item.id.toString()}
renderItem={({item}) => <OrderGuideOption guideData={item} isSelected={item.id == this.props.selectedGuide.id} onSelected={this.selectOrderGuide} />}
/>
</View>
}
</View>
);
}
}
function mapStateToProps(state){
const {products, orderGuide} = state;
return {
selectedGuide: products.selectedOrderGuide,
orderGuide
}
}
export default connect(mapStateToProps)(OrderGuideSelect);
Also, I may be importing of the OrderGuideSelect component should be correct:
In your code calling this.renderOrderGuideOptions function on onPress event doesn't make sense, i.e. this.renderOrderGuideOptions returns the element but where to append it in DOM?
This should be achived using state in React. So you can set the state in onPress handler then use that state in render to show your OrderGuideOptions component.
So on onPress event bind the function handler:
<TouchableOpacity onPress={this.showOrderGuideOptions}>
<MBIcon name="ico-24-filter" size={30} style={styles.filterIcon}/>
</TouchableOpacity>
Now this showOrderGuideOptions will set the state named showOrderGuideFunction to true.
showOrderGuideOptions(){
this.setState({showOrderGuideFunction: true});
}
At last step use this showOrderGuideFunction state to render your component in the render function like this:
render() {
return (
<div>
...
{
this.state.showOrderGuideFunction &&
renderOrderGuideOptions()
}
</div>
)
}
You can do what you want probably holding a state property in your component and show your OrderGuideOptions according to this state property.
state = { showOrderGuideOptions: false };
renderOrderGuideOptions = () =>
this.setState( prevState => ( { showOrderGuideOptions: !prevState.showOrderGuideOptions }) );
render() {
return (
<View>
<TouchableOpacity onPress={this.renderOrderGuideOptions}>
<MBIcon name="ico-24-filter" size={30} style={styles.filterIcon}/>
</TouchableOpacity>
{ this.state.showOrderGuideOptions && <OrderGuideSelect /> }
</View>
)
}
I think you wanted to something similar to this
class RenderOrderGuideSelectComponent extends Component {
constructor(props) {
super(props);
this.state={
showOrderGuideSelect : false
};
}
renderOrderGuideOptions = () => {
this.setState({showOrderGuideSelect: true});
}
render() {
if(this.state.showOrderGuideSelect) {
return (
);
} else {
return (
this.renderOrderGuideOptions()}>
);
}
}
}
I have a row where date is getting displayed on click of that view, I want a datepicker to pop up and display.
class EditProfilePicture extends React.Component {
state = {
currentDate: new Date()
};
setCurrentDateForIOS = currentDate => {
this.setState({ currentDate });
};
pickDate = () => (
<View>
{Platform.OS === "ios" ? (
<DatePickerForIOS
setCurrentDateForIOS={this.setCurrentDateForIOS}
/>
) : (
DatePickerForAndroid().then(currentDate =>
this.props.changeBirthDate({ currentDate })
)
)}
</View>
);
render() {
return (
<View>
<View style={styles.Container}>
<Text style={styles.heading}>Your birthday</Text>
<TouchableWithoutFeedback onPress={this.pickDate}>
<View style={styles.dropdown}>
<Text style={styles.textStyle}>
{DateFormatter(this.state.currentDate)}
</Text>
<Icon name="chevron-down" color={MED_GREY} />
</View>
</TouchableWithoutFeedback>
</View>
</View>
);
}
}
And in DatePickerForIOS I have this---
import React from "react";
import PropTypes from "prop-types";
import { DatePickerIOS } from "react-native";
const DatePickerForIOS = props => {
return (
<DatePickerIOS
date={new Date()}
mode="date"
onDateChange={() => props.setCurrentDateForIOS}
/>
);
};
DatePickerIOS.propTypes = {
setCurrentDateForIOS: PropTypes.func.isRequired
};
export default DatePickerForIOS;
While the code works fine for android, in IOS the screen contains NAN/NAN/NAN as text initially and the datepicker doesn't open up when clicked on the view.
DatePickerIOS needs to be part of the render function of EditProfilePicture
Currently you create the component fromonPress from TouchableWithoutFeedback.
You would need to do something like the docs say
render() {
return (
<View style={styles.container}>
<DatePickerIOS
date={this.state.chosenDate}
onDateChange={this.setDate}
/>
</View>
)
}
You would need to hide/show this a state boolean value to toggle on off.
Without knowing your Android code, I suspect that is acting like a popup modal.
Another solution would be to use a package like react-native-modal-datetime-picker which has the same interface between iOS and Android