Unable to enter text in ReactNative textbox - javascript

EDITED I am new to ReactNative and I am trying to write on my TextBoxes. However, I am not able to enter anything. I tried adding redux form for to signup screen. This is my Signup.js :
import React, { Component } from 'react';
import {StyleSheet, Text, View, StatusBar, TouchableOpacity} from 'react-native';
import {Field, reduxForm} from 'redux-form';
import Logo from '../components/Logo';
import Form from '../components/Form';
import InputText from '../components/InputText';
import {Actions} from 'react-native-router-flux';
const styles = StyleSheet.create({
container:{
backgroundColor: '#232122',
flex: 1,
alignItems: 'center',
justifyContent: 'center'
},
signupTextCont:{
flexGrow: 1,
alignItems:'flex-end',
justifyContent: 'center',
paddingVertical:16,
flexDirection:'row'
},
signupText: {
color:'rgba(255,255,255,0.7)',
fontSize:16
},
signupButton: {
color: '#FFA200',
fontSize:16,
fontWeight:'500'
},
button:{
width:300,
backgroundColor:'#FFA200',
borderRadius:25,
marginVertical:10,
paddingVertical: 13
},
buttonText:{
fontSize:16,
fontWeight:'500',
color:'#ffffff',
textAlign:'center'
},
errorText:{
color:"#FFA200",
fontSize:14,
paddingHorizontal:16,
paddingBottom: 8
}
});
class Signup extends Component<{}> {
goBack() {
Actions.pop();
}
createNewUser = () =>{
alert("Utilizador criado com sucesso!")
}
onSubmit = (values) => {
console.log(values);
}
renderTextInput = (field) => {
const {meta: {touched, error}, label, secureTextEntry, maxLength, keyboardType, placeholder, input: {onChange, ...restInput}} = field;
return(
<View>
<InputText
onChangeText={onChange}
maxLength={maxLength}
placeholder={placeholder}
keyboardType={keyboardType}
secureTextEntry={secureTextEntry}
label={label}
{...restInput} />
{touched && <Text style={styles.errorText}>{error}</Text>}
</View>
);
}
render() {
const {handleSubmit} = this.props;
return(
<View style={styles.container}>
<Logo/>
<Field
name="name"
placeholder="Insira o seu nome"
component={this.renderTextInput}/>
<Field
name="email"
placeholder="Insira o seu email"
component={this.renderTextInput}/>
<Field
name="password"
placeholder="Password"
secureTextEntry={true}
component={this.renderTextInput}/>
<TouchableOpacity style={styles.button} onPress={handleSubmit(this.onSubmit)}>
<Text style={styles.buttonText}>Signup</Text>
</TouchableOpacity>
<View style={styles.signupTextCont}>
<Text style={styles.signupText}>Ja tens uma conta?</Text>
<TouchableOpacity onPress={this.goBack}><Text style={styles.signupButton}> Entra</Text></TouchableOpacity>
</View>
</View>
)
}
}
const validate = (values) => {
const errors = {};
if(values.name){
errors.name = "Name is required"
}
if(values.email){
errors.email = "Email is required"
}
if(values.name){
errors.password = "Password is required"
}
return errors;
}
export default reduxForm({
form: "register",
validate
})(Signup)
And this is my InputText:
import PropTypes from "prop-types";
import React, {Component} from "react";
import {TextInput, Text, View, StyleSheet} from "react-native";
const propTypes = {
mapElement: PropTypes.func,
onSubmitEditing: PropTypes.func,
onChangeText: PropTypes.func,
value: PropTypes.string,
placeholder: PropTypes.string,
maxLength: PropTypes.number,
keyboardType: PropTypes.string,
secureTextEntry: PropTypes.bool,
label: PropTypes.string
};
const defaultProps = {
mapElement: (n) => {},
onSubmitEditing: () => {},
onChangeText: () => {},
value: "",
placeholder: "",
maxLength: 200,
keyboardType: "default",
secureTextEntry: false,
label: ""
};
const styles = StyleSheet.create({
inputBox: {
width:300,
backgroundColor:'rgba(255, 255,255,0.2)',
borderRadius: 25,
paddingHorizontal:16,
fontSize:16,
color:'#ffffff',
marginVertical: 10
}
});
class InputText extends Component <{}> {
render() {
const {placeholder, secureTextEntry, keyboardType, maxLength, value, onChangeText, onSubmitEditing} = this.props;
return (
<View>
<TextInput
style={styles.inputBox}
underlineColorAndroid="rgba(0,0,0,0)"
placeholder={placeholder}
placeholderTextColor="rgba(255,255,255,0.8)"
selectionColor="#999999"
secureTextEntry={secureTextEntry}
keyboardType={keyboardType}
maxLength={maxLength}
returnKeyType="next"
value={value}
onSubmitEditing={onSubmitEditing}
onChangeText={this.onChangeText} />
</View>
);
}
}
InputText.defaultProps = defaultProps;
InputText.propTypes = propTypes;
export default InputText;
I don't understand why this is happening. Please help me

<TextInput
style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
onChangeText={text => onChangeText(text)}
value={value}
/>
I think trying this method

Related

React Native onChange undefined

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;

TypeError: undefined is not an object (evaluating 'navigation.replace')

MY login page
import React, { useState } from 'react'
import { TouchableOpacity, StyleSheet, View, ImageBackground } from 'react-native'
import { Text } from 'react-native-paper'
import Logo from '../Component/Logo'
import Header from '../Component/Header'
import Button from '../Component/Button'
import TextInput from '../Component/Inputtext'
import BackButton from '../Component/Backbutton'
import { theme } from '../core/theme'
import { emailValidator } from '../Component/emailval'
import { passwordValidator } from '../Component/Passwordval'
export default function LoginScreen({ navigation }) {
const [email, setEmail] = useState({ value: '', error: '' })
const [password, setPassword] = useState({ value: '', error: '' })
const onLoginPressed = () => {
const emailError = emailValidator(email.value)
const passwordError = passwordValidator(password.value)
if (emailError || passwordError) {
setEmail({ ...email, error: emailError })
setPassword({ ...password, error: passwordError })
return
}
navigation.reset({
index: 0,
routes: [{ name: 'Dashboard' }],
})
}
return (
<ImageBackground style={styles.image} source={require('../imgs/back.png') }>
<View>
<BackButton />
<Logo />
<Header style={styles.header}>Welcome back.</Header>
<TextInput
label="Email"
returnKeyType="next"
value={email.value}
onChangeText={(text) => setEmail({ value: text, error: '' })}
error={!!email.error}
errorText={email.error}
autoCapitalize="none"
autoCompleteType="email"
textContentType="emailAddress"
keyboardType="email-address"
style={styles.textmail}
/>
<TextInput
label="Password"
returnKeyType="done"
value={password.value}
onChangeText={(text) => setPassword({ value: text, error: '' })}
error={!!password.error}
errorText={password.error}
secureTextEntry
style={styles.textmail}
/>
<View style={styles.forgotPassword}>
<TouchableOpacity
onPress={() => navigation.navigate('ResetPasswordScreen')}
>
<Text style={styles.forgot}>Forgot your password?</Text>
</TouchableOpacity>
</View>
<Button mode="contained" onPress={onLoginPressed} style={styles.login}>
Login
</Button>
<View style={styles.row}>
<Text>Don’t have an account? </Text>
<TouchableOpacity onPress={() => navigation.replace('login')}>
<Text style={styles.link}>Sign up</Text>
</TouchableOpacity>
</View>
</View>
</ImageBackground>
)
}
const styles = StyleSheet.create({
forgotPassword: {
width: '100%',
alignItems: 'flex-end',
marginBottom: 24,
},
row: {
flexDirection: 'row',
marginTop: 4,
},
forgot: {
fontSize: 13,
color: '#414757',
},
link: {
fontWeight: 'bold',
color: '#560CCE',
},
header: {
fontSize: 21,
color: '#560CCE',
fontWeight: 'bold',
paddingVertical: 12,
},
image: {
width:'100%',
height: '100%',
},
textmail:{
backgroundColor:"#ffffff",
width:"90%",
alignSelf:'center',
borderRadius:40,
},
login:{
width:"70%"
}
})
App js::
import React from 'react';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import OnboardingScreen from './Component/Onboardingscreen';
import LoginScreen from './Component/Loginscreen';
import Forgotpass from './Component/Forgotpassword';
import RegisterScreen from './Component/SignupScreen';
import AsyncStorage from '#react-native-async-storage/async-storage';
import { useEffect } from 'react';
const AppStack = createStackNavigator();
const App =() => {
const [isFirstLaunch, setIsFirstLaunch,] = React.useState(null);
useEffect(() => {
AsyncStorage.getItem('alreadyLaunched').then(value => {
if(value == null) {
AsyncStorage.setItem('alreadyLaunched','true');
setIsFirstLaunch(true);
} else {
setIsFirstLaunch(false);
}
});
}, []);
if (isFirstLaunch == null) {
return null;
} else if ( isFirstLaunch == true ){
return (
<NavigationContainer>
<AppStack.Navigator
headerMode='none'
>
<AppStack.Screen name="OnboardingScreen" component={OnboardingScreen}/>
<AppStack.Screen name='login' component={LoginScreen} />
<AppStack.Screen name="RegisterScreen" component={RegisterScreen} />
<AppStack.Screen name="ResetPasswordScreen" component={Forgotpass} />
</AppStack.Navigator>
</NavigationContainer>
);
} else {
return <LoginScreen />;
}
}
export default App;
Error occur while i pressing "forgot password" and "signup" ,
all dependency is addad ,
it shows onpress error and i added error screenshot also there are following below,
ERROR TypeError: undefined is not an object (evaluating 'navigation.replace')
ERROR TypeError: undefined is not an object (evaluating 'navigation.replace')
Try using the useNavigation() hook:
import { useNavigation } from '#react-navigation/native';
export default function LoginScreen() {
const navigation = useNavigation();
return (
...
<TouchableOpacity onPress={() => navigation.replace('login')}>
<Text style={styles.link}>Sign up</Text>
</TouchableOpacity>
...
);
}
Single data in a array is deleted in api data so it's show
null is a not an object
Solution:give the absent value = null;

React Native Expo Infinite Loading State

This is probably a dumb question, but I've been following some react native / expo tutorials on how to make a login screen with Firebase. The tutorial I followed also made a loading screen (using a loading state) that will display while Firebase is connecting. Unfortunately, the loading state never ends for me, and I don't know how to fix it.
Here is my Navigator.js file:
import React, { useReducer } from "react";
import { View, ActivityIndicator } from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from "#react-navigation/stack";
import { createDrawerNavigator } from "#react-navigation/drawer";
import { AuthContext } from '../contexts/UserContext';
import { firebase } from "../utils/FirebaseConfig";
import Login from "../screens/Login";
import Signup from "../screens/Signup";
import Home from "../screens/Home";
const Drawer = createDrawerNavigator();
const RootStack = createStackNavigator();
export default AppNavigation = (props) => {
const initialLoginState = {
isLoading: true,
user: null,
};
const loginReducer = (prevState, action) => {
switch (action.type) {
case 'LOGIN':
return {
...prevState,
user: action.user,
isLoading: false,
};
case 'LOGOUT':
return {
...prevState,
user: null,
isLoading: false,
};
case 'REGISTER':
return {
...prevState,
user: action.user,
isLoading: false,
};
}
};
const [loginState, dispatch] = useReducer(loginReducer, initialLoginState);
const authContext = React.useMemo(() => ({
signIn: async (email, password) => {
return firebase
.auth()
.signInWithEmailAndPassword(email, password)
.then(async (userCred) => {
dispatch({ type: 'LOGIN', user: userCred.user });
return true;
}).catch((error) => {
if (error.code === "auth/user-disabled") {
alert("User disabled!");
}
if (error.code === "auth/invalid-email") {
alert("That email address is invalid!");
}
if (error.code === "auth/user-not-found") {
alert("User not found, please sign up!");
}
if (error.code === "auth/wrong-password") {
alert("Wrong password!");
}
return false;
})
},
signOut: async () => {
return firebase.auth().signOut().then(async () => {
dispatch({ type: 'LOGOUT' });
});
},
signUp: (email, password) => {
return firebase.auth().createUserWithEmailAndPassword(email, password).then((userCred) => {
dispatch({ type: 'REGISTER', user: userCred.user });
}).catch((error) => {
if (error.code === "auth/email-already-in-use") {
alert("That email address is already in use!");
}
if (error.code === "auth/invalid-email") {
alert("That email address is invalid!");
}
if (error.code === "auth/operation-not-allowed") {
alert("Operation is not allowed!");
}
if (error.code === "auth/weak-password") {
alert("The password is too weak!");
}
return false;
})
}
}), []);
if (loginState.isLoading) {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<ActivityIndicator size="large" color="grey" />
</View>
);
}
return (
<AuthContext.Provider value={authContext}>
<NavigationContainer>
{loginState.user !== null ? (
<Drawer.Navigator >
<Drawer.Screen name="Home" user={loginState.user} component={Home} />
</Drawer.Navigator>
) :
(
<RootStack.Navigator headerMode='none'>
<RootStack.Screen name="Login" component={Login} />
<RootStack.Screen name="Signup" component={Signup} />
</RootStack.Navigator>
)
}
</NavigationContainer>
</AuthContext.Provider>
)
}
Here is my Home.js File:
import React from 'react';
import { useContext } from 'react';
import { Text, TouchableOpacity, View } from 'react-native';
import { AuthContext } from "../contexts/UserContext";
function Home(props) {
const { signOut } = useContext(AuthContext);
return (
<View style={{ flex: 1 }}>
<Text>Welcome</Text>
<Text>Email: {props.user?.email}</Text>
<Text>uid: {props.user?.uid}</Text>
<Text>displayName: {props.user?.displayName}</Text>
<Text>photo: {props.user?.photoURL}</Text>
<TouchableOpacity onPress={() => signOut()} style={{ flexDirection: "row", alignItems: "center", justifyContent: "center", width: "100%" }} >
<Text style={{ fontWeight: "bold", fontSize: 18 }}>Logout</Text>
</TouchableOpacity>
</View>
);
}
export default Home;
Here is the Login.js file:
import React, { useContext, useState } from 'react';
import { KeyboardAvoidingView, View, Text, TextInput } from 'react-native';
import { AuthContext } from "../contexts/UserContext";
function Login(props) {
const [data, setData] = useState({
email: "",
password: ""
})
const { signIn } = useContext(AuthContext);
const emailInputChange = (val) => {
setData({
...data,
email: val
})
}
const passwordChange = (val) => {
setData({
...data,
password: val
});
}
const LoginHandle = () => {
signIn(data.email, data.password)
}
return (
<KeyboardAvoidingView>
<View style={{ flex: 1 }}>
<Text>Email: </Text>
<View >
<TextInput
placeholder="Email"
autoCapitalize="none"
onChangeText={(val) => emailInputChange(val)}
/>
</View>
<Text>Password: </Text>
<View>
<TextInput
placeholder="Password"
autoCapitalize="none"
secureTextEntry={true}
onChangeText={(val) => passwordChange(val)}
/>
</View>
<TouchableOpacity onPress={() => LoginHandle()} style={{ width: "100%", height: 50, justifyContent: "center", alignItems: "center", borderRadius: 10 }}>
<Text style={{ color: "#FFF", fontSize: 18, fontWeight: "bold" }}>Login</Text>
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
);
}
export default Login;
And finally, the Signup.js file:
import React, { useContext, useState } from 'react';
import { KeyboardAvoidingView, View, Text, TextInput } from 'react-native';
import { AuthContext } from "../contexts/UserContext";
function Signup(props) {
const [data, setData] = useState({
email: "",
password: ""
})
const { signUp } = useContext(AuthContext);
const emailInputChange = (val) => {
setData({
...data,
email: val
})
}
const passwordChange = (val) => {
setData({
...data,
password: val
});
}
const SignupHandle = () => {
signUp(data.email, data.password)
}
return (
<KeyboardAvoidingView>
<View style={{ flex: 1 }}>
<Text>Email: </Text>
<View >
<TextInput
placeholder="Email"
autoCapitalize="none"
onChangeText={(val) => emailInputChange(val)}
/>
</View>
<Text>Password: </Text>
<View>
<TextInput
placeholder="Password"
autoCapitalize="none"
secureTextEntry={true}
onChangeText={(val) => passwordChange(val)}
/>
</View>
<TouchableOpacity onPress={() => SignupHandle()} style={{ width: "100%", height: 50, justifyContent: "center", alignItems: "center", borderRadius: 10 }}>
<Text style={{ color: "#FFF", fontSize: 18, fontWeight: "bold" }}>Signup</Text>
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
);
}
export default Signup;

Getting JSON Parse error: Unexpected identifier "undefined" when using React native & React navigation?

I am pretty new to React Native, so if the question seems stupid i am sorry in advance, i have been trying for hours to get this to work before asking this question.
I am trying to pass data from a text input to the next screen using firebase database.
I keep getting the error JSON Parse error: Unexpected identifier "undefined", I have attached below my two files, one with the text input (InputForm.js) and the other one which i want to show that data on the screen (ASTConfig1screen)
If anyone can help with this you really are a superstar!
InputForm.js
import React, { Component } from 'react';
import { StyleSheet, ScrollView, ActivityIndicator, View, TextInput } from 'react-native';
import { Button } from 'react-native-elements';
import firebase from '../Firebase';
import { withNavigation } from 'react-navigation';
class InputForm extends Component {
constructor() {
super();
this.ref = firebase.firestore().collection('boards');
this.state = {
name: '',
inventoryclass: '',
outlet: '',
isLoading: false,
};
}
updateTextInput = (text, field) => {
const state = this.state
state[field] = text;
this.setState(state);
}
saveBoard() {
this.setState({
isLoading: true,
});
this.ref.add({
name: this.state.name,
inventoryclass: this.state.inventoryclass,
outlet: this.state.outlet,
}).then((docRef) => {
this.setState({
name: '',
outlet: '',
inventoryclass: '',
isLoading: false,
});
this.props.navigation.navigate('ASTConfig1');
})
.catch((error) => {
console.error("Error adding document: ", error);
this.setState({
isLoading: false,
});
});
}
render() {
if(this.state.isLoading){
return(
<View style={styles.activity}>
<ActivityIndicator size="large" color="#ffa500"/>
</View>
)
}
return (
<ScrollView style={styles.container}>
<View style={styles.subContainer}>
<TextInput style={styles.inputtext}
placeholder={'Name'}
placeholderTextColor="white"
value={this.state.name}
onChangeText={(text) => this.updateTextInput(text, 'name')}
/>
</View>
<View style={styles.subContainer}>
<TextInput style={styles.inputtext}
multiline={true}
numberOfLines={4}
placeholder={'Inventory Class'}
placeholderTextColor="white"
value={this.state.inventoryclass}
onChangeText={(text) => this.updateTextInput(text, 'inventoryclass')}
/>
</View>
<View style={styles.subContainer}>
<TextInput style={styles.inputtext}
placeholder={'Outlet'}
placeholderTextColor="white"
value={this.state.outlet}
onChangeText={(text) => this.updateTextInput(text, 'outlet')}
/>
</View>
<View style={styles.button}>
<Button
large
leftIcon={{name: 'save'}}
title='Save'
onPress={() => this.saveBoard()} />
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20
},
subContainer: {
flex: 1,
marginBottom: 20,
padding: 5,
borderBottomWidth: 2,
borderBottomColor: '#CCCCCC',
},
inputtext: {
color: 'white',
fontSize: 20
},
activity: {
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0,
alignItems: 'center',
justifyContent: 'center'
}
})
export default withNavigation(InputForm);
and this is where i would like to show the data on this screen
ASTConfig1.js
import React from 'react';
import {
View,
Text,
StyleSheet,
Button,
ImageBackground,
StatusBar,
SafeAreaView,
TextInput,
ScrollView,
UIManager,
ActivityIndicator
}
from 'react-native';
import {AccordionList} from "accordion-collapse-react-native";
import { Separator } from 'native-base';
import {widthPercentageToDP as wp, heightPercentageToDP as hp} from 'react-native-responsive-screen';
import firebase from '../Firebase';
import Logo from '.././components/Logo';
import Colors from '.././constants/Colors';
import Search from '.././components/Search';
import InputForm from '.././components/InputForm';
class ASTConfig1Screen extends React.Component {
static navigationOptions = {
title: 'ASTConfig1',
};
constructor(props) {
super(props);
this.state= {
isLoading: true,
board: {},
key: '',
status:true,
text: '',
list:[
{
title: 'Getting Started',
body: 'React native Accordion/Collapse component, very good to use in toggles & show/hide content'
},
{
title: 'Components',
body: 'AccordionList,Collapse,CollapseHeader & CollapseBody'
},
{
title: 'Test',
body: 'AccordionList,Collapse,CollapseHeader & CollapseBody'
}
],
}
}
componentDidMount() {
const { navigation } = this.props;
const ref = firebase.firestore().collection('boards').doc(JSON.parse(navigation.getParam('boardkey')));
ref.get().then((doc) => {
if (doc.exists) {
this.setState({
board: doc.data(),
key: doc.id,
isLoading: false
});
} else {
console.log("No such document!");
}
});
}
_head(item){
return(
<Separator bordered style={{alignItems:'center'}}>
<Text>{item.title}</Text>
</Separator>
);
}
_body(item){
return (
<View style={{padding:10}}>
<Text style={{textAlign:'center'}}>{item.body}</Text>
</View>
);
}
ShowHideTextComponentView = () =>{
if(this.state.status == true)
{
this.setState({status: false})
}
else
{
this.setState({status: true})
}
}
render() {
if(this.state.isLoading){
return(
<View style={styles.activity}>
<ActivityIndicator size="large" color="#0000ff" />
</View>
)
}
return (
<View style={styles.screen}>
<ImageBackground
source={require('.././assets/Img/BackGround2.png')}
style={styles.background}>
</ImageBackground>
<SafeAreaView>
<View style={{flex: 1, justifyContent: 'space-between', width: wp('80%')}}>
<View style={styles.logotop}>
<Logo/>
</View>
<View style={styles.editstock}>
<Text style={styles.editstocktext}>EDIT STOCK LIST:</Text>
</View>
{/*Start of 3 buttons Firebase*/}
<View style={styles.three}>
<View style={styles.edit1}>
<Text style={styles.textheader}>{this.state.board.name}</Text>
<Button style={styles.edit} title='Edit' ></Button>
</View>
<View style={{padding: 3}}></View>
<View style={styles.edit2}>
<Text style={styles.text}>{this.state.board.inventoryclass}</Text>
<Button style={styles.edit} title='Edit' ></Button>
</View>
<View style={styles.edit3}>
<Text style={styles.text}>{this.state.board.outlet}</Text>
<Button style={styles.edit} title='Edit' ></Button>
</View>
</View>
{/*End of 3 buttons Firebase*/}
{/*Start of AccordionList*/}
<ScrollView>
<View style={styles.middle}>
<AccordionList
list={this.state.list}
header={this._head}
body={this._body}
/>
</View>
</ScrollView>
{/*End of AccordionList*/}
{/*Start of Search*/}
<View>
{
this.state.status ? null : <View style={styles.bottom}>
<Text style={styles.textbottom}>SEARCH FOR NEW ITEMS:</Text>
<Search />
</View>
}
<Button title="ADD" onPress={this.ShowHideTextComponentView} />
</View>
</View>
</SafeAreaView>
</View>
);
};
};
{/*End of Search*/}
export default ASTConfig1Screen;
but it returns the error - Error adding document: [SyntaxError: SyntaxError: SyntaxError: JSON Parse error: Unexpected identifier "undefined"
in inputform.js saveBoard function you should
this.props.navigation.navigate('Details', {
'ASTConfig1': docRef
});
and remove JSON.parse form other file

Clear TextInput onPress()

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})}
/>

Categories