Making Sign in form in react native - react-native

I am trying to create a sign in form using custom text field. Inside a custom form and use that form details to validate user in login page.
Custom text field
export default class UserInput extends Component {
render() {
return (
<View style={styles.inputWrapper}>
<Image source={this.props.source} style={styles.inlineImg} />
<TextInput
style={styles.input}
placeholder={this.props.placeholder}
secureTextEntry={this.props.secureTextEntry}
/>
</View>
);
}
}
using custom text field to create a form.
export default class Form extends Component {
constructor(props) {
super(props);
this.state = {
email: "",
password: ""
};
}
render() {
const { onChange, ...rest } = this.props;
return (
<KeyboardAvoidingView behavior="padding" style={styles.container}>
<UserInput
source={usernameImg}
placeholder="Username"
/>
<UserInput
source={passwordImg}
secureTextEntry={this.state.showPass}
placeholder="Password"
/>
</KeyboardAvoidingView>
);
}
}
using form and other components in the sign in screen.
class SignInScreen extends Component {
constructor(props) {
super(props);
this.state = {
email: "",
password: "",
isLoading: false
};
}
signIn = async () => {
console.log("signIn");
firebase
.auth()
.signInWithEmailAndPassword("entered email", "entered password")
.then(
() => {
console.log("then");
this.moveTohome();
},
error => {
console.log(error, "eroor in login");
}
);
console.log("App");
};
moveTohome = async () => {
console.log("move to home");
await AsyncStorage.setItem("userToken", this.state.email);
this.props.navigation.navigate("App");
};
render() {
const changeWidth = this.buttonAnimated.interpolate({
inputRange: [0, 1],
outputRange: [myWidth * 0.9, myHeight * 0.08]
});
return (
// <DismissKeyboard>
<Wallpaper>
<Form />
<SignupSection navigation={this.props.navigation} />
<ButtonSubmit
onPress={() => {
this.signIn();
}}
/>
</Wallpaper>
// </DismissKeyboard>
);
}
}
I want to access the email and password entered in the sign in screen.
I Did not wanted to use any custom forms available. I dont know the redux to maintain state also. So what would be the simple way I can do? in the app.
I searched a lot but nothing is working for me.

If you want to access the email/password in some other screen then you can send them in a param object in your react navigation method.
this.props.navigation.navigate("App",{
email:this.state.email,password:this.state.password
});
But this would only be sent to App route in this case and if you want to access at other page then you need to pass them again.
Another way will be to hook up your app with Redux as it works so good when combined with React for state management.

Related

Clearing Input in React Native

I'm new to react native.
I've created a react native app and my first screen is a login screen. I'm using onChangeText to update state vars with username and password and this works great initially.
However on "logout" when I pop back to the login screen. The inputs still have my username and password in. However the state vars are now back to null.
I've tried setting value to {this.state.username} for the input but this just causes a depth error on state after 2 input presses so doesn't work.
Am I missing something?
import React, { Component } from 'react';
import { View, Text, StyleSheet, Image, Alert, AsyncStorage, Linking } from 'react-native';
import { Input, Left, Spinner, Container, Item, Form, Header, Content, Label, Button } from 'native-base'
export default class Login extends Component {
state = { username: "", password: "", isLoaded: true }
static navigationOptions = {
header: null
}
constructor(props) {
super()
this.state.isLoaded = false
AsyncStorage.getItem("loggedIn").then(res => {
if (res === "true") {
this.props.navigation.navigate('List')
}
else {
this.setState({isLoaded: true})
}
})
}
checkLogin() {
if ((!this.state.username) || (!this.state.password)) {
Alert.alert('Error', 'Username/Password combination unknown', [{
text: 'Okay'
}])
return
}
....... snip ......
if (response === false) {
Alert.alert('Error', 'Username/Password combination unknown', [{
text: 'Okay'
}])
}
else {
AsyncStorage.setItem('user', JSON.stringify(response));
AsyncStorage.setItem('loggedIn', "true");
this.setState({username: null, password: null})
this.props.navigation.navigate('List')
}
}
}
render()
{
if (this.state.isLoaded == false) {
return (
<Container>
<Spinner />
</Container>
)
}
return (
<Container>
<Content>
<Image source={require('../../assets/logo.jpg')}/>
<Form>
<Item floatingLabel>
<Label>Username</Label>
<Input
autoCapitalize='none'
clearButtonMode='always'
onChangeText={text => this.setState({username:text})} />
</Item>
<Item floatingLabel>
<Label>Password</Label>
<Input
secureTextEntry={true}
clearButtonMode='always'
onChangeText={text => this.setState({password: text})} />
</Item>
<Button primary onPress={_ => this.checkLogin()}>
<Text style={styles.loginButtonText}>Login</Text>
</Button>
</Form>
</Content>
</Container>
);
}
}
You can use direct manipulation method.
Try passing ref to Input like ref={ (c) => this._input = c } and then calling the setNativeProps function this._input.setNativeProps({text:''})
I am also using react navigation and face similar issue.
I fixed as below :
import { NavigationEvents } from "react-navigation";
class ... {
onStartScreenFocus = ()>={
this.setState({
username: "", password: ""
})
}
render(){
return(
<View>
<NavigationEvents
onWillFocus={() => this.onStartScreenFocus()}
onDidBlur={() => this.onDidScreenBlur()} />
<View>
)
}
}

React Native Form Validation

I created a login form using react-native and I want to validate every fields but I don't know how to do it. I'm quite new to react-native so I want to ask anyone for help. Form validation should show error under following conditions:
Input form is empty
Email text isn't email form.
Password text does not satisfy the conditions above.
If Input form has errors the login button should be disabled.
If Input form doesn't have any errors, show alert to inform login
success
Sample image validation:
Here is my code:
import React from 'react';
import { StyleSheet, Text, View, Image, TextInput, Dimensions, ScrollView,
CheckBox, TouchableOpacity } from 'react-native';
import logo from './image/Logo.png'
const { width: WIDTH } = Dimensions.get('window')
export default class App extends React.Component {
constructor(){
super();
this.state={
check:false,
email: '',
};
this.validates = this.validates.bind(this);
}
CheckBoxText(){
this.setState({
check:!this.state.check,
})
}
validates = () => {
let text = this.state.email;
let emailError = this.state.emails;
let reg = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/ ;
if(reg.test(text) === false)
{
console.warn("Invalid email")
this.setState({email:text})
return false;
}
else {
this.setState({email:text})
console.log("Email is Correct");
}
}
render() {
return (
<View>
<View style={styles.container}>
<Image source={logo} style={styles.logo}/>
</View>
<View style = {styles.container2}>
<Text style={styles.emailAdd}>
Email
</Text>
<TextInput
onChangeText={(text) => this.setState({email:text})}
type='email'
value={this.state.email}
keyboardType='email-address'
style={styles.emailInput}
placeholder={'Input Email Address'}
underlineColorAndroid='transparent'/>
</View>
<View style = {styles.container3}>
<Text style={styles.password}>
Password
</Text>
<TextInput
style={styles.passwordInput}
placeholder={'Input Password'}
secureTextEntry={true}
underlineColorAndroid='transparent'/>
</View>
<View style = {styles.container4}>
<View>
<CheckBox value={this.state.check} onChange={()=>this.CheckBoxText()} style={styles.rememberMe}/>
</View>
<View>
<Text style={styles.remember}>Remember me</Text>
</View>
</View>
<TouchableOpacity style={styles.btnLogin} onPress={this.validates} >
<Text style={styles.txtLogin}>Sign In</Text>
</TouchableOpacity>
</View>
);
}
}
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
var validRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
if (!email) {
Toast.show('Email is required.');
} else if (!email.match(validRegex)) {
Toast.show('Invalid Email');
} else if (!password) {
Toast.show('Password is required.');
}
I recommend using formik and yup to easily build a login form with input validation. These two packages when integrated together, simplifies your codebase thanks to both of its features.
Please take a look at a CodeSandbox snippet here, https://codesandbox.io/s/stack-overflow-54204827-llvkzc?file=/index.tsx:254-656. And note, I'm using typescript here.
The package.json file at the time of written snippet is:
"dependencies": {
...
"formik": "2.2.9",
...
"yup": "0.32.11"
},
And to break the solution down, first we define our yup schema for our Login form:
Note, you may tweak the regex pattern later, as this password validation accepts min 6 to max 12 characters, with at least one uppercase letter, one lowercase letter, one number and one special character.
/**
* The `yup` Login Form schema
*/
const LoginSchemaA = Yup.object().shape({
email: Yup.string()
.email("Invalid email.")
.required("Email must be provided."),
password: Yup.string()
.required("Password must be provided.")
.matches(
/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##\$%\^&\*])(?=.{6,12})/,
"Password must be minimum 6 and maximum 12 characters."
)
});
Note, .email("Invalid email.") here is the default email validation feature used. You can remove this, and use .matches(...) function instead for your own regular expression.
And just the <Formik /> section for your further use:
<Formik
initialValues={{
email: "",
password: ""
}}
validationSchema={LoginSchemaA}
onSubmit={(
values: Values,
{ setSubmitting }: FormikHelpers<Values>
) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
setSubmitting(false);
}, 500);
}}
>
{({ errors, touched }) => (
<Form>
<label htmlFor="email">Email</label>
<Field
id="email"
name="email"
placeholder="john.doe#email.com"
type="email"
/>
{errors.email && touched.email ? (
<div style={{ color: "red" }}>{errors.email}</div>
) : null}
<label htmlFor="password">Password</label>
<Field id="password" name="password" type="password" />
{errors.password && touched.password ? (
<div style={{ color: "red" }}>{errors.password}</div>
) : null}
<button type="submit">Submit</button>
</Form>
)}
</Formik>
Lastly, you would want to grab the values itself for further use - ignore the setTimeout, alert and setSubmitting usages.
An example output of JSON.stringify(values, null, 2) would be as below:
{
"email": "john.doe#test.com",
"password": "Awesome#Password!2022"
}
Hope this helps you in your react-native coding journey!
here is my code you can try this
import React, { Component } from "react"
import { View, Button } from "react-native"
import TextField from "textfield"
import validation from "validation"
import validate from "validation_wrapper"
export default class Form extends Component {
constructor(props) {
super(props)
this.state = {
email: "",
emailError: "",
password: "",
passwordError: ""
}
}
register() {
const emailError = validate("email", this.state.email)
const passwordError = validate("password", this.state.password)
this.setState({
emailError: emailError,
passwordError: passwordError
})
if (!emailError && !passwordError) {
alert("Details are valid!")
}
}
render() {
return (
<View>
<TextField
onChangeText={(value) => this.setState({ email: value.trim() })}
onBlur={() => {
this.setState({
emailError: validate("email", this.state.email)
})
}}
error={this.state.emailError}
/>
<TextField
onChangeText={(value) => this.setState({ password: value.trim() })}
onBlur={() => {
this.setState({
passwordError: validate("password", this.state.password)
})
}}
error={this.state.passwordError}
secureTextEntry={true}
/>
<Button title="Register" onPress={this.validateRegister} />
</View>
)
}
}
<!-- begin snippet: js hide: false console: true babel: false -->
const validation = {
email: {
presence: {
message: "^Please enter an email address"
},
email: {
message: "^Please enter a valid email address"
}
},
password: {
presence: {
message: "^Please enter a password"
},
length: {
minimum: 5,
message: "^Your password must be at least 5 characters"
}
}
}
export default validation
import validation from "validation.js"
export default function validate(fieldName, value) {
// Validate.js validates your values as an object
// e.g. var form = {email: 'email#example.com'}
// Line 8-9 creates an object based on the field name and field value
var formValues = {}
formValues[fieldName] = value
// Line 13-14 creates an temporary form with the validation fields
// e.g. var formFields = {
// email: {
// presence: {
// message: 'Email is blank'
// }
// }
var formFields = {}
formFields[fieldName] = validation[field]
// The formValues and validated against the formFields
// the variable result hold the error messages of the field
const result = validatejs(formValues, formFields)
// If there is an error message, return it!
if (result) {
// Return only the field error message if there are multiple
return result[field][0]
}
return null
}
import React from "react"
import { View, TextInput, Text } from "react-native"
const TextField = (props) => (
<View>
<TextInput />
props.error ? <Text>{props.error}</Text> : null
</View>
)
export default TextField

Passing value of component to another Scene to use in post method - react native

I need Some Help as possible.
In my code I have scene that return into my view, an array with names. However, I want to do something also. When I click the name, I want to take the email of the name I have clicked and past to my post method, to return in another scene with information of the email person. Here is my code:
My Users Class with all elements
import React from 'react';
import ListaItens from './ListaUsers'
import BarraNavegacao from './BarraNavegacao';
import {View,Image,Alert,TouchableHighlight,AsyncStorage} from 'react-native';
import axios from 'axios';
export default class Users extends React.Component {
constructor(props) {
super(props);
this.state = {tituloBarraNav: 'Colaboradores',testLocal:''};
}
My refresh function is into Component Users
async refresh() {
let tmp_localData = {};
AsyncStorage.getItem('localData', (err, result) => {
//console.log(result);
tmp_localData = JSON.parse(result);
//console.log('Local temp: ', tmp_localData.User.email);
}).then((result) => {
tmp_localData = JSON.parse(result);
//console.log('Email: ', tmp_localData.email);
axios({
method: 'post',
url: 'my url'
data: {
email: 'someEmail#test.com,
}
},
console.log('aqui esta o email'),
).then((response) => {
//console.log('Get tmpLocal ----------',tmp_localData);
//console.log('Get response ----------',response);
tmp_localData.User = {
"userID": response.data.response.userID,
"displayName": response.data.response.displayName,
"email": response.data.response.email,
"avatar": response.data.response.avatar,
"gender": response.data.response.gender,
"Session": {
"token": response.data.response.token,
},
"FootID": response.data.response.FootID,
};
//this.refresh();
//console.log('Set tmpLocal',tmp_localData);
AsyncStorage.setItem('localData', JSON.stringify(tmp_localData), () => {
}).then((result) => {
this.props.navigator.push({id: 'MenuPrincipal'});
console.log('Navigator',this.props.navigator);
//Alert.alert('Clicou Aqui ');
});
}).catch((error) => {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
Alert.alert('Não foi possivel mudar o utilizador');
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log('erro de ligaçao', error.message);
Alert.alert('Não foi possivel mudar o utilizador');
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('erro de codigo no then', error.message);
Alert.alert('Não foi possivel mudar o utilizador');
}
console.log(error.config);
Alert.alert('Não foi possivel mudar o utilizador');
});
});
}
My render in Users
render(){
const {principal, conteudo,imgConteudo1,imgConteudo2, texto,box}= myStyle;
return(
<View style={principal}>
<BarraNavegacao back navigator={this.props.navigator} tituloProp={this.state.tituloBarraNav}/>
<TouchableHighlight onPress={() => {this.refresh();}}
clearButtonMode={'while-editing'}
activeOpacity={1} underlayColor={'white'}>
<ListaItens/>
</TouchableHighlight>
</View>
);
}
}
I have ListaItems Component that will walk through an array and will put inside ScroolView with map method. So the code is:
My ListaItems Class
import React from 'react';
import { ScrollView} from 'react-native';
import axios from 'axios';
import Items from './Items';
export default class ListaItens extends React.Component {
constructor(props) {
super(props);
this.state = {listaItens: [], listaEmail: [] };
}
componentWillMount() {
//request http
axios.get('my url')
.then((response) => {
this.setState({listaItens: response.data.response})
})
.catch(() => {
console.log('Erro ao imprimir os dados')
});
}
render() {
return (
<ScrollView>
{this.state.listaItens.map(item =>(<Items key={item.email} item={item}/>))}
</ScrollView>
);
}
}
The last component is the component the build what i want to show inside scrollview in ListaItems. The component name is Items. the code is:
My Items Class
import React, {Component} from 'react';
import {Text, Alert, View, Image,} from 'react-native';
export default class Items extends Component {
constructor(props) {
super(props);
this.state = {listaEmail: ''};
}
render() {
const {foto, conteudo, texto, box, test} = estilo;
return (
<View>
<Text/>
<Text/>
<View style={conteudo}>
<Image style={foto} source={{uri: this.props.item.avatar}}/>
<Text style={texto}>{this.props.item.displayName}</Text>
</View>
<View style={test}>
<Text style={texto}>{this.props.item.email}</Text>
</View>
</View>
);
}
}
So, in Users Class for refresh() function in the post method on this email: "someEmail#test.com", I want to be dynamic, when I click the name of a person in Items Class, I want to take the the email here on this.props.item.email and put in parameter on post method of Users Class----refresh()----axios()---Data---email:the email i want to past.
A litle help here, please. I am desperate right now because i have tryied and I did not make it
First move the Touchable to the item
export default class Items extends Component {
render() {
const { foto, conteudo, texto, box, test } = estilo;
return (
<View> //I'm not sure if the this.props.item.email is the one you use, just change it if you need.
<TouchableHighlight onPress={() => { this.props.callback(this.props.item.email); }}
clearButtonMode={'while-editing'}
activeOpacity={1} underlayColor={'white'}>
<Text />
<Text />
<View style={conteudo}>
<Image style={foto} source={{ uri: this.props.item.avatar }} />
<Text style={texto}>{this.props.item.displayName}</Text>
<View style={test}>
<Text>{this.props.item.email}</Text>
</View>
</View>
</TouchableHighlight>
</View>
);
}
}
Them change you function to receive the email param.
refresh = (email) => {
let tmp_localData = {};
AsyncStorage.getItem('localData', (err, result) => {
tmp_localData = result;
}).then((result) => {
axios({
method: 'post',
url: 'my Url',
data: {
email: email,
}
})
})
}
And them you can pass the function to component via props
render() {
const { principal, conteudo, imgConteudo1, imgConteudo2, texto, box } =
myStyle;
return (
<View style={principal} >
<BarraNavegacao back navigator={this.props.navigator} tituloProp={this.state.tituloBarraNav} />
<ListaItens callback={this.refresh} />
</View>
);
}

Update state when user press back button in React Native

I use react-navigation for manage routes. This is my Home component:
class HomeScreen extends React.Component {
constructor(props) {
this.state = {
userProfile: {
firstname: 'John',
avatar: 'john-profile.png',
location: 'Canada',
}
}
}
componentDidMount() {
AsyncStorage.getItem('userProfile', (errs, result) => {
this.setState({userProfile: JSON.parse(result)});
});
}
render() {
return (
<View>
<Image src="{this.state.userProfile.avatar}" />
<Text>Firstname: {this.state.userProfile.firstname}</Text>
<Text>Location: {this.state.userProfile.location}</Text>
</View>
);
}
}
And this is the Profile screen:
class ProfileScreen extends React.Component {
constructor(props) {
this.state = {
userProfile: null,
}
}
componentDidMount() {
AsyncStorage.getItem('userProfile', (errs, result) => {
this.setState({userProfile: JSON.parse(result)});
});
}
save() {
var userSavedProfile = this.state.userProfile;
userSavedProfile.firstname = "Peter";
userSavedProfile.avatar = "peter-avatar.png";
userSavedProfile.location = "EEUU";
this.setState({userProfile: userSavedProfile});
AsyncStorage.setItem('userProfile', JSON.stringify(this.state.userProfile), () => {});
}
render() {
return (
<View>
<Button title="Save" onPress={() => this.save()} />
</View>
);
}
}
When I save the new user information and I press back button in header (react-navigation) the user profile is old, firstname = John, etc... How update state from Home when user press back button and refresh data?
You can use BackHandler from react-native
https://facebook.github.io/react-native/docs/backhandler.html
You can change state inside function of backhandler
I think that your application would need a state manager, where you could store your user information and access it anywhere in the app. You should take a look at Redux. It would fit your needs and the info in your Home screen would automatically update.
but for anyone who will need this functionality in there react native application here is the solution you can try.
using react navigation.
import {withNavigationFocus} from "react-navigation";
class Profile extends Component {
...
}
export default withNavigationFocus(Profile);
There can be two workarounds check it out -
1 Send callback in params
class HomeScreen extends React.Component {
constructor(props) {
this.state = {
userProfile: {
firstname: 'John',
avatar: 'john-profile.png',
location: 'Canada',
}
}
this.getUserData = this.getUserData.bind(this);
}
componentDidMount() {
this.getUserData;
}
getUserData = () =>{
AsyncStorage.getItem('userProfile', (errs, result) => {
this.setState({userProfile: JSON.parse(result)});
});
}
render() {
return (
<View>
<Image src="{this.state.userProfile.avatar}" />
<Text onPress={()=>this.props.navigation.navigate('ProfileScreen', this.getUserData)}>Firstname: {this.state.userProfile.firstname}</Text>
<Text>Location: {this.state.userProfile.location}</Text>
</View>
);
}
}
class ProfileScreen extends React.Component {
constructor(props) {
this.state = {
userProfile: null,
}
}
componentDidMount() {
AsyncStorage.getItem('userProfile', (errs, result) => {
this.setState({userProfile: JSON.parse(result)});
});
}
save() {
var userSavedProfile = this.state.userProfile;
userSavedProfile.firstname = "Peter";
userSavedProfile.avatar = "peter-avatar.png";
userSavedProfile.location = "EEUU";
this.setState({userProfile: userSavedProfile});
AsyncStorage.setItem('userProfile', JSON.stringify(this.state.userProfile), () => {});
//this is the magic
this.props.navigation.state.params.getUserData();
}
render() {
return (
<View>
<Button title="Save" onPress={() => this.save()} />
</View>
);
}
}
2 On HomeScreen Constructor add this (Dirty one)
this.props.navigation.addListener(
'didFocus',
payload => {
this.setState({is_updated:true});
}
);
You can use componentDidUpdate(){...} insted componentDidMount(){}

Implement FB login with react native and redux

I want to use Redux framework in my react native based app for implementing Facebook login (I am learning Redux at the moment). I am looking for suggestions on how to structure my Facebook login code to use the redux. More specifically, what actions, reducer and store should I create?
Below is the current Facebook based login code that I have in my app (it does not use redux structure). I have deleted the unrelated code to keep things simple:
index.ios.js
class ProjectXApp extends React.Component {
constructor(props) {
// Set the use to NULL
this.state = {
user: null,
};
}
handleLogin(user) {
this.setState({
// Update the user state once the login is complete
user,
});
}
renderScene(route, navigator) {
const Component = route.component;
return (
<View style={styles.app}>
<Component
user={this.state.user}
navigator={navigator}
route={route}
/>
</View>
);
}
render() {
return (
<Navigator
renderScene={this.renderScene.bind(this)}
initialRoute={{
// Render the Login page in the beginning
component: Login,
props: {
onLogin: this.handleLogin.bind(this),
},
}}
/>
);
}
}
Login.js
// Import Facebook Login Util Component
class Login extends React.Component {
constructor(props) {
super(props);
this.state = {
// 'false' means responseToken is not required. 'true' means responseToken is required
responseToken: false,
};
}
// This method gets the fb access token, if the token is returned then
// I render the Main App component (switchToMain method). If the
// access token is not returned then I render a login Button (Refer to render method)
async getAccessToken() {
let _this = this;
await (FBSDKAccessToken.getCurrentAccessToken((token) => {
if(!token) {
_this.setState({responseToken: true})
return;
}
_this.setState({responseToken: true});
_this.props.route.props.onLogin({user: true});
_this.switchToMain();
}));
}
switchToMain() {
this.props.navigator.push({
component: Main, // Render the app
props: {
onLogOut: this.onLogOut.bind(this)
}
});
}
componentDidMount() {
this.getAccessToken();
}
onLoginButtonPress() {
// Shows transition between login and Main Screen
this.setState({responseToken: false})
FBSDKLoginManager.logInWithReadPermissions(['public_profile','email','user_friends'], (error, result) => {
if (error) {
alert('Error logging in');
} else {
if (result.isCancelled) {
alert('Login cancelled');
} else {
this.setState({result});
this.getAccessToken();
}
}
});
}
onLogOut() {
this.setState({responseToken: true});
}
render() {
// This component renders when I am calling getAccessToken method
if(!this.state.responseToken) {
return (
<Text></Text>
);
}
// This renders when access token is not available after calling getAccessToken
return (
<View style={styles.container}>
<TouchableHighlight
onPress={this.onLoginButtonPress.bind(this)}
>
<View>
// Login Button
</View>
</TouchableHighlight>
</View>
);
}
}
// Removed the styling code
Logout.js
import { FBSDKLoginManager } from 'react-native-fbsdklogin';
class Logout extends React.Component {
onLogOut() {
FBSDKLoginManager.logOut();
this.props.onLogOut();
this.props.navigator.popToTop();
}
render() {
return (
<View>
<TouchableHighlight
onPress={this.onLogOut.bind(this)}
>
<View
// Styles to create Logout button
</View>
</TouchableHighlight>
</View>
);
}
});
// Removed the styling code
Have you looked at this lib:
https://github.com/lynndylanhurley/redux-auth?