Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Context is not defined no-undef

I have navigation constant which is an array of objects(web-store mega-nav). I need to use context provider and when I'm trying to use my context it's telling me NavContext' is not defined no-undef.

NavContext.js

import { createContext } from 'react'

const navigation = [...] // array of objects

const NavContext = createContext(navigation)

export default NavContext

Nav.js

import {createContext} from 'react'
import NavContext from './context/NavContext' //added

function Nav() {

    return (
        <NavContext.Provider> //deleted value
        // childrens
        </NavContext.Provider>
    )
}

Sidebar.js

//then in one of the child I'm trying to call it:

import { useContext } from 'react'
import NavContext from '../context/NavContext' //added

function Sidebar(){
    const nav = useContext(NavContext)

    return (
        {nav.map(...)} // nav is undefined
    )
}

Now nav constant is undefined when I'm using useContext

like image 281
Morani Avatar asked May 02 '26 09:05

Morani


1 Answers

//Create a new NavContext.js File.

import React, { createContext, useReducer } from "react";

export const NavContext = createContext();

const initialState = {
}

function reducer(state, action) {
  return { ...state, ...action };
}

export const NavProvider = (props) => {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <NavContext.Provider value={{ state, dispatch }}>
      {props.children}
    </NavContext.Provider>
  );
};

Then in your index.js file.

import { NavProvider} from "./NavContext";

ReactDOM.render(
  <NavProvider>
    <App />
  </NavProvider>,
  document.getElementById("root")
);

If that doesnt work idk what will.