The reference to React in useContext is currently undefined

I am currently working on a React App that involves CRUD operations connected to a Rails API. The project structure is as follows:

App.js
 -> UserIndex
   --> Form
   --> User
 -> User

My goal is to pass a function from <App /> to its grandchild component, <User />, skipping the immediate child.

This is the code for <App />:

import "./App.css";
import User from "./components/User";
import UserIndex from "./components/UserIndex";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import { useState, createContext } from "react";

function App() {
  const [user, setUser] = useState({});
  const UserContext = createContext();

  function handleShow() {
    console.log("showed!");
  }

  return (
    <div>
      <BrowserRouter>
        <Routes>
          <UserContext.Provider value={handleShow}>
            <Route path="/" element={<UserIndex />}></Route>
          </UserContext.Provider>
          <Route
            path="users/:userId"
            element={<User id={user.id} name={user.name} email={user.email} />}
          />
        </Routes>
      </BrowserRouter>
    </div>
  );
}

export default App;

I have imported and created CreateContext, provided it through UserContext.Provider.

And here's the code for <User />:

import React, { useContext } from "react";
import { Link } from "@mui/material";
import axios from "axios";

function User(props) {
  const userName = useContext(UserContext);
  return (
    <div className="centerText">
      <Link
        href={`/users/${props.id}`}
        color="inherit"
        onClick={props.handleShow}
      >
        <h4>{props.name}</h4>
        <h4>{props.email}</h4>
      </Link>
      {props.deleteData && <button onClick={props.deleteData}>Delete</button>}
    </div>
  );
}

export default User;

While importing useContext, I encountered an error trying to fetch the UserContext that was provided. It kept returning: UserContext is not defined.

I also attempted wrapping all components in UserContext.Provider but the issue persisted:

<BrowserRouter>
        <Routes>
          <UserContext.Provider value={handleShow}>
            <Route path="/" element={<UserIndex />}></Route>

            <Route
              path="users/:userId"
              element={
                <User id={user.id} name={user.name} email={user.email} />
              }
            />
          </UserContext.Provider>
        </Routes>
      </BrowserRouter>

Despite researching online, most examples feature the same-filename setup, causing no trouble when fetching UserContext. Any idea what might be going wrong? Thank you!

EDIT:

After making corrections, this is how the code now looks:

import "./App.css";
import User from "./components/User";
import UserIndex from "./components/UserIndex";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import { useState, createContext } from "react";

export const UserContext = createContext();

function App() {
  const [user, setUser] = useState({});

  // function handleShow() {
  //   console.log("showed!");
  // }
  const handleShow = "fñalksdjfñdlskfjds";

  return (
    <div>
      <BrowserRouter>
        <Routes>
          <Route
            path="/"
            element={
              <UserContext.Provider value={handleShow}>
                <UserIndex />
              </UserContext.Provider>
            }
          ></Route>

          <Route
            path="users/:userId"
            element={<User id={1} name={"hey"} email={"there"} />}
          />
        </Routes>
      </BrowserRouter>
    </div>
  );
}

export default App;
import React, { useContext } from "react";
import { Link } from "@mui/material";
import axios from "axios";
import UserContext from "../App";

function User(props) {
  console.log(UserContext);
  const userName = useContext(UserContext);

  console.log(userName);

  return (
    <div className="centerText">
      <Link
        href={`/users/${props.id}`}
        color="inherit"
        onClick={props.handleShow}
      >
        <h4>{props.name}</h4>
        <h4>{props.email}</h4>
      </Link>
      {props.deleteData && <button onClick={props.deleteData}>Delete</button>}
    </div>
  );
}

export default User;

Answer №1

Make sure to define and export the UserContext outside of the App component.

export const UserContext = createContext();

function App() {
...

Afterwards, you can import the UserContext from the '/App' file.

import { UserContext } from '/App';

Answer №2

1- Start by creating a brand new file called UserContext.js

2- Inside UserContext.js, define and export the UserContext constant:

import { createContext } from 'react';

const UserContext = createContext();

export default UserContext;

3- Next, import UserContext into the desired file:

import UserContext from "./UserContext";

4- Retrieve the necessary information like this:

const UserInfo = useContext(UserContext);

Note: Make sure to also import useContext from react

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React- Error: Unhandled Type Mismatch in function call for _this4.getNotes

As I delve into learning React, I've created a basic application to manage notes with titles and descriptions. This application interacts with a REST API built using Go, enabling me to perform operations like retrieving, editing, creating, and deleti ...

The functionality of React's flushSync() is not performing as anticipated

I'm curious about why the following code snippet doesn't work as expected when using flushSync(). After clicking on the button, the alert displays "Hello, !" instead of showing the current state. Can anyone help me understand why this is happenin ...

Convert the pager produced by ReactiveList into another language

In my React application, I am using ReactiveList (v2.17) to display a list with a pager at the bottom. The problem is that the pager buttons are in English ("Prev", "Next"), while the site is supposed to be in Dutch. Is there a way to translate these but ...

jQuery not being applied to dynamically added dropdown element

I am currently utilizing bootstrap and jquery within my react project. I have a button that, when clicked, should transform into a dropdown field. The dropdown functions properly when placed statically, but the functionality is lost once it is dynamically ...

Frontend and backend development in IntelliJ: Should you work on one or multiple projects?

My project is divided into two main parts: JVM/kotlin backend (developed with gradle) React/typescript frontend (created with vite) Here is the directory structure of my project: my-project/ frontend/ package.json src/ node_modules/ ba ...

Transforming a React, Redux, and MUI Menu into an Electron Application

I'm in the process of transforming a web-based React + Redux + MUI application into an Electron app. The original app features a main AppBar with multiple dropdown menus, each containing menu items that interact with the app's Redux store. While ...

I am looking to transfer information to a different screen using FlatList in React Native

Hey everyone, I'm new to React Native and I'm trying to create a news app with posts. I'm having trouble figuring out how to pass data in a flatlist to another screen and open the screen with the post data. I'm using V6 navigation. Here ...

The data fetched from an API response does not get displayed by React

I've come across various questions but couldn't find the solution. Below is the code I have: import React, { Component } from "react"; import axios from "axios"; import "./tree.css"; import "./mainTree"; class TablesTree extends Component { c ...

React, redux, and redux observable are all essential tools for developing web applications. They

I am currently working on determining the type of a promise's resolve function. Here is a snippet of the code, or you can find it on GitHub: https://github.com/Electra-project/Electra-Desktop/blob/master/src/app/header/epics.ts export function getSt ...

I need the language chosen using Lingui's Language Switcher (i18n) to persist throughout the app, even after a refresh

I have been experimenting with Lingui for internationalization (i18n) in my app. I followed the documentation and tutorial to create a language switcher, but I am unsure how to set it up so that the selected language persists throughout the app even after ...

Guide on programmatically importing excel/CSV data into MongoDB collection/documents using MERN stack

I have a spreadsheet containing employee information. My objective is to save this data from the Excel file into a MongoDB database, specifically in the employee collection (each row from the spreadsheet as a document in MongoDB). This process is being car ...

How to programmatically disable the expansion panel in React js using Material UI

Is there a way to disable React Material Accordian / Expansion Panel using state properties instead of the traditional disabled attribute? I want to achieve something like this: <ExpansionPanel disabled="stateProperty?true:false" > I have searched ...

CSS2DRenderer does not belong to the Three.js library

Before we dive in, let me provide some background information: I recently incorporated three.js into a default React project using npm. Now, I'm interested in integrating this example that utilizes CSS2D. Unfortunately, I encountered an error when a ...

Next.js page freezes when Axios request is made causing the tab to become unresponsive

Curious about how to troubleshoot (or where to start) with my current Axios problem. I am working on a Next.js project (12.3) and have an axios interceptor hook that manages all of my internal requests. The interceptor functions properly on every action/pa ...

Error message: Unable to access properties of null when calling 'registerPlugin' in @devexpress/dx-react-grid-material-ui

I have developed a CustomGrid component that is based on the DevExpress Grid component. So far, it has been working smoothly. Here's how the implementation looks like in App.tsx: import Paper from "@mui/material/Paper"; import { Table, TableHeaderRow ...

How can I access a Next.js Application from a set Hostname in my Local Environment?

If I have a Next.js Application that is functioning correctly. It can be accessed through either http://localhost:4000 or http://somehostname.local:4000 To achieve this, I have added the line: 127.0.0.1 somehostname.local to my hosts file. However, ...

Update to Material UI V5: Incorrect theme color passed to MUI component via SX styling

After upgrading my material UI version from 4 to 5, I encountered a strange bug: While the theme colors work fine everywhere else on the app, the Tabs component is displaying default MUI theme colors. I tried changing the color using the 'sx' pr ...

Is it possible for me to create an API that allows for interaction with content within an iframe?

I am currently working on a project that involves populating web pages in an iframe. However, the CORS policy is making it impossible for me to interact with the content inside the iframe from my application. I have tried using postMessage, but it seems vu ...

Tips for creating a new route within a separate component in React JS without causing the previous one to unmount

I am currently developing a recipe website using React JS and React Router. On the HomePage, I have set up a display of cards, each representing a preview of a recipe. Each card is enclosed within a <Link></link> tag. When one of these cards ...

You will encounter a TypeError with the message "Super expression must be null or a function" when attempting to export a named class

I'm experimenting with components. I have a default export in place but now I think I need to create a named class for my next export. Take a look at the code below: export default Users; import React from 'react'; export class UsersTest e ...