differents buttons, differents images? react native - ios

I'm a student and I developing a mobile app with React Native.
My target is this image:
(https://cdn.discordapp.com/attachments/403580119714889736/407172407049060352/Apercu_bingo_2_choisir_invites.jpg)
I could write the code with independent buttons, the problem appears when I want to add different images to each button. (I'm waiting for the back dev to create a boucle to add all the images with the shortest code possible (looking forward for some loop ideas ;) ).
import React, {Component} from 'react';
import Button from 'react-native-button';
import
{
AppRegistry,
StyleSheet,
View,
Text,
TouchableHighlight,
Alert,
Image,
ScrollView,
TouchableWithoutFeedback
}
from 'react-native';
import styles from './Styles';
class ToggleButton extends React.Component {
render() {
return (
<View style={styles.cont2}>
<TouchableHighlight style={styles.bubblechoice} onPress={this.props.onPress}>
<View style={[styles.overlay, this.props.selected ? {backgroundColor: '#3C1088'} : {}]}>
<Image style={styles.bubblechoice} source={require('./photo1.jpg')}/>
</View>
</TouchableHighlight>
</View>
);
}
}
export default class MyComponent extends Component
{
constructor(props) {
super(props);
this.state = {
inv1: false,
inv2: false,
};
}
updateChoice(type) {
let newState = {...this.state};
newState[type] = !newState[type];
this.setState(newState);
}
render() {
return (
<View style={styles.containerinvite}>
<ScrollView contentContainerStyle={styles.list}>
<ToggleButton label='inv1' onPress={() => { this.updateChoice('inv1') } } selected={this.state.inv1}/>
<ToggleButton label='inv2' onPress={() => { this.updateChoice('inv2') } } selected={this.state.inv2}/>
<TouchableWithoutFeedback
onPress={() => {Alert.alert('OK');}}>
<View style={styles.button}>
<Text style={styles.buttonText}>ok</Text>
</View>
</TouchableWithoutFeedback>
</View>
);
}
onPress1 = () => {
this.setState({
inv1: !this.state.inv1
});
}
onPress2 = () => {
this.setState({
inv2: !this.state.inv2
});
}
}
The result that I have is:
https://scontent-cdt1-1.xx.fbcdn.net/v/t35.0-12/28580783_10216099091730046_1132055272_o.png?oh=fdb33bbe2b82f29cac1d80b8e25f269e&oe=5A9B2488&dl=1, https://www.facebook.com/
The thing is that the View that changes the status color can't be without children, so I can't just change the image from there. I tried different options but I'm still can manage different photos with independents buttons.

From your parent component you should pass your photos to the child component and use that prop for your source instead of
<Image style={styles.bubblechoice} source={require('./photo1.jpg')}/> =>> This is wrong.
<Image style={styles.bubblechoice} source={require(photoUrls)}/> =>> It should be like this.
If you have further questions about it do not hesitate to ask.

Related

React Native NOT rendering data from database on IOS

I have problem with render data on IOS Simulator. Render is work properly on website, but on IOS I still got stuck on "Loading.." text.
Here is my code:
import React from 'react'
import { useState } from 'react';
import { useEffect } from 'react';
import { SafeAreaView, Text, View, StyleSheet, Image, Alert } from 'react-native';
import { Card } from 'react-native-paper'
import firebase from 'firebase'
import Button from '../components/Button'
import Background from '../components/Background'
import TopBar from '../components/TopBar'
export default function HomeScreen({ navigation }) {
const [data, setData] = useState([])
const sampleData = [{id:0, title:"One"}, {id:1, title: "Two"}]
useEffect(() =>
{
const donorsData = [];
firebase.database()
.ref("testdb")
.orderByChild("isDonor")
.equalTo(true)
.once("value")
.then((results) => {
results.forEach((snapshot) => {
donorsData.push(snapshot.val());
});
setData(donorsData);
});
}, [])
const card = data.length > 0
? data.map(item =>
{
return <Card key={item.uid} style={{ marginBottom: 20, borderRadius: 10, }}>
<Text>{item.name}</Text>
<Text>{item.description}</Text>
<Image src={item.photo}></Image>
</Card>
})
: <Text>Loading...</Text>
return (
<View style={styles.container}>
{card}
</View>
);
}
On website is everything ok Website Screen
But on IOS Simulator I got only Loading
IOS Screen
I tried a lot of solutions found here, but no one works with this case. I think is probably because iOS doesn't have data? When I put console log at to top of return, I got nothing.
This might be a race condition error. You shouldn't rely on the data being fetched within 1500ms.
If that doesn't work. Make sure your result from firebase is correct.
Maybe something like this?
const [data, setData] = useState([])
const fetchDonorData = () => {
firebase.database()
.ref("testdb")
.orderByChild("isDonor")
.equalTo(true)
.once("value")
.then((results) => {
console.log({result}) //Make sure the data looks the way you want it
const mappedResult = results?.map(snapshot => snapshot.val())
setData(mappedResult)
})
}
useEffect(() => {
fetchDonorData()
}, [])
const renderItem = ({item}) =>
<Card style={{ marginBottom: 20, borderRadius: 10, }}>
<Text>{item.name}</Text>
<Text>{item.description}</Text>
<Image src={item.photo}></Image>
</Card>
return (
<View style={styles.container}>
<FlatList
data={data}
renderItem={renderItem}
keyExtractor={({item}) => item.uid}
ListEmptyComponent={<Text>Loading...</Text>}
/>
</View>
)

Using states in react native

I'm pretty new to the idea of states in react native and have trouble using them to change the states of the components. I have three text components one which is a question and another two are answers (yes and no), and another text component that checks if my answer to the question is write, so the check text component. When I click on yes for a certain question the state of the last check component should change to 'right' if the answer was yes or to 'wrong' if the answer is no. So basically, this is what I want to do :
So, the idea is when i click on yes and then check the pop-up should be this. This is the code I have so far:
import React, {useState} from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
export default function App() {
const [myState, setMyState] = useState('Yes');
const [myState2, setMyState2] = useState('Right');
const updateState = () => {
let tempStr = myState;
if (tempStr == "Yes"){
setMyState2('Right');
}
else{
setMyState2('Wrong');
};
}
return (
<View style={{alignItems: 'center', top: 150}}>
<Text>Is the earth round?</Text>
<Text mystate={setMyState}>Yes</Text>
<Text mystate={setMyState}>No</Text>
<Text mystate2={setMyState2}>Check</Text>
</View>
);
}
Currently, none of my text components seem to work.
Can anyone tell me how it could be done. Thanks!
I believe this will sufficiently help you with your question. useEffect is basically the new ComponentWillUpdate for hooks, and you should use it to check for when a state in a functional component updates. On the other hand, your code wasn't working because you were passing a mystate prop to the Text component. There is simply no mystate prop, and there also isn't a command to tell the app that you are pressing the text. You can simply use the onPress prop. Personally I prefer using a TouchableOpacity, but you could use a Button or even just pass it into the Text component itself.
import React, { useState, useEffect } from 'react'
import { View, Text, TouchableOpacity, Alert } from 'react-native'
export default function App() {
const [myAnswer, setMyAnswer] = useState('Who knows')
const [correct, setCorrect] = useState('')
useEffect(() => {
if (myAnswer == 'Who knows') setCorrect('Please answer!')
else if (myAnswer == 'Round') setCorrect('Correct!')
else if (myAnswer == 'Not round') setCorrect('Wrong :(')
}, [myAnswer])
return (
<View style = {{ justifyContent: 'center', alignItems: 'center', flex: 1 }}>
<Text>Is the Earth round?</Text>
<TouchableOpacity
onPress = {() => setMyAnswer('Round')}>
<Text>Yes</Text>
</TouchableOpacity>
<TouchableOpacity
onPress = {() => setMyAnswer('Not round')}>
<Text>Nope</Text>
</TouchableOpacity>
<TouchableOpacity
onPress = {() => { Alert('Your answer was...', correct) }}>
<Text>Check My Answer</Text>
</TouchableOpacity>
</View>
)

Unable to display fetched data in react native firebase using this.state.data.map()

I have been battling with the display of database item on my page using this.state.noteArray.map(val, key). I intend to display each value with a delete button to remove it from the page.
import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
TextInput,
ScrollView,
TouchableOpacity
} from 'react-native';
import firebase from 'firebase';
// Initialize Firebase
const config = {
apiKey: "XXXXXXXXXXXXXXX",
authDomain: "XXXXXXXXXXXXXXXXXXXXXX",
databaseURL: "XXXXXXXXXXXXXXXXXXXXXXXX",
projectId: "XXXXXXXXXXXXXXXXXXXXXX",
storageBucket: "",
messagingSenderId: "XXXXXXXXXXXXXXXXXXXX"
};
firebase.initializeApp(config);
export default class Main extends Component {
constructor(props){
super(props);
this.state = {
noteArray: [],
noteText: '',
};
this.addNote = this.addNote.bind(this);
}
componentDidMount(){
firebase.database()
.ref()
.child("todo")
.once("value", snapshot => {
const data = snapshot.val()
if (snapshot.val()){
const initNoteArray = [];
Object
.keys(data)
.forEach(noteText => initNoteArray.push(data[noteText]));
this.setState({
noteArray: initNoteArray
});
}
});
firebase.database()
.ref()
.child("todo")
.on("child_added", snapshot => {
const data = snapshot.val();
if (data){
this.setState(prevState => ({
noteArray: [data, ...prevState.noteArray]
}))
console.log(this.state.noteArray);
}
})
}
addNote(){
// firebase function here to send to the database
if (!this.state.noteText) return;
var d = new Date();
const newNote = firebase.database().ref()
.child("todo")
.push ({
'date':d.getFullYear()+
"/"+(d.getMonth()+1) +
"/"+ d.getDate(),
'note': this.state.noteText
});
newNote.set(this.state.noteText, () => this.setState({noteText: ''}))
}
render() {
let notes = this.state.noteArray.map((val, key)=>{
return
(<View key={key} keyval={key} val={val} style={styles.note}>
<Text style={styles.noteText}>{this.state.val.date}</Text>
<Text style={styles.noteText}>{this.state.val.note}</Text>
<TouchableOpacity onPress={this.state.deleteMethod} style={styles.noteDelete}>
<Text deleteMethod={()=>this.deleteNote(key)} style={styles.noteDeleteText}>D</Text>
</TouchableOpacity>
</View>)
});
return (
<View style={styles.container}>
<View style={styles.header}>
<Text style={styles.headerText}>Todo App</Text>
</View>
<ScrollView style={styles.scrollContainer}>
{notes}
</ScrollView>
<View style={styles.footer}>
<TextInput
style={styles.textInput}
placeholder='>note'
onChangeText={(noteText)=> this.setState({noteText})}
value={this.state.noteText}
placeholderTextColor='white'
underlineColorAndroid='transparent'>
</TextInput>
</View>
<TouchableOpacity onPress={ this.addNote } style={styles.addButton}>
<Text style={styles.addButtonText}>+</Text>
</TouchableOpacity>
</View>
);
}
deleteNote(key){
this.state.noteArray.splice(key, 1);
this.setState({noteArray: this.state.noteArray});
}
}
There is no warning or error, but it is not displaying anything. I will appreciate if there is any help and inline comment to understand the process for the next time, I am a newbie, trying to master the code for future similar projects. All I care to know is the basic understanding of the CRUD and search using React native firebase. Thank you so much
If I correctly understand you need a proper way to display your data. Since noteArray is an array, there's nothing easier than a FlatList, which is scrollable by itself.
So, in your render method:
render() {
return (
<View style={styles.container}>
<FlatList
data={this.state.noteArray} // Here is where you pass your array of data
renderItem={this.renderItem} // Here is how to display each item of your data array
ListHeaderComponent={this.renderHeader}
ListFooterComponent={this.renderFooter}
/>
</View>
);
}
Where:
renderHeader = () => {
return (
<View style={styles.header}>
<Text style={styles.headerText}>Todo App</Text>
</View>
)
}
renderFooter = () => {
return (
<View>
<View style={styles.footer}>
<TextInput
style={styles.textInput}
placeholder='>note'
onChangeText={(noteText)=> this.setState({noteText})}
value={this.state.noteText}
placeholderTextColor='white'
underlineColorAndroid='transparent'>
</TextInput>
</View>
<TouchableOpacity onPress={ this.addNote } style={styles.addButton}>
<Text style={styles.addButtonText}>+</Text>
</TouchableOpacity>
</View>
)
}
renderItem = ({ item, index }) => {
return (
<View key={index} style={styles.note}>
<Text style={styles.noteText}>{item.date}</Text>
<Text style={styles.noteText}>{item.note}</Text>
<TouchableOpacity onPress={this.state.deleteMethod} style={styles.noteDelete}>
<Text deleteMethod={()=>this.deleteNote(index)} style={styles.noteDeleteText}>D</Text>
</TouchableOpacity>
</View>
)
}
Thanks for your support. I have reviewed my code and it is working perfectly as I want. I will love to post it here in case someone else needs to work or learn about it. I used array.map() function to iterate over the items.
import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
TextInput,
ScrollView,
TouchableOpacity
} from 'react-native';
import Note from './Note';
import firebase from 'firebase';
// Initialize Firebase
const config = {
apiKey: "XXXXXXXXXXXXXXXXXXXXXXXXXX",
authDomain: "XXXXXXXXXXXXXXXXXXXXXX",
databaseURL: "XXXXXXXXXXXXXXXXXXXXXXXX",
projectId: "XXXXXXXXXXXXXXXXXXXXXXXXX",
storageBucket: "",
messagingSenderId: "XXXXXXXXXXXXXXXX"
};
firebase.initializeApp(config);
export default class Main extends Component {
constructor(props){
super(props);
this.state = {
noteArray: [],
noteText: '',
};
this.addNote = this.addNote.bind(this);
}
componentDidMount(){
firebase.database()
.ref()
.child("todo")
.once("value", snapshot => {
const data = snapshot.val()
if (snapshot.val()){
const initNoteArray = [];
Object
.keys(data)
.forEach(noteText => initNoteArray.push(data[noteText]));
this.setState({
noteArray: initNoteArray
});
}
});
firebase.database()
.ref()
.child("todo")
.on("child_added", snapshot => {
const data = snapshot.val();
if (data){
this.setState(prevState => ({
noteArray: [data, ...prevState.noteArray]
}))
console.log(this.state.noteArray);
}
})
}
addNote(){
// firebase function here to send to the database
if (!this.state.noteText) return;
var d = new Date();
const newNote = firebase.database().ref()
.child("todo")
.push ();
newNote.set({
'date':d.getFullYear()+
"/"+(d.getMonth()+1) +
"/"+ d.getDate(),
'note': this.state.noteText
});
this.setState({noteText:''});
}
render() {
let notes = this.state.noteArray.map((val, key)=>{
return <Note key={key} keyval={key} val={val}
deleteMethod={()=>this.deleteNote(key)}/>
});
return (
<View style={styles.container}>
<View style={styles.header}>
<Text style={styles.headerText}>Todo App</Text>
</View>
<ScrollView style={styles.scrollContainer}>
{notes}
</ScrollView>
<View style={styles.footer}>
<TextInput
style={styles.textInput}
placeholder='>note'
onChangeText={(noteText)=> this.setState({noteText})}
value={this.state.noteText}
placeholderTextColor='white'
underlineColorAndroid='transparent'>
</TextInput>
</View>
<TouchableOpacity onPress={ this.addNote } style={styles.addButton}>
<Text style={styles.addButtonText}>+</Text>
</TouchableOpacity>
</View>
);
}
deleteNote(key){
this.state.noteArray.splice(key, 1);
this.setState({noteArray: this.state.noteArray});
}
}
I have another .js component named Note.js for display template. This was included in the Main.js and was reference just after the render.
import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
TouchableOpacity,
} from 'react-native';
export default class Note extends Component {
render() {
return (
<View key={this.props.keyval} style={styles.note}>
<Text style={styles.noteText}>{this.props.val.date}</Text>
<Text style={styles.noteText}>{this.props.val.note}</Text>
<TouchableOpacity onPress={this.props.deleteMethod} style={styles.noteDelete}>
<Text style={styles.noteDeleteText}>D</Text>
</TouchableOpacity>
</View>
);
}
}

Want to pass data to other component - ListView

I have added and imported the sample data. I want to list out data from this file in a list view and I'm passing the data to the Row Component for RenderRow. But getting error saying
Row(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.
import React, { Component } from 'react';
import { AppRegistry, View, ListView, Text, StyleSheet } from 'react-native';
import Row from './app/Row';
import data from './app/Data';
export default class ListViewDemo extends Component {
constructor(props) {
super(props);
const rowHasChanged = (r1, r2) => r1 !== r2
const ds = new ListView.DataSource({rowHasChanged});
this.state = {
dataSource: ds.cloneWithRows(data),
};
render() {
return (
<ListView
dataSource={this.state.dataSource}
renderRow={(data) => <Row {...data} />} // Getting error here
/>
);
}
}
AppRegistry.registerComponent('DemoApp',() => ListViewDemo)
These my sample Data.js You can check the data here.
export default data = [
{...}, {...}
];
Row.js:
const Row = (props) => {
<View Style={styles.container}>
<Image source={{ uri: props.picture.large}} />
<Text >
{`${props.name.first} ${props.name.last}`}
</Text>
</View>
}
What would be the problem?
ES6 only returns when there is no explicit blocks:
const cb = (param) => param * 2;
You should explicitly return:
const Row = (props) => {
return (
<View Style={styles.container}>
<Image source={{ uri: props.picture.large}} />
<Text >
{`${props.name.first} ${props.name.last}`}
</Text>
</View>
);
}
Check this answer for further explanation.
Change this Line to
renderRow={(data) => <Row {...data} />}
To This
renderRow={(data) =><Row {...this.props} />}
This may help you to get props in the row Component

Open Webview on TouchableOpacity onPress React-Native

Presently I am using Linking but it is opening the url outside the app, I want this app to be opened within the app without showing the URL.
But unable to open Webview on TouchableOpecity onPress event in React-Native. Do I need to add a page and then open the page with URL ?
Can anyone please help.
I am considering the simplest of cases where i am rendering a single component and no navigator is being used.
class ABC extends Component {
constructor(props){
super(props)
this.state = {
check : false
}
}
renderWebView(){
if(this.state.check){
return(
<WebView
source={{uri: 'your url goes here'}}
style={{marginTop: 20}}
/>
);
}else {
return(
<TouchableOpacity
onPress={()=>this.setState({check: true})}>
<Text>Open WebView</Text>
</TouchableOpacity>
);
}
}
render() {
return (
<View style={{flex:1}}>
{this.renderWebView()}
</View>
);
}
}
You can use one of the Navigators and treat the webview component as one route.

Resources