cant submit form formik and react-native-elements - react-native

I didn't do a whole a lot of work on react-native to being with but the formik and react-native-elements is not getting anywhere with my setup. I am not really sure what I am missing exactly. Basically, the form cannot be submitted. I have a reusable button and input components made out of react native elements. The form don't get submitted. Out of curiousity, I also tried RN's default button to submit the form but it also doesn't work. My sandbox is here.
My setup is pretty straight forward as you can see below. Any help would be great on what I am missing exactly:
FormInput.js:
import React, { Component } from "react";
import { View, StyleSheet } from "react-native";
import { Input } from "react-native-elements";
export default class FormInput extends Component {
render() {
let { name, ...rest } = this.props;
return (
<>
<View>
<Input name={name} {...rest} />
</View>
</>
);
}
}
FormButton.js
import React, { Component } from "react";
import { Button } from "react-native-elements";
export default class FormButton extends Component {
render() {
let { title, ...rest } = this.props;
return (
<>
<Button title={title} {...rest} onPress={() => this.props.onPress} />
</>
);
}
}
App.js:
import React, { Component, Fragment } from "react";
import { Alert, Button, Image, StyleSheet, Text, View } from "react-native";
import FormInput from "./components/forms/FormInput";
import FormButton from "./components/forms/FormButton";
import * as yup from "yup";
import { Formik } from "formik";
class App extends Component {
handleSubmit = values => {
console.log("submitted values ", values);
};
render() {
return (
<View style={styles.app}>
<Formik
initialValues={{
name: ""
}}
onSubmit={values => {
this.handleSubmit(values);
}}
validationSchema={yup.object().shape({
name: yup
.string()
.min(3)
.max(25)
.required()
})}
>
{({
values,
handleChange,
errors,
setFieldTouched,
touched,
isValid,
handleBlur,
handleSubmit
}) => (
<Fragment>
<FormInput
name="name"
onChangeText={handleChange("name")}
onBlur={handleBlur("name")}
autoFocus
/>
<Button
onPress={() => handleSubmit}
title="React Native Button"
/>
<FormButton
title="React native elements child button"
onPress={() => handleSubmit}
/>
</Fragment>
)}
</Formik>
</View>
);
}
}
export default App;

Can you post the error if exist? And did you make a method for submit button so that it can pass the value ?

In you App.js you're buttons onPress should be like below:
<Button
onPress={handleSubmit}
title="React Native Button"
/>
<FormButton
title="React native elements child button"
onPress={handleSubmit}
/>
Your onPress do not need to be an annonymous function.

Related

RESOLVED React navigation not working react native

I am just giving a console.log (data) and navigating to another screen.
but I'm having the following error:
Component Exception
undefined is not an object
what am I doing wrong?
NOTE: When I use, navigation.goBack() works.
code below;
the error persists
Can anyone help me??
CODE UPDATED
import React, { useRef } from 'react';
import { useNavigation } from '#react-navigation/native';
import { Form } from '#unform/mobile';
import {
KeyboardAvoidingView,
Platform,
ScrollView,
Image,
} from 'react-native';
import logo from '../../assets/logo.png';
import Input from '../../components/Input';
import Button from '../../components/Button';
import { Container, FormContainer, Title, TitleContainer } from './styles';
export default function SignUp() {
const formRef = useRef(null);
const navigation = useNavigation();
const handleSignUp = data => {
console.log(data);
navigation.navigate('SignUpPersonalData', { data });
};
return (
<>
<KeyboardAvoidingView
style={{ flex: 1 }}
behavior={Platform.OS === 'ios' && 'padding'}
enabled
>
<ScrollView keyboardShouldPersistTaps="handled">
<Container>
<Image source={logo} />
<TitleContainer>
<Title>Crie sua conta</Title>
</TitleContainer>
<Form ref={formRef} onSubmit={handleSignUp}>
<Input
autoCorrect={false}
autoCapitalize="none"
keyboardType="email-address"
name="email"
icon="mail"
placeholder="E-mail"
/>
<Input
secureTextEntry
returnKeyType="send"
name="password"
icon="lock"
placeholder="Senha"
/>
<Button onPress={() => formRef.current.submitForm()}>
Continuar
</Button>
</Form>
</Container>
</ScrollView>
</KeyboardAvoidingView>
</>
);
Screenshot error:
SX
don't use useCallback, try the following.
const handleSignUp = (data) =>{
console.log(data);
navigation.navigate('SignUpPersonalData',{data: data});
}

How do i make so the TextInput clears after submit in react native

I have a TextInput in my code that doesn't clear itself after submit and i have no idea on why it does that or how to solve it. I've looked at other posts that has this kinda issue? but none works or i don't really know where to place the code to make it clear itself after submiting.
Code
import React, { useState } from 'react';
import {
StyleSheet,
Text,
View,
TextInput,
Button,
} from 'react-native';
export default function AddList({ submitHandler }) {
const [text, setText] = useState('');
const changeHandler = (val) => {
setText(val);
}
return(
<View style={styles.container}>
<View style={styles.wrapper}>
<TextInput
style={styles.input}
placeholder='text'
onChangeText={changeHandler}
/>
<Button onPress={() => submitHandler(text)} title='ADD' color='#333' />
</View>
</View>
);
}
Simply create a new function after useState as below:
const onSubmit = useCallback(() => {
if (submitHandler) submitHandler(text)
setText("")
}, [text])
and modify textinput and button as below:
<TextInput
style={styles.input}
placeholder='What Tododay?'
onChangeText={changeHandler}
value={text}
/>
<Button
onPress={onSubmit}
title='ADD TO LIST'
color='#333'
/>
Do not forget to import useCallback from react.
I hope it help you.

React Native - Navigation with functional components

I installed Navigation to take some data from a page and send to another (hopefully I will).
But it doesn't work and I get
"We couldn't find a navigation object. Is your component inside a navigator?"
File Insert.js
import React, { useState } from "react";
import { createAppContainer } from "react-navigation";
import { createStackNavigator } from "react-navigation-stack";
import { useNavigation } from "#react-navigation/native";
import ViewData from "./ViewData";
const MainNavigator = createStackNavigator({
ViewDataPage: ViewData
});
...
const Insert = props => {
...
createAppContainer(MainNavigator);
const navigate = useNavigation();
return (
<TouchableWithoutFeedback
onPress={() => {
Keyboard.dismiss();
}}
>
<View style={styles.inputContainer}>
<Input
placeholder="Your Name"
onChangeText={text => setEnteredName(text)}
value={enteredName}
/>
...
<View>
<Button
title="Submit"
onPress={() => sendValues(enteredName, enteredSurname)}
/>
<Button
title="Click"
onPress={() =>navigate("ViewDataPage", { name: "Jane" })
}
/>
</View>
</View>
</TouchableWithoutFeedback>
I think I made a mess, I can't even get the page "ViewData".
I would like to change page sending some values in the hooks
Any idea where I mistook?
"#react-navigation/native" is for React Navigation 5. You can't use it with React Navigation 4.

How to call my toast (native-base) anywhere of my code?

I am using base-native (https://docs.nativebase.io/Components.html#toast-def-headref) with this code a toast is generated.
import React, { Component } from 'react';
import { Container, Header, Content, Toast, Button, Text } from 'native-base';
export default class ToastExample extends Component {
render() {
return (
<Container>
<Header />
<Content padder>
<Button onPress={()=> Toast.show({
text: 'Wrong password!',
buttonText: 'Okay'
})}>
<Text>Toast</Text>
</Button>
</Content>
</Container>
);
}
}
I want to call it from anywhere in my code, for example
handlerToast= ()=>{
Toast.show({
text: 'Wrong password!',
buttonText: 'Okay'
})
}
If I put it into a function I get errors,like this:
<Button onPress={()=> this.handlerToast()}
</Button>
what can I do?
As described in native base doc :
For Toast to work, you need to wrap your topmost component inside from native-base.
So, wrap your topmost component with native base <Root> as below :
import { Root } from "native-base";
import { StackNavigator } from "react-navigation";
const AppNavigator = StackNavigator(
{
Page: { screen: Page },
}
);
export default () =>
<Root>
<AppNavigator />
</Root>;
In recent version of native-base NativeBaseProvider
is used instead of Root
import {NativeBaseProvider} from 'native-base';
export default () =>
<NativeBaseProvider>
<App/>
</NativeBaseProvider>;

Identifier has already been declared react native

So I have created a simple react-native following the Coursera lectures.
My Menu component just holds a list of recipes and displays them on the device.
import React, { Component } from 'react';
import { View, FlatList } from 'react-native';
import { ListItem } from 'react-native-elements';
function Menu(props){
const renderMenuItem = ({item, index}) => {
return(
<ListItem
key={index}
title={item.name}
subtitle={item.description}
hideChevron={true}
onPress={() => props.onPress(item.id)}
leftAvatar={{ source: require('./images/uthappizza.png')}}
/>
);
}
return(
<FlatList
data={props.dishes}
renderItem={renderMenuItem}
keyExtractor={item => item.id.toString()}
/>
)
}
export default Menu;
Next, there is the DishdetailComponent which renders the details of each dish.
import React from 'react';
import { Text, View } from 'react-native';
import { Card } from 'react-native-elements';
function RenderDish(props) {
const dish = props.dish;
if (dish != null) {
return(
<Card
featuredTitle={dish.name}
image={require('./images/uthappizza.png')}>
<Text style={{margin: 10}}>
{dish.description}
</Text>
</Card>
);
}
else {
return(<View></View>);
}
}
function Dishdetail(props) {
return(<RenderDish dish={props.dish} />);
}
export default Dishdetail;
And finally, I have the MainComponent which is like the top component holding the two previous components.
import { View } from 'react-native';
import { DISHES } from '../shared/dishes';
import Dishdetail from './DishdetailComponent';
class Main extends Component {
constructor(props){
super(props);
this.state = {
dishes: DISHES,
selectedDish: null
};
}
onDishSelect(dishId) {
this.setState({selectedDish: dishId})
}
render(){
return(
<View style={{flex:1}}>
<Menu dishes={this.state.dishes} onPress={(dishId) => this.onDishSelect(dishId)} />
<Dishdetail dish={this.state.dishes.filter((dish) => dish.id === this.state.selectedDish)[0]} />
</View>
);
}
}
export default Main;
When I run the app I get this
Did I miss something? Here is my repo if you want to have a closer look.
Few moments here:
1) Seems you forgot to import the Menu component at the top of imports
2) You simply have a typo in the import of DishdetailComponent
Just paste these lines instead of yours
import { View } from "react-native";
import { DISHES } from "../shared/dishes";
import Dishdetail from "./DishDetailComponent";
import Menu from "./MenuComponent";
Also, sometimes bunder crashes and don't reload.
To fix this I would suggest using
yarn start --reset-cache command (but don't forget to kill previous Metro Bundler instance) :)