Search code examples
reactjsreact-contextuse-context

Context API error -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined


Consider the following code:

My Context.js is:


export const ListContext = createContext();

export const ListContextProvider = (props) => {
  const initialValues = {
    account: "",
    name: "",
    email: "",
  };

  const [values, setValues] = useState(initialValues);

  const ListContext = {
    initialValues,
    values,
    setValues,
  };

  return (
    <ListContext.Provider value={ListContext}>
      {props.children}
    </ListContext.Provider>
  );
};

And wrapped it in App.js like this:

import Homepage from './components/Homepage';
...
import { ListContextProvider } from './components/Context';


function App() {
  const [currentAccount, setCurrentAccount] = useState("");
  return (
    <ListContextProvider>
    <div className="App">
      <Navbar currentAccount={currentAccount} setCurrentAccount={setCurrentAccount}/>
      <Routes>
        <Route path="/" element={<Landingpage />} />
        <Route path="sell" element={ <Sellingform currentAccount={currentAccount}/> } />
        <Route path="storage" element={<WebStorage/>} />
      </Routes>
    </div>  
    </ListContextProvider>
  );
}

export default App;

The page doesn't load anything and console.log throws the following warning:

Warning: React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.


Solution

  • My bad. I had declared ListContext twice. Instead of

    const ListContext = {
      initialValues,
      values,
      setValues,
    };
        
    return (
     <ListContext.Provider value={ListContext}>
        {props.children}
     </ListContext.Provider>
    )
    

    Changed it to the following and it worked.

    const listContext = {
      initialValues,
      values,
      setValues,
    };
        
    return (
     <ListContext.Provider value={listContext}>
        {props.children}
     </ListContext.Provider>
    )