Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

UseContext can't find variable?

I’m trying to understand useContext but I don’t see what I’m doing wrong here, I get the error message "Can’t find variable: Test" but in the tutorial I’m reading from it never says anything about needing to import/export other than what is in the code?
Thank you!

App.js

    import React, { createContext } from 'react';
    const Test = createContext()

    export default function App() {
  return (
    <Test.Provider value="hello">
        <Home/>
    </Test.Provider>  );
}

Home.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const Home = () => {

    return(
        <Test.Consumer>
                <View style={styles.homeContainer}>
                  {value}
                </View>
        </Test.Consumer>
    )
}

>Solution :

You aren’t exporting Test from App.js, so you can’t just implicitly use it in Home.js.

I’d recommend moving it to another file, say, contexts.js:

import React from 'react';
const Test = React.createContext();
export {Test};

You can then do

import {Test} from './contexts';

in both (or all, in the future) of your other source files to refer to the same context type.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading