I have this chat screen in my app where I am sending a message with the help of a button next to it and with its onPress(),
Here is the code:
import React, { Component } from "react";
import {
View,
Text,
StyleSheet,
TextInput,
Button,
Image,
TouchableOpacity,
Picker,
AsyncStorage
} from "react-native";
import axios from "axios";
import { Dropdown } from "react-native-material-dropdown";
import { Input } from "native-base";
class MessageForm extends Component {
state = {
message: "",
rc_id: this.props.rc_id,
usertype: this.props.usertype,
senderid: this.props.userid,
subject: this.props.subject
};
sendMessage = async () => {
console.log(
this.state.rc_id,
this.state.usertype,
this.state.senderid,
this.state.message,
this.state.subject
);
try {
let { data } = await axios
.post("https://tgesconnect.org/api/Communicate_class", {
userid: this.state.rc_id,
usertype: this.state.usertype,
message: this.state.message,
senderid: this.state.senderid,
subject: this.state.subject
})
.then(response => {
console.log(response.data);
this.setState({
message: ""
});
});
} catch (err) {
console.log(err);
}
};
render() {
return (
<View>
<View style={styles.container}>
<Input
style={styles.textInput}
placeholder={this.props.message}
underlineColorAndroid="transparent"
onChangeText={message => {
this.setState({ message });
}}
/>
<TouchableOpacity
style={styles.button}
onPress={() => {
this.sendMessage();
}}
>
<Image source={require("../../Assets/Images/ic_send.png")} />
</TouchableOpacity>
</View>
</View>
);
}
}
export default MessageForm;
const styles = StyleSheet.create({
container: {
display: "flex",
flexDirection: "row",
minWidth: "100%",
backgroundColor: "#eeeeee",
borderTopColor: "#cccccc",
borderTopWidth: 1,
flex: 1,
justifyContent: "flex-end"
},
textInput: {
flex: 1,
backgroundColor: "#ffffff",
height: 40,
margin: 10,
borderRadius: 5,
padding: 3
},
button: {
flexShrink: 0,
width: 40,
height: 40,
marginTop: 10,
marginRight: 10,
marginBottom: 10,
alignItems: "center",
justifyContent: "center"
},
container1: {
flex: 1,
alignItems: "center",
justifyContent: "center"
}
});
Now when I click on the Touchable icon, the textbox is not getting cleared, I don't understand why it is not happening.
I have changed the state again to have a blank text but still it is not happening.
Bind the input value with the state.
<Input
style={styles.textInput}
placeholder={this.props.message}
underlineColorAndroid="transparent"
onChangeText={message => {this.setState({ message });}}
value={this.state.message}
/>
You can use useState.
just import by import {useState} from "react";
const [text, setText] = useState("");
const onChange = (textValue) => setText(textValue);
return (
<View style={styles.container}>
<TextInput
placeholder="Item"
style={styles.text}
onChangeText={onChange}
value={text}
/>
<TouchableOpacity
style={styles.btn}
onPress={() => {
//addItem.addItem(text);
setText("");
}}
>
<Text>Add</Text>
</TouchableOpacity>
</View>
);
<TextInput
style={styles.textInput}
placeholder="Start to type.."
multiline={true}
maxLength={3000}
value={this.state.sms}
onChangeText={(sms)=>this.setState({sms})}
/>
Related
I want to input a value, which will be compared to my dummy data, and once the value is compared, i'll get an alert if the value is matched or not
//UPDATE - I have made some changes to the code, not the alert is working, but the values are not being matched. only getting the second alert - Error.
import { View, Text, FlatList, TextInput, StyleSheet, TouchableOpacity, Button } from 'react-native'
import React, {useState} from 'react'
import { CATEGORIES } from '../DummyData/dummy-data'
const renderGridItem = (itemData) =>{
return (
<View style={{marginVertical:5,marginVertical:15, flex:1, margin:15}}>
<Text style={{color:'black'}}>
{itemData.item.id}
</Text>
</View>
)
}
const Meals = props => {
const [text, onChangeText] = useState();
var onClick = () => {
if (renderGridItem === text){
alert("ID Matched");
}
else{
alert('Error')
}
}
console.log(text)
return (
<View>
<FlatList keyExtractor={(item, index) => item.id}
data={CATEGORIES}
numColumns={2}
renderItem={renderGridItem} />
<TextInput
style={styles.tip}
placeholder='Enter CNIC'
keyboardType='default'
onChangeText={onChangeText}
value={text}
/>
<TouchableOpacity style={styles.top} onPress={() => { ()=>onChangeText(text); onClick()} }>
<Text style={{textAlign:'center'}}>
Enter
</Text>
</TouchableOpacity>
</View>
)
}
const styles = StyleSheet.create({
tip:{
borderWidth:1,
marginVertical:50,
borderRadius:8
},
top:{
width:'30%',
borderWidth:1,
marginLeft:140,
padding: 10,
borderRadius:8
},
})
export default Meals
//Dummy-Data (Array)
import Data from "../Model/Data";
export const CATEGORIES = [
new Data('c1', 'Person 1', '#f5428d'),
new Data('c3', 'Person 2', '#f5a442'),
];
//Data
class Data {
constructor(id, title){
this.id=id,
this.title=title
}
}
export default Data
Please check the code it might be helpful to you.
import React, { useState, useEffect } from "react";
import {
StyleSheet,
SafeAreaView,
TextInput,
View,
Text,
Button,
TouchableOpacity,
} from "react-native";
const App = () => {
const [text, setText] = useState("");
function onPressButton() {
var result = DATA.some((item, index) => item.title == text);
if (result == true) {
alert("DATA Found");
} else {
alert("DATA not found");
}
}
return (
<SafeAreaView style={{ flex: 1 }}>
<View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
<TextInput
style={{ borderBottomWidth: 1, width: "90%", padding: 10 }}
placeholder="Enter Title"
onChangeText={(text) => setText(text)}
/>
<TouchableOpacity
style={{
width: 100,
height: 50,
borderWidth: 1,
justifyContent: "center",
alignItems: "center",
borderRadius: 10,
marginTop: 20,
}}
onPress={onPressButton}
>
<Text>Find</Text>
</TouchableOpacity>
</View>
</SafeAreaView>
);
};
const DATA = [
{ id: 1, title: "ABC" },
{ id: 2, title: "XYZ" },
];
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "white",
},
});
export default App;
OUTPUT:
so I am trying to perform some onChange event, as I learned, but somehow it throws me the error that the onChange function is undefined. The right dependency is installed (react-hook-form).
Here is my code.
Someone a idea, where the issue is coming from?
https://codesandbox.io/embed/jolly-butterfly-diqb1?fontsize=14&hidenavigation=1&theme=dark
import React from "react";
import {
StyleSheet,
TextInput,
Text,
TouchableOpacity,
Image,
ScrollView
} from "react-native";
import { useForm, Controller } from "react-hook-form";
const AddAddress = () => {
const { control, handleSubmit, errors, reset } = useForm({
defaultValues: {
name: "",
email: ""
}
});
function submit(data) {
console.log(data);
}
return (
<ScrollView contentContainerStyle={styles.container}>
<Text style={styles.title}>React Hook Form</Text>
<Controller
control={control}
name="name"
render={({ onChange, value }) => (
<TextInput
placeholder="Name"
style={styles.input}
onChangeText={(value) => onChange(value)}
/>
)}
/>
<Controller
control={control}
name="email"
render={({ onChange, value }) => (
<TextInput
placeholder="Email"
style={styles.input}
onChangeText={(value) => onChange(value)}
/>
)}
/>
<TouchableOpacity onPress={handleSubmit(submit)}>
<Text style={styles.button}>Submit</Text>
</TouchableOpacity>
</ScrollView>
);
};
export default AddAddress;
It is because you are passing the onChange function dirctly, but it is a part of the field prop, so you should pass them as a named argument
...Controller
render={({
field: { onChange, onBlur, value, name, ref },
fieldState: { invalid, isTouched, isDirty, error },
}) => ( ...
Kindly have a look at the docs : https://react-hook-form.com/api/usecontroller/controller
Or pass in the value field, and use the field.onChange method.
This is the modified code.
The output on submit will be as follows after providing the inputs
{name: "sample", email: "sample#g,co"}
import React from "react";
import {
StyleSheet,
TextInput,
Text,
TouchableOpacity,
Image,
ScrollView
} from "react-native";
import { useForm, Controller } from "react-hook-form";
const AddAddress = () => {
const { control, handleSubmit, errors, reset } = useForm({
defaultValues: {
name: "",
email: ""
}
});
function submit(data) {
console.log(data);
}
return (
<ScrollView contentContainerStyle={styles.container}>
<Text style={styles.title}>React Hook Form</Text>
<Controller
control={control}
name="name"
// ------------ modified here
render={({field}) => (
<TextInput
placeholder="Name"
style={styles.input}
onChange = {(e)=>field.onChange(e)}
value = {field.value}
/>
)}
/>
<Controller
control={control}
name="email"
// ------------ modified here
render={({ field }) => (
<TextInput
placeholder="Email"
style={styles.input}
onChange = {(e)=>field.onChange(e)}
value = {field.value}
/>
)}
/>
<TouchableOpacity onPress={handleSubmit(submit)}>
<Text style={styles.button}>Submit</Text>
</TouchableOpacity>
</ScrollView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#282828",
alignItems: "center",
justifyContent: "center"
},
title: {
fontSize: 36,
marginBottom: 30,
marginTop: 16,
color: "white"
},
error: {
fontSize: 16,
color: "red",
marginTop: 16,
marginBottom: 16,
marginLeft: 36,
marginRight: 36
},
input: {
fontSize: 18,
borderWidth: 1,
padding: 12,
width: "80%",
borderRadius: 10,
backgroundColor: "white",
marginBottom: 16,
marginTop: 16
},
image: {
width: 120,
height: 120,
borderColor: "orange",
borderWidth: 2,
borderRadius: 100
},
button: {
fontSize: 20,
color: "white",
width: 120,
marginTop: 8,
borderRadius: 10,
backgroundColor: "#c01c00",
padding: 8,
textAlign: "center"
}
});
export default AddAddress;
I'm quite new to react native and trying to set up a search bar with search functionality. I'm trying to set it up where the list updates with each letter typed. The data is displayed fine but the error occurs when I try and type something into the search bar.
Full Error Message
https://ibb.co/Zd5hB52
Here is the file that is having issues
import { StyleSheet, Text, View, Button, StatusBar, ScrollView, TextInput } from "react-native";
import Icon from 'react-native-vector-icons/Ionicons';
import datas from "../components/CurrencyData"
import FavouritesList from "../components/FavouritesList";
const AddToFavourites = () => {
const state = {
datas: datas,
filter: datas
}
const [currencyFilter, setSearch] = useState(state.filter)
const getFlags = () => {
return currencyFilter.map(data => {
return <FavouritesList detail={data} key={data.id}/>
})
}
const searchCurrencies = (searchFor) => {
setSearch({
filterCurrency: datas.filter(i=>
i.name.toLowerCase().includes(searchFor.toLowerCase),
),
});
}
return (
<View style={styles.container}>
<View style= {styles.action}>
<Icon name="search" size={25}/>
<TextInput
style= {{flex: 1}}
placeholder= "Search..."
underlineColorAndroid="transparent"
onChangeText= {text => {searchCurrencies(text)}}
/>
</View>
<ScrollView>
<StatusBar backgroundColor="#1E90FF" barStyle="light-content"/>
{getFlags()}
</ScrollView>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
justifyContent: "center",
},
action: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
borderWidth: 2,
height: 50,
borderRadius: 30,
paddingLeft: "4%",
paddingRight: "4%",
margin: "3%"
},
})
export default AddToFavourites;```
[1]: https://i.stack.imgur.com/kWkHo.png
with hooks you don't pass the state object like setState, you just pass the new value
change
setSearch({
filterCurrency: datas.filter(i => i.name.toLowerCase().includes(searchFor.toLowerCase)),
});
to
setSearch( datas.filter(I =>i.name.toLowerCase().includes(searchFor.toLowerCase)));
Hi I'm getting the error undefined is not an object(evaluating 'navigation.navigate') after I'm submitting the form. I searched many google/stackoverflow answers but none of them helped me.
I'm not sure if this is cause by firebase or actual prop navigation. Any insights on this ???
Please see the code below:
// parent component
import React from 'react';
import { StyleSheet, Text, View, Image } from 'react-native';
import LoginForm from '../components/LoginForm';
const Login = () => {
return (
<View style={styles.mainWrapper}>
<Image style={styles.logo} title="Logo" source={require('../assets/box.png')}/>
<LoginForm/>
</View>
);
}
const styles = StyleSheet.create({
logo: {
width: 150,
height: 150,
marginTop: 55
},
mainWrapper: {
display: "flex",
alignItems: "center"
}
});
export default Login;
// login form component
import React, { useState } from 'react';
import { StyleSheet, Text, View, TextInput, TouchableOpacity, Alert} from 'react-native';
import firebase from 'firebase/app';
import 'firebase/auth';
import { firebaseConfig } from '../config';
if(!firebase.apps.length){
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
}
const auth = firebase.auth();
const LoginForm = ({navigation}) => {
const [email,setEmail] = useState('');
const [password, setPassword] = useState('');
const signIn = async() => {
try {
let response = await auth.signInWithEmailAndPassword(email,password);
if(response.user){
Alert.alert('logged in' + response.user.email);
navigation.navigate('Driver');
}
}catch(e){
Alert.alert(e.message);
}
};
return (
<View style={styles.formView}>
<TextInput
value={email}
placeholder="Email"
style={styles.input}
onChangeText={userEmail => setEmail(userEmail)}
autoCapitalize='none'
keyboardType='email-address'
autoCorrect={false}
/>
<TextInput
value={password}
placeholder="Password"
secureTextEntry={true}
style={styles.input}
onChangeText={userPassword => setPassword(userPassword)}
/>
<TouchableOpacity style={styles.submitBtn} title="Login" onPress={() => signIn()}>
<Text style={styles.appButtonText}>Login</Text>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
formView: {
marginTop: 45,
display: "flex",
alignItems: "center",
},
input: {
marginTop: 20,
width: 300,
height: 40,
paddingHorizontal: 10,
borderRadius: 5,
backgroundColor: 'white',
},
submitBtn: {
backgroundColor: "#FFE17D",
color: "#E6646E",
fontWeight: "bold",
width: 150,
height: 40,
marginTop: 20,
borderColor: "#E6646E",
borderRadius: 5,
display: "flex",
justifyContent: "center",
borderWidth: 1,
},
appButtonText: {
fontSize: 18,
color: "#E6646E",
fontWeight: "bold",
alignSelf: "center",
textTransform: "uppercase"
}
});
Only the stack screens have access to the props navigation. You can try sending navigation to LoginForm but that works only if Login is a Stack Screen.
const Login = ({navigation}) => {
return (
<View style={styles.mainWrapper}>
<Image style={styles.logo} title="Logo" source={require('../assets/box.png')}/>
<LoginForm navigation={navigation}/>
</View>
);
}
Or you can have a look in the useNavigation hook
I was trying to make a "photo galley app" where each image is a "button" that toggle on the boolean property for Modal tag. The problem is that the images are rendered by a FlatList which pass props to component "GenerateImage.js", but at the same time, I need to pass the state and dispatch function as a parameter as well.
File who render the FlatList:
import React, { Component } from 'react'
import { FlatList, View, StyleSheet, TouchableOpacity, Text, AppRegistry } from 'react-native'
import { connect } from 'react-redux'
import GenerateImage from '../components/GenerateImage'
import commonStyles from '../commonStyles'
import Modal from '../components/Modal'
const Photos = ({ params }) => {
return (
<View style={{ flex: 1 }}>
<Modal isVisible={params.showFullImage} />
<View style={styles.buttonsContainer}>
<TouchableOpacity style={styles.touchContainer}>
<Text style={styles.button}>Hoje</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.touchContainer}>
<Text style={styles.button}>Mês</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.touchContainer}>
<Text style={styles.button}>Ano</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.touchContainer}>
<Text style={styles.button}>Álbuns</Text>
</TouchableOpacity>
</View>
<View style={{ flex: 30 }}>
<FlatList data={params.images} keyExtractor={item => `${item.id}`}
renderItem={({item}) => <GenerateImage {...item} />} numColumns={2} />
</View>
</View>
)
}
const styles = StyleSheet.create({
buttonsContainer: {
flex: 3,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#1c2431',
},
touchContainer: {
marginHorizontal: 20,
backgroundColor: '#439ce8',
borderRadius: 30,
width: 65,
alignItems: 'center',
justifyContent: 'center',
padding: 5
},
button: {
color: 'white',
fontFamily: commonStyles.Font,
fontSize: 14
}
})
export default connect(state => ({ params: state[0] }))(Photos)
GenerateImage.js:
import React from 'react'
import { View,
StyleSheet,
Image,
PixelRatio,
Dimensions,
TouchableOpacity } from 'react-native'
import { connect } from 'react-redux'
const GenerateImage = (props, {param, dispatch}) => {
function toggleModal(param) {
return {
type: 'TOGGLE_MODAL_ON',
}
}
return (
<View style={styles.container}>
<View style={styles.imgContainer}>
<TouchableOpacity activeOpacity={0.7} onPress={() => dispatch(toggleModal(param))}>
<Image source={props.image} style={styles.imgContainer} />
</TouchableOpacity>
</View>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
marginVertical: 5,
marginHorizontal: 4
},
imgContainer: {
height: Dimensions.get('window').height * 0.25,
width: Dimensions.get('window').width * 0.48,
//borderRadius: 8,
//flex: 1,
//orderWidth: 1,
},
image: {
resizeMode: 'contain',
aspectRatio: PixelRatio.get()
},
})
export default connect(state => ({ param: state[0].showFullImage }))(GenerateImage)
So, how can I pass both data?