0

I'm trying to wrap my mind around using Context in my React Native app that uses React Navigation. I think I am way off on this one. I am simply trying to pass the name of a book to my entire app through the navigation stacks.

App.js

const BookContext = React.createContext();

class BookProvider extends Component {

  state = { 
    name: 'book name' 
  }

  render() {
    return (
      <BookContext.Provider value={{
          name: this.state.name
        }}>

        {this.props.children}
      </BookContext.Provider>
    )
  }

}

export default function App() {
  return (

     <BookProvider>
       <BookContext.Consumer>

         {({ name }) => (<Routes name={name} />)} //my react navigation stacks component

       </BookContext.Consumer>
     </BookProvider>

  );
}

and in Book.js (a component in the navigation stack)

componentDidMount() {
    console.log(this.context)
}

returns an empty object {}

Any help is appreciated!

barrylachapelle
  • 967
  • 4
  • 13
  • 34

1 Answers1

0

To save you some Googling, this is the correct approach: https://github.com/react-navigation/react-navigation/issues/935#issuecomment-359675855

Another way, if you're using a relatively new version of React, and your component in question at that route is a functional component, is to use the useContext React hook.

e.g.

import React, { useContext } from 'react'
import { BookContext } from '/path/to/BookContext'

function BookConsumerComponent() {
  const { name } = useContext(BookContext);

  console.log(name);
}
username-yj
  • 105
  • 1
  • 4
  • Thanks for this. That GitHub answer is passing props to the Components through the navigator correct? I might be a bit of a newbie but I assumed that's what Context was working to prevent? Is that the only way to use Context with react navigation without using hooks? – barrylachapelle Jan 09 '20 at 18:26
  • You could also place the consumer in your component directly. However, IIRC, the recommended approach is to use hooks, as this is where the future developments are being focused by the React team (you'll have to learn it sooner or later, and it'll be a huge time saver as your project grows). I'll point you here for further reading for a start: https://stackoverflow.com/questions/53062732/react-functional-components-with-hooks-vs-class-components – username-yj Jan 09 '20 at 21:06