I have a react native app with expo-client and gives a too-many re-renders error I will post the files, notice that I use react-native-paper.
This is App.js which is a wrapper for app
import React from "react";
import { Provider as PaperProvider, DefaultTheme } from "react-native-paper";
import { StatusBar } from "expo-status-bar";
import Homescreen from "./views/screens/homescreen";
//import { SafeAreaView, Text } from "react-native";
export default function App() {
return (
<PaperProvider theme={theme}>
<Homescreen />
<StatusBar />
</PaperProvider>
);
}
const theme = {
...DefaultTheme,
};
This is the homescreen which is a wrapper for login and sign up components
import React from "react";
import { View } from "react-native";
import { NavigationContainer } from "#react-navigation/native";
import { createStackNavigator } from "#react-navigation/stack";
import SignUp from "../components/signup";
import Login from "../components/login";
import { Button } from "react-native-paper";
export default function Homescreen({ navigation }) {
const Stack = createStackNavigator();
return (
<View>
<Button onPress={() => navigation.navigate("SignUp")}>SignUp</Button>
<Button onPress={() => navigation.navigate("LogIn")}>Login</Button>
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="SignUp" component={SignUp} />
<Stack.Screen name="LogIn" component={Login} />
</Stack.Navigator>
</NavigationContainer>
</View>
);
}
There are sign up and login components which are very identical
import React, { useState } from "react";
import { View } from "react-native";
import { TextInput, Button } from "react-native-paper";
export default function SignUp() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const signUp = (t1, t2) => {
setEmail("");
setPassword("");
};
const changeEmailHandler = (e) => {
setEmail(e.target.value);
};
const changePasswordHandler = (e) => {
setPassword(e.target.value);
};
return (
<View>
<TextInput
mode="outlined"
left
label="email"
placeholder="Enter your email: "
onChangeText={changeEmailHandler}
value={email}
/>
<TextInput
mode="outlined"
left
label="password"
placeholder="Enter your password: "
onChangeText={changePasswordHandler}
value={password}
type="password"
/>
<Button
icon="arrow-right-alt"
mode="contained"
onClick={signUp(email, password)}
>
Join us now
</Button>
</View>
);
}
import React, { useState } from "react";
import { View } from "react-native";
import { TextInput, Button } from "react-native-paper";
export default function Login() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const logIn = (t1, t2) => {
setEmail("");
setPassword("");
};
const changeEmailHandler = (e) => {
setEmail(e.target.value);
};
const changePasswordHandler = (e) => {
setPassword(e.target.value);
};
return (
<View>
<TextInput
mode={outlined}
left
label="email"
placeholder="Enter your email: "
onChangeText={changeEmailHandler}
value={email}
/>
<TextInput
mode={outlined}
left
label="password"
placeholder="Enter your password: "
onChangeText={changePasswordHandler}
value={password}
type="password"
/>
<Button
icon="arrow-right-alt"
mode="contained"
onClick={logIn(email, password)}
></Button>
</View>
);
}
This is the appbar component
import React from "react";
import { View } from "react-native";
import { Appbar } from "react-native-paper";
export default function CustomAppBar() {
return (
<View>
<Appbar>
<Appbar.Header>
<Appbar.Content title="Date Planner" />
</Appbar.Header>
</Appbar>
</View>
);
}
The onClick event in the <Button> is the problem. It calls signUp(email, password) on every render which causes an infinite loop because inside there is a call for setPassword. Instead in onClick you can pass a callback, see my suggestion below.
You need to modify your button as:
<Button
icon="arrow-right-alt"
mode="contained"
onClick={() => signUp(email, password)}
>
Join us now
</Button>
In this way the signUp function will be called only on click event.
Based on the comment also needs to change onClick={logIn(email, password)} as well similarly as suggested above.
Related
I am building a RegisterScreen for my app and I have this child component called `LogResContainer' where I have a component that I share between my login and my register screens.
The thing is I think I am calling everything as it should be called and I don't know what's wrong anymore.
Here is the RegisterScreen.js:
import {
KeyboardAvoidingView,
StyleSheet,
Text,
TextInput,
TouchableOpacity,
View
} from 'react-native'
import React, {useState}from 'react'
import { createUserWithEmailAndPassword } from 'firebase/auth';
import { auth } from '../firebase.js';
import { styles } from '../styles/styles.js';
import {LogResContainer} from './LogResContainer.js';
const RegisterScreen = () => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const handleSignup = () => {
createUserWithEmailAndPassword(auth, email, password)
.then(userCredential => {
const user = userCredential.user;
console.log(user.email);
})
.catch(error => alert(error.message));
}
console.log(setEmail);
console.log(setPassword);
console.log(handleSignup);
console.log("Registrar");
return (
<LogResContainer
setEmail={setEmail}
setPassword={setPassword}
type='Registrar'
func={handleSignup}
/>
);
}
export default RegisterScreen
And here is LogResContainer.js:
import {styles} from '../styles/styles.js';
export default LogResContainer = ({setEmail, setPassword, type, func}) => {
return (
<KeyboardAvoidingView style={styles.container} behavior="padding">
<View style={styles.inputContainer}>
<TextInput
placeholder="Email"
value={email}
onChangeText={(text) => setEmail(text)}
style={styles.input}
/>
<TextInput
placeholder="Password"
value={password}
onChangeText={(text) => setPassword(text)}
style={styles.input}
secureTextEntry
/>
</View>
<View style={styles.buttonContainer}>
<TouchableOpacity onPress={func} style={styles.button}>
<Text style={styles.buttonText}>{type}</Text>
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
);
};
I have studied the props docs and looked at multiple youtube videos but I am pretty much exhausted. Don't know what I am missing.
You export LogResContainer as default export, but try to import it like a named export.
Either change the export to a named export:
export const LogResContainer = () => <>"I am a named export"</>
Or change the import to import the default:
import LogResContainer from "./LogResContainer.js"
And if you don't know the difference between named and default exports, read it here: https://www.geeksforgeeks.org/what-is-export-default-in-javascript/
And please add the errors you get, so we can help you better.
I have implemented AWS custom UI authenctication in my react native app and React navigation to navigate through the different screens.
While implementing the logical conditions to see if the "User is already logged in or not" I have assigned the screen "Home" for logged in user and screen 'Login' for not logged in user it's working fine and navigating as expected but the console is showing this error when clicking on login button.
ERROR The action 'NAVIGATE' with payload {"name":"Home"} was not handled by any navigator.
Here is the Navigation code:
import React, {useEffect, useState} from 'react'
import {ActivityIndicator, Alert, View} from 'react-native';
import HomeScreen from '../screens/HomeScreen';
import LoginScreen from '../screens/LoginScreen';
import RegisterScreen from '../screens/RegisterScreen';
import ConfirmEmailScreen from '../screens/ConfirmEmailScreen';
import ForgotPassword from '../screens/ForgotPassword';
import NewPasswordScreen from '../screens/NewPasswordScreen';
import { NavigationContainer } from '#react-navigation/native'
import { createNativeStackNavigator } from '#react-navigation/native-stack';
import {Auth, Hub} from 'aws-amplify';
const Stack = createNativeStackNavigator();
const Navigation = () => {
const [user, setUser] = useState(undefined);
//Checking if user is already logged in or not!
const checkUser = async () => {
try {
const authUser = await Auth.currentAuthenticatedUser({bypassCache: true});
setUser(authUser);
} catch(e) {
setUser(null);
}
};
useEffect(() => {
checkUser();
}, []);
useEffect(() => {
const listener = data => {
if (data.payload.event === 'signIn' || data.payload.event === 'signOut') {
checkUser();
}
}
Hub.listen('auth', listener);
return () => Hub.remove('auth', listener);
}, []);
if (user === undefined) {
return (
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<ActivityIndicator/>
</View>
);
}
return (
<NavigationContainer>
<Stack.Navigator>
{/*{If user is logged in navigate him to Homescreen else go throght the Screens based on the user selection */}
{user ? (
<Stack.Screen name='Home' component={HomeScreen}/>
) : (
<>
<Stack.Screen name='Login' component={LoginScreen}/>
<Stack.Screen name='Register' component={RegisterScreen}/>
<Stack.Screen name='ConfirmEmail' component={ConfirmEmailScreen}/>
<Stack.Screen name='ForgotPassword' component={ForgotPassword}/>
<Stack.Screen name='NewPassword' component={NewPasswordScreen}/>
</>
)}
</Stack.Navigator>
</NavigationContainer>
);
};
export default Navigation;
Here is the Login Screen:
import React, {useState} from 'react'
import { View, Text, Image, StyleSheet, useWindowDimensions, TouchableWithoutFeedback, Keyboard, Alert, KeyboardAvoidingView, ScrollView } from 'react-native'
import Logo from '../../../assets/images/logo-main.png'
import CustomButton from '../../components/CustomButton/CustomButton';
import CustomInput from '../../components/CustomInput/CustomInput';
import { useNavigation } from '#react-navigation/native';
import {Auth} from 'aws-amplify';
import {useForm} from 'react-hook-form';
const LoginScreen = () => {
const [loading, setLoading] = useState(false);
const {height} = useWindowDimensions();
const {control, handleSubmit, formState: {errors}} = useForm();
const navigation = useNavigation();
const onLoginPressed = async (data) => {
if(loading) {
return;
}
setLoading(true);
try {
await Auth.signIn(data.username, data.password);
navigation.navigate('Home');
} catch(e) {
Alert.alert('Opps', e.message)
}
setLoading(false);
};
const onForgotPasswordPressed = () => {
navigation.navigate('ForgotPassword');
}
const onRegisterPressed = () => {
navigation.navigate('Register')
}
return (
<KeyboardAvoidingView behavior={Platform.OS === "ios" ? "padding" : "height"} style={styles.container}>
<ScrollView contentContainerStyle={{flexGrow:1, justifyContent:'center'}} showsVerticalScrollIndicator={false}>
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<View style={styles.root}>
<Image source={Logo} style={[styles.logo, {height : height * 0.2}]} resizeMode={'contain'} />
<CustomInput icon='user' name='username' placeholder='Username' control={control} rules={{required: 'Username is required'}} />
<CustomInput icon='lock' name='password' placeholder='Password' control={control} rules={{required: 'Password is required'}} secureTextEntry={true} />
<CustomButton text={loading ? 'Loading...' : 'Login Account'} onPress={handleSubmit(onLoginPressed)} />
<CustomButton text='Forgot Password?' onPress={onForgotPasswordPressed} type='TERTIARY' />
<CustomButton text="Don't have an account? Create one" onPress={onRegisterPressed} type='TERTIARY' />
</View>
</TouchableWithoutFeedback>
</ScrollView>
</KeyboardAvoidingView>
);
};
const styles = StyleSheet.create({
root: {
alignItems: 'center',
padding: 20,
},
logo: {
width: 200,
maxWidth: 300,
maxHeight: 300,
},
});
export default LoginScreen;
Issue
At the time you are calling navigation.navigate('Home') there is no screen called in Home in Navigation because of that ternary that checks whether there is a user or not and renders conditionally your screens. That's why React Naviagation is not happy.
Solution
React Navigation's documention tell us that we shouldn't "manually navigate when conditionally rendering screens". Means you should find a way to call setUser(user) in Login where setUser is the state setter from Navigation component.
To do so we can use a context and for that change Navigation as follow (I added comments where I changed things):
import React, { createContext, useEffect, useState } from "react";
import { ActivityIndicator, View } from "react-native";
import ConfirmEmailScreen from "../screens/ConfirmEmailScreen";
import ForgotPassword from "../screens/ForgotPassword";
import HomeScreen from "../screens/HomeScreen";
import LoginScreen from "../screens/LoginScreen";
import NewPasswordScreen from "../screens/NewPasswordScreen";
import RegisterScreen from "../screens/RegisterScreen";
import { NavigationContainer } from "#react-navigation/native";
import { createNativeStackNavigator } from "#react-navigation/native-stack";
import { Auth, Hub } from "aws-amplify";
const Stack = createNativeStackNavigator();
// Line I added
export const AuthContext = createContext(null);
const Navigation = () => {
const [user, setUser] = useState(undefined);
//Checking if user is already logged in or not!
const checkUser = async () => {
try {
const authUser = await Auth.currentAuthenticatedUser({ bypassCache: true });
setUser(authUser);
} catch (e) {
setUser(null);
}
};
useEffect(() => {
checkUser();
}, []);
useEffect(() => {
const listener = (data) => {
if (data.payload.event === "signIn" || data.payload.event === "signOut") {
checkUser();
}
};
Hub.listen("auth", listener);
return () => Hub.remove("auth", listener);
}, []);
if (user === undefined) {
return (
<View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
<ActivityIndicator />
</View>
);
}
return (
// Wrapper I added
<AuthContext.Provider value={{ user, setUser }}>
<NavigationContainer>
<Stack.Navigator>
{/*{If user is logged in navigate him to Homescreen else go throght the Screens based on the user selection */}
{user ? (
<Stack.Screen name="Home" component={HomeScreen} />
) : (
<>
<Stack.Screen name="Login" component={LoginScreen} />
<Stack.Screen name="Register" component={RegisterScreen} />
<Stack.Screen name="ConfirmEmail" component={ConfirmEmailScreen} />
<Stack.Screen name="ForgotPassword" component={ForgotPassword} />
<Stack.Screen name="NewPassword" component={NewPasswordScreen} />
</>
)}
</Stack.Navigator>
</NavigationContainer>
</AuthContext.Provider>
);
};
export default Navigation;
Consume AuthContext from Navigation in Login so you are able to call setUser after login, like below (I added comments where I changed thing):
import { useNavigation } from "#react-navigation/native";
import React, { useContext, useState } from "react";
import {
Alert,
Image,
Keyboard,
KeyboardAvoidingView,
ScrollView,
StyleSheet,
TouchableWithoutFeedback,
useWindowDimensions,
View,
} from "react-native";
import Logo from "../../../assets/images/logo-main.png";
import CustomButton from "../../components/CustomButton/CustomButton";
import CustomInput from "../../components/CustomInput/CustomInput";
import { Auth } from "aws-amplify";
import { useForm } from "react-hook-form";
// Line I added
import {AuthContext} from "./Navigation" // ⚠️ use the correct path
const LoginScreen = () => {
// Line I added
const { setUser } = useContext(AuthContext);
const [loading, setLoading] = useState(false);
const { height } = useWindowDimensions();
const {
control,
handleSubmit,
formState: { errors },
} = useForm();
const navigation = useNavigation();
const onLoginPressed = async (data) => {
if (loading) {
return;
}
setLoading(true);
try {
const user = await Auth.signIn(data.username, data.password);
// Line I added
setUser(user);
} catch (e) {
Alert.alert("Opps", e.message);
}
setLoading(false);
};
const onForgotPasswordPressed = () => {
navigation.navigate("ForgotPassword");
};
const onRegisterPressed = () => {
navigation.navigate("Register");
};
return (
<KeyboardAvoidingView
behavior={Platform.OS === "ios" ? "padding" : "height"}
style={styles.container}
>
<ScrollView
contentContainerStyle={{ flexGrow: 1, justifyContent: "center" }}
showsVerticalScrollIndicator={false}
>
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<View style={styles.root}>
<Image
source={Logo}
style={[styles.logo, { height: height * 0.2 }]}
resizeMode={"contain"}
/>
<CustomInput
icon="user"
name="username"
placeholder="Username"
control={control}
rules={{ required: "Username is required" }}
/>
<CustomInput
icon="lock"
name="password"
placeholder="Password"
control={control}
rules={{ required: "Password is required" }}
secureTextEntry={true}
/>
<CustomButton
text={loading ? "Loading..." : "Login Account"}
onPress={handleSubmit(onLoginPressed)}
/>
<CustomButton
text="Forgot Password?"
onPress={onForgotPasswordPressed}
type="TERTIARY"
/>
<CustomButton
text="Don't have an account? Create one"
onPress={onRegisterPressed}
type="TERTIARY"
/>
</View>
</TouchableWithoutFeedback>
</ScrollView>
</KeyboardAvoidingView>
);
};
const styles = StyleSheet.create({
root: {
alignItems: "center",
padding: 20,
},
logo: {
width: 200,
maxWidth: 300,
maxHeight: 300,
},
});
I keep getting an error when I run my app, and the screen is just white.
ERROR Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem., js engine: hermes
ERROR Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication). A frequent cause of the error is that the application entry file path is incorrect.
This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native., js engine: hermes
ERROR Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication). A frequent cause of the error is that the application entry file path is incorrect.
This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native., js engine: hermes
Full code is available on my GitHub, but let I'll past the areas of the code I was fiddling with:
https://github.com/astuertz/hashtagValues/commits/master
First, here's my store.js:
import { configureStore } from '#reduxjs/toolkit';
import activeImgReducer from '../features/counter/activeImgSlice';
import userAuthReducer from '../features/counter/userAuthSlice';
export default configureStore({
reducer: {
activeImg: activeImgReducer,
user: userAuthReducer
}
})
Here's my index.js:
/**
* #format
*/
import React from 'react';
import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
import store from './src/app/store';
import { Provider } from 'react-redux';
const reduxApp = () => (
<Provider store={store}>
<App />
</Provider>
);
AppRegistry.registerComponent(appName, () => reduxApp);
And my App.js (without styles):
import React from 'react';
import {View, Text, StyleSheet} from 'react-native';
import Navigation from './src/components/routes/navigation';
import Amplify from 'aws-amplify';
import config from './src/aws-exports';
import { withAuthenticator } from 'aws-amplify-react-native';
Amplify.configure({
...config,
Analytics: {
disabled: true,
},
});
const App = () => {
return (
<View style={styles.root}>
<Navigation />
</View>
);
};
Here's my navigation.js (everything from the root stack down--the root stack has several other stacks nested in it):
const RootStack = createNativeStackNavigator();
const RootStackScreen = () => {
const [isLoading, setIsLoading] = useState(true);
const [user, setUser] = useState(null);
useEffect(() => {
setTimeout(() => {
setIsLoading(!isLoading);
setUser('user');
}, 2500)
}, []);
return (
<RootStack.Navigator screenOptions={{
animationEnabled: false,
headerShown: false,
presentation: 'modal',
}}>
{isLoading ? (
<RootStack.Screen name="LoadingScreen" component={LoadingScreen} />
) : user ? (
<RootStack.Screen name="AppTabs" component={AppTabsScreen} />
) : (
<RootStack.Screen name="AuthStackScreen" component={AuthStackScreen} />
)}
<RootStack.Screen name="Gallery" component={GalleryScreen} options={{
animationEnabled: true,
cardStyle: {
backgroundColor: 'black',
},
}}/>
</RootStack.Navigator>
);
};
export default () => {
return (
<NavigationContainer>
<RootStackScreen />
</NavigationContainer>
);
};
I now have it back to the way I had it before the error started occurring.
The only other thing I was messing with is the Sign In Screen and the Profile Screen (with Sign Out). Here's the Sign In Screen:
import React, {useState} from 'react';
import {
View,
Text,
StyleSheet,
Image,
Dimensions,
TextInput,
Button,
TouchableWithoutFeedback,
Keyboard,
TouchableOpacity,
Alert,
} from 'react-native';
import logo from '../../graphics/Values_logo.png';
import { useNavigation } from '#react-navigation/native';
import { Auth } from 'aws-amplify';
import { useSelector, useDispatch, } from 'react-redux';
import { validateUser } from '../../features/counter/userAuthSlice';
const WIDTH = Dimensions.get("window").width;
const HEIGHT = Dimensions.get("window").height;
const SignIn = () => {
const navigation = useNavigation();
const dispatch = useDispatch();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const onPressSignIn = async () => {
if (email.length < 1 || password.length < 1) return Alert.alert('no input', 'please input an email and password to log in.');
try {
const u = await Auth.signIn(email, password);
dispatch(validateUser(u));
} catch(e) {
Alert.alert('Login Failed!', e.message);
return;
}
Alert.alert('Login Successful!');
return;
}
const renderLogo = (
<Image
source={logo}
style={styles.logoSize}
resizeMode='contain'
/>
);
const inputElements = (
<>
<TextInput
placeholder='email'
value={email}
onChangeText={setEmail}
style={styles.textInput}
/>
<TextInput
placeholder='password'
value={password}
onChangeText={setPassword}
style={styles.textInput}
secureTextEntry={true}
/>
<TouchableOpacity
onPress={onPressSignIn}
style={styles.button}
>
<Text style={styles.buttonText}>Sign In</Text>
</TouchableOpacity>
<Text
style={styles.hyperlink}
>Forgot Password?</Text>
<Text
style={styles.hyperlink}
onPress={() => navigation.push("SignUp")}
>Sign Up</Text>
</>
);
return (
<TouchableWithoutFeedback
onPress={() => Keyboard.dismiss()}>
<View style={styles.pageContainer}>
<View style={styles.logo}>
{renderLogo}
</View>
<View style={styles.inputContainer} >
{inputElements}
</View>
</View>
</TouchableWithoutFeedback>
);
}
And the Profile Screen:
import React from 'react';
import {View, Text, StyleSheet, Button, Alert,} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Auth } from 'aws-amplify';
import { useSelector, useDispatch, } from 'react-redux';
import { signOutUser } from '../../features/counter/userAuthSlice';
const dispatch = useDispatch();
const onSignOut = async () => {
try {
await Auth.signOut();
dispatch(signOutUser());
} catch (error) {
Alert.alert('error signing out: ', error.message);
return;
}
Alert.alert('Sign Out Successful!');
}
const ProfileScreen = () => {
return (
<SafeAreaView style={styles.pageContainer}>
<Text>ProfileScreen</Text>
<Button title="Sign Out" onPress={onSignOut} />
</SafeAreaView>
);
};
const styles = StyleSheet.create({
root: {
flex: 1
},
pageContainer: {
justifyContent: 'center',
alignItems: 'center',
flex: 1,
width: '100%'
}
});
export default ProfileScreen;
I'm really not sure what I did to break my app or how to fix it.
In Profile Screen, you are calling const dispatch = useDispatch(); which is outside of the component and is an invalid call. It has to be called in inside ProfileScreen. When you are not sure where the problem occurs try commenting you code and see if it works without them. Like commenting your screens one by one would help you find which screen the error is caused in etc.
Hey I have tried a lot of things but I can't seem to get this thing to work I am trying to make a simple modal using material UI but whenever I try to change state it's showing me a blank white page. does anyone have any idea why is it happening here's my code
a
import {Button,Modal} from "#material-ui/core";
import {useState} from "react";
import RegisterBody from '../Register/RegisterForm'
import LoginBody from '../Login/LoginForm'
const UserModel = () => {
const [isOpen, setIsOpen] = useState(false)
const [isLoginModel, setLoginModel] = useState();
const [MainModelBody] = useState(LoginBody);
function handleRegister() {
if (!isLoginModel) {
console.log("Register")
//Todo: Send Register Request
} else {
MainModelBody.setState(RegisterBody)
setLoginModel(false)
}
}
function handleSignIn() {
if (isLoginModel) {
console.log("Login")
//Todo: send Sign in request
} else {
MainModelBody.setState(LoginBody)
setLoginModel(true)
}
}
function handleUserModel() {
setIsOpen(!isOpen)
}
return (
<>
<Button className="userActionButton" onClick={handleUserModel}>Sign In</Button>
<Modal open={isOpen}
onClose={!isOpen}
disablePortal
disableEnforceFocus
disableAutoFocus
aria-labelledby="simple-modal-title"
aria-describedby="simple-modal-description"
>
<div className = 'UserModel'>
<LoginBody/>
<Button onClick={handleRegister}>Register</Button>
<Button onClick={handleSignIn}>Sign In</Button>
</div>
</Modal>
</>
);
}
export default UserModel
LoginBody
import {useState} from 'react';
import LoginElements from './LoginElements';
import {FormControl} from "#material-ui/core";
const LoginForm = ()=> {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const handleSubmit = (e) => {
e.preventDefault();
const user = {email, password}
console.log(user)
};
return (
<div className="form">
<FormControl noValidate autoComplete="off" onSubmit={handleSubmit}>
<LoginElements
email={email}
password={password}
setEmail={setEmail}
setPassword={setPassword}
/>
</FormControl>
</div>
);
}
export default LoginForm;
LoginElements
import {Button, TextField} from "#material-ui/core";
const LoginElements = (props) => {
return (
<>
<TextField label="Email" type="email" required value={props.email} onChange={(e) => props.setEmail(e.target.value)}/>
<br/>
<TextField label="Password" type="password" required value={props.password} onChange={(e) => props.setPassword(e.target.value)}/>
<br/>
<Button variant="contained" type="submit">Login</Button>
<Button variant="contained" type="register">Register</Button>
<br/>
<label>{props.email}</label>
<label>{props.password}</label>
</>
)
}
export default LoginElements;
RegisterBody
import {useState} from 'react';
import RegisterElements from './RegisterElements';
const LoginForm = ()=> {
const [email, setEmail] = useState('')
const [confirmEmail, setConfirmEmail] = useState('')
const [password, setPassword] = useState('')
const [confirmPassword, setConfirmPassword] = useState('')
const handleSubmit = (e) => {
e.preventDefault();
const user = {email, password}
console.log(user)
};
return (
<div className="form">
<form noValidate autoComplete="off" onSubmit={handleSubmit}>
<RegisterElements
email={email}
confirmEmail={email}
password={password}
confirmPassword={password}
setEmail={setEmail}
setConfirmEmail={setEmail}
setPassword={setPassword}
setConfirmPassword={setPassword}
/>
</form>
</div>
);
}
export default LoginForm;
Register Elements
import {Button, TextField} from "#material-ui/core";
const RegisterElements = (props) => {
return (
<>
<TextField label="Confirm Email" type="email" required value={props.email}
onChange={(e) => props.setEmail(e.target.value)}/>
<TextField label="Confirm Email" type="email" required value={props.confirmEmail}
onChange={(e) => props.setConfirmEmail(e.target.value)}/>
<br/>
<TextField label="Password"
type="password"
required value={props.password}
onChange={(e) => props.setPassword(e.target.value)}/>
<TextField label="Confirm Password" required value={props.confirmPassword}
onChange={(e) => props.setConfirmPassword(e.target.value)}/>
<br/>
<Button variant="contained" type="Login">Login</Button>
<Button variant="contained" type="submit">Login</Button>
<label>{props.email}</label>
<label>{props.password}</label>
</>
)
}
export default RegisterElements;
My apologies for bad code i am new with react
You are "toggling" the isLoginModel state but you only render LoginBody in the JSX.
You should be able to use the isLoginModel state and conditionally render either the LoginBody or RegisterBody component into the modal body. There's really no need for the extra state to hold a component reference.
import {Button,Modal} from "#material-ui/core";
import {useState} from "react";
import RegisterBody from '../Register/RegisterForm'
import LoginBody from '../Login/LoginForm'
const UserModel = () => {
const [isOpen, setIsOpen] = useState(false)
const [isLoginModel, setLoginModel] = useState(true); // login by default
function handleRegister() {
if (!isLoginModel) {
console.log("Register");
// TODO: Send Register Request
} else {
setLoginModel(false);
}
}
function handleSignIn() {
if (isLoginModel) {
console.log("Login");
// TODO: send Sign in request
} else {
setLoginModel(true);
}
}
function handleUserModel() {
setIsOpen(isOpen => !isOpen);
}
return (
<>
<Button className="userActionButton" onClick={handleUserModel}>Sign In</Button>
<Modal open={isOpen}
onClose={!isOpen}
disablePortal
disableEnforceFocus
disableAutoFocus
aria-labelledby="simple-modal-title"
aria-describedby="simple-modal-description"
>
<div className='UserModel'>
{isLoginModel ? <LoginBody /> : <RegisterBody />} // <-- condition render
<Button onClick={handleRegister}>Register</Button>
<Button onClick={handleSignIn}>Sign In</Button>
</div>
</Modal>
</>
);
}
This is App.js using react-navigation. There are two screens on it called HomeScreen and AddScreen.
import * as React from 'react';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import HomeScreen from './src/HomeScreen';
import AddScreen from './src/AddScreen';
const Stack = createStackNavigator();
function App() {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Add" component={AddScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
export default App;
And This is home Screen. There is a 'items' in 'useState. It is gived through Add by navigation as props.
import * as React from 'react';
import PropTypes from 'prop-types';
import { View, Text, Button } from 'react-native';
function HomeScreen({ navigation, route }) {
const [items, setItems] = React.useState([]);
React.useEffect(() => {
if (route.params?.items) {
// Post updated, do something with `route.params.post`
// For example, send the post to the server
console.log('saved');
}
}, [route.params?.items]);
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button
title="Create post"
onPress={() => navigation.navigate('Add', { items, setItems })}
/>
<View>
{items.map((item, i) => {
return (
<View>
<Text>{item.itemName}</Text>
<Text>{item.itemPrice}</Text>
</View>
);
})}
</View>
</View>
);
}
HomeScreen.propTypes = {
navigation: PropTypes.object.isRequired,
};
export default HomeScreen;
And AddScreen receives 'items' as route.params.
And it use 'setItems' to push his own data in it.
After adding, navigation return to HomeScreen with items that is added with new item.
import * as React from 'react';
import PropTypes from 'prop-types';
import { View, Text, Button, TextInput } from 'react-native';
function AddScreen({ route, navigation }) {
const { items, setItems } = route.params;
const [itemName, setItemName] = React.useState('');
const [itemPrice, setItemPrice] = React.useState('0');
const addItem = () => {
setItems([...items, { itemName, itemPrice }]);
setItemName('');
setItemPrice('0');
};
return (
<View>
<TextInput
multiline
placeholder="What's on your mind?"
value={itemName}
onChangeText={setItemName}
/>
<TextInput
multiline
placeholder="What's on your mind?"
value={itemPrice}
onChangeText={setItemPrice}
/>
<Button
title="Done"
onPress={() => {
addItem();
// Pass params back to home screen
navigation.navigate('Home', items);
}}
/>
</View>
);
}
AddScreen.propTypes = {
navigation: PropTypes.object.isRequired,
route: PropTypes.object.isRequired,
};
export default AddScreen;
It works well on my purpose.
But I'm not sure whether this way is correct or not using react hooks to give and receive data from parent to child.
Could you modify my code ?
You should consider using React Context API https://uk.reactjs.org/docs/context.html. Its dedicated to sharing the common state (items in your case). Here is an example:
You should create a common context for items:
ItemsState.js
import React, { useState, useContext } from 'react';
const ItemsContext = React.createContext([]);
export const ItemsProvider = ({ children }) => {
return (
<ItemsContext.Provider value={useState([])}>
{children}
</ItemsContext.Provider>
);
}
export const useItems = () => useContext(ItemsContext);
Then share the context between screens with provider in App.js like this
import {ItemsProvider} from 'ItemsState';
function App() {
return (
<ItemsProvider> // share the items between both screens
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Add" component={AddScreen} />
</Stack.Navigator>
</NavigationContainer>
</ItemsProvider>
);
}
Then use items context in each screen like this AddScreen.js
import {useItems} from './ItemsState';
function AddScreen({ route, navigation }) {
const [items, setItems] = useItems(); // <- using items context as global useState
const [itemName, setItemName] = React.useState('');
const [itemPrice, setItemPrice] = React.useState('0');
const addItem = () => {
setItems([...items, { itemName, itemPrice }]);
setItemName('');
setItemPrice('0');
};
return (
<View>
<TextInput
multiline
placeholder="What's on your mind?"
value={itemName}
onChangeText={setItemName}
/>
<TextInput
multiline
placeholder="What's on your mind?"
value={itemPrice}
onChangeText={setItemPrice}
/>
<Button
title="Done"
onPress={() => {
addItem();
// Pass params back to home screen
navigation.navigate('Home', items);
}}
/>
</View>
);
}
You can also use useReducer hook and make more Redux-like. Check out this article
https://medium.com/simply/state-management-with-react-hooks-and-context-api-at-10-lines-of-code-baf6be8302c
in order to share data between components you can use Context API or Redux, passing full objects through navigation routes is an anti-pattern, you can find more information in the docs
https://reactnavigation.org/docs/params/#what-should-be-in-params