Reputation: 1170
In web based React our props have context, which can be set and in used as dependency injection mechanism. I would like to do something similar in React native app. Is there any way to do that?
Upvotes: 2
Views: 1606
Reputation: 1118
Hey there here is an example of context in react native that Ive used for authentication in one of my projects, centralizing the authentication the methods can then be imported into the relevant screens for example signIn, signUp or [user, setUser] =useState().
import React, {createContext, useState} from 'react';
export const AuthContext = createContext({});
export const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
return(
<AuthContext.Provider
value = {{
user,
setUser,
LoginWithEmail: async (user, success_callback, failed_callback) => {
......
},
SignupWithEmail: (email, password) => {
....
},
Signout: () => {
.....
},
checkIfLoggedIn : user => {
.....
},
contactpage : (email, message, name, phone) => {
.....
},
forgotPassword : (email) => {
.....
},
logout: async () => {
....
},
}}>
{children}
</AuthContext.Provider>
);
};
and then you can pass in context using this in your relevant screens:
const {LoginWithEmail} = useContext(AuthContext);
const {signUpWithEmail} = useContext(AuthContext);
const {user, setUser} = useContext(AuthContext);
Upvotes: 0
Reputation: 9701
React Native uses the same react
package used for web applications. All React Native components work in the same way as the React ones (in terms of creation, lifecycle and the API, the main difference being that they do not render HTML elements, but custom components that then talk to the OS API), so you can use context in the same way you do in React. In fact, the F8 App makes use of the context functionality in order to handle the back button in Android. Have a look at the source code.
Upvotes: 1