skip to Main Content

I have the following Tab Navigator in my React Native app, using React Navigation v6:

<Tab.Navigator>
  <Tab.Screen name="Screen1" component={Screen1}/>
  <Tab.Screen name="Screen1" component={Screen2}/>
</Tab.Navigator>

I want to pass a prop called prop1 that will be accessible in each screen. How do I do this?

2

Answers


  1. React Navigation v6 doesn’t allow you to pass props directly to screens from the navigator component as you could in previous versions. However, there are still a few different methods to pass props to screens.

    You can wrap your navigator with a context provider and use the useContext hook in your screen components to access your data. Like so:

    import React, { createContext, useContext } from "react";
    
    const MyContext = createContext();
    
    <MyContext.Provider value={prop1}>
      <Tab.Navigator>
        <Tab.Screen name="Screen1" component={Screen1}/>
        <Tab.Screen name="Screen2" component={Screen2}/>
      </Tab.Navigator>
    </MyContext.Provider>
    

    In your Screen1 and Screen2 components:

    import React, { useContext } from "react";
    import { MyContext } from "./path/to/context";
    
    function Screen1() {
      const prop1 = useContext(MyContext);
    
      // ...
    }
    
    function Screen2() {
      const prop1 = useContext(MyContext);
    
      // ...
    }
    

    Alternatively, you can use Higher Order Components:
    You can wrap your Screen components in a higher-order component, and pass the props to the HOC. Like so:

    function withProps(Component, prop1) {
      return function WrappedComponent(props) {
        return <Component {...props} prop1={prop1} />;
      };
    }
    
    const Screen1WithProps = withProps(Screen1, 'your data here');
    const Screen2WithProps = withProps(Screen2, 'your data here');
    
    <Tab.Navigator>
      <Tab.Screen name="Screen1" component={Screen1WithProps} />
      <Tab.Screen name="Screen2" component={Screen2WithProps} />
    </Tab.Navigator>
    

    Screen1 and Screen2 components:

    function Screen1({ prop1 }) {
      console.log(prop1);  // 'your data here'
      
      // ...
    }
    
    function Screen2({ prop1 }) {
      console.log(prop1);  // 'your data here'
      
      // ...
    }
    
    Login or Signup to reply.
  2. You can do this by moving the component from the component prop to become a child of the screen. Example:

    <Tab.Navigator>
      <Tab.Screen name="Screen1">
        {() => <Screen1 prop1={prop1} />}
      </Tab.Screen>
      <Tab.Screen name="Screen2">
        {() => <Screen2 prop1={prop1} />}
      </Tab.Screen>
    </Tab.Navigator>
    

    Official doc here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search