Skip to content

Instantly share code, notes, and snippets.

@dani-mp
Last active February 25, 2020 13:33
Show Gist options
  • Save dani-mp/f61bea189a9b16259171851fd7cde994 to your computer and use it in GitHub Desktop.
Save dani-mp/f61bea189a9b16259171851fd7cde994 to your computer and use it in GitHub Desktop.
React Navigation (v1/2/3/4) Navigator wrapped in a React Context Provider
// So we have a context...
const Context = React.createContext();
class Provider extends React.Component {
addTodo = todo => this.setState(({ todos }) => ({ todos: [...todos, todo] }));
state = {
todos: [],
addTodo: this.addTodo
};
render() {
return (
<Context.Provider value={this.state}>
{this.props.children}
</Context.Provider>
}
}
const Consumer = Context.Consumer;
// ... and we have a stack navigator
const Todos = ({ navigation }) => (
<Consumer>
{({ todos }) => (<TodosList todos={todos} onAddTodo={navigation.push('AddTodo')} />)}
</Consumer>
);
const AddTodo = ({ navigation }) => (
<Consumer>
{({ addTodo }) => (<CreateTodo onCreateTodo={todo => {
addTodo(todo);
navigation.pop();
}}
/>)}
</Consumer>
);
const Stack = createStackNavigator({ Todos, AddTodo });
// you can wrap the stack with the provider...
const StackWithTodos = props => (
<Provider>
<Stack {...props} /> // Important: pass down navigation and screenProps from parent for nested navigators.
</Provider>
);
StackWithTodos.router = Stack.router; // Also important: static router must be the same as well.
// ... and use it wherever you want, without creating a new app container.
const TabNavigator = createBottomTabNavigator({
TabA: StackWithTodos,
TabB: ...,
});
@dani-mp
Copy link
Author

dani-mp commented Jan 9, 2020

Hi, @barrylachapelle. I can't see any console.log statement in your code.

@mjamroz
Copy link

mjamroz commented Feb 14, 2020

thanks a lot!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment