2

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Great answer! Thank you
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.