14

so no where in my react code do I use the useContext property. I have a npm package which has a compiled webpack file that has a component in there. when i try to use the component in my react app it throw the error Uncaught TypeError: Cannot read properties of null (reading 'useContext'). the component function is there and outputs a react object. it just breaks the page when using it. now I looked into what useContext is and I believe it has something to do with state.

so below is my input component that I will be using in my react App

import React from 'react';
import {TextField} from  '@mui/material';
class Input extends React.Component {
  constructor(props){
    super(props)
  }
  render(){
    return (
      <div className="input" style={{position:"relative",left:this.props.tabOver? this.props.tabOver.toString()+"px":"0px"}}>
        <label style={{display:"block", width:"100%",position:"relative", margin: "5px"}}> {this.props.labelName}</label>
        <TextField
        size="small"
        onChange={(e)=>{this.props.update(e.target.value)}}
        value={this.props.value}
        label={this.props.label? this.props.label:"type here"}
        error={this.props.error? this.props.error:false}
        required={this.props.required? this.props.required:false}
        disabled={this.props.disabled? this.props.disabled:false}
        helperText={this.props.helperText? this.props.helperText:""}
        InputProps={{ style: { fontSize: this.props.InputProps? this.props.InputProp:10 } }}
        InputLabelProps={{ style: { fontSize: (this.props.InputLabelProps? this.props.InputLabelProps:12) } }}
        style={{background:'white', "borderLeft":"20px solid "+this.props.border,"borderRadius": "10px",width: this.props.width !== undefined ? this.props.width.toString()+"px":"100px"}}
        id="filled-basic"
        variant="filled" />
      </div>
    );
  }
}
export default Input;

and here is my react Application that uses Input

// import logo from './logo.svg';
import './App.scss';
import React from 'react';
import {Breadcrumbs,Link,Typography} from  '@mui/material';
import {Input} from '@zenaby/something';

class App extends React.Component {
  constructor(props){
    super(props)
   }

  render(){
    return (
      <div className="App">
        <ul className="header">
          <li> logo </li>
          <li> login </li>
        </ul>
        <div className="formCt">
         <Input />        
        </div>
      </div>
    );
  }
}
export default App;

I compiled this input with this webpack file

const path = require('path'); 
module.exports = {
  entry: "./compile/index.js",
  mode:"production",
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: "index.js", 
    libraryTarget: "commonjs2" 
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: {
            presets: ["@babel/preset-react",
            "@babel/preset-env"],
            plugins: ["@babel/plugin-proposal-class-properties"]
          }
        }
 }
 ]
  },
  target: 'node'
};

also my package json is here

{
  "name": "somename",
  "version": "0.1.0",
  "private": false,
  "babel": {
    "presets": [
      "@babel/preset-react"
    ]
  },
  "main":"dist/header.js",
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.2.0",
    "@testing-library/user-event": "^13.5.0",
    "react-dom": "^18.1.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "pp": "babel .components -d ./dist --ignore 'node_modules'",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "description": "This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).",
  "author": "grant",
  "license": "ISC",
  "peerDependencies": {
    "react": "^18.1.0"
  },
  "devDependencies": {
    "@babel/cli": "^7.17.10",
    "@babel/plugin-syntax-jsx": "^7.17.12",
    "@babel/preset-react": "^7.17.12"
  }
}


I wish this was an easy answer but being on this issue for hours I don't have any juice left in me to figure it out. in fact this answer could be helpful to alot of people who are new making components for npmjs. anyways thank you for looking at it any feedback is great :).

krishnaacharyaa
  • 14,953
  • 4
  • 49
  • 88
Grant mitchell
  • 277
  • 1
  • 2
  • 12

5 Answers5

25

This often happens if the packages are installed in different levels.

The mistake

app
 |node_modules          <-- some packages installed here
 |package.json
node_modules
package.json            <-- some packages installed here

Correct Way

app
 |node_modules
 |package.json          <-- install all the packages at the same heirarchy
krishnaacharyaa
  • 14,953
  • 4
  • 49
  • 88
5

the answer was i had forgot to delete my node_modules in my other package and react was duplicated also throwing the error saying react hooks error. React hooks duplicate react package

Grant mitchell
  • 277
  • 1
  • 2
  • 12
  • Please what node_modules, don’t understand what you mean by deleting your node_module in your other package – Emmanuel uzoezie Jul 01 '22 at 05:31
  • yes so when you create a npm package you want to link it for building purposes. Using rollup to compile it. If I leave my external package with react in it thats a React Error of having two or more React packages running in the same App. try it and you'll get the same error if you have another react package. – Grant mitchell Jul 02 '22 at 07:05
1

January 2023:

I also had this error Cannot read properties of null (reading 'useContext')

I solved it by adding 'rollup-plugin-peer-deps-external' to my rollup.config.mjs

import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import typescript from '@rollup/plugin-typescript';
import dts from 'rollup-plugin-dts';
import PeerDepsExternalPlugin from 'rollup-plugin-peer-deps-external';  //<--- THIS

import packageJson from "./package.json" assert {type: 'json'};

export default [
    {
        input: "src/index.ts",
        output: [
            {
                file: packageJson.main,
                format: "cjs",
                sourcemap: true,
            },
            {
                file: packageJson.module,
                format: "esm",
                sourcemap: true,
            },
        ],
        plugins: [
            PeerDepsExternalPlugin(),              //<--- THIS
            resolve(),
            commonjs(),
            typescript({ tsconfig: "./tsconfig.json" }),
        ],
    },
    {
        input: "dist/esm/types/index.d.ts",
        output: [{ file: "dist/index.d.ts", format: "esm" }],
        plugins: [dts()],
    },
];
gantonioid
  • 367
  • 1
  • 2
  • 15
0

If you are the author of the npm package make sure you have added peer dependencies in package.json file. The version of react and react-dom must exactly be same as the dev dependencies in package.json.

    {
  "name": "@githubusername/repo-name",
  "version": "3.16.0",
  "scripts": {
    "build": "rollup -c"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@rollup/plugin-commonjs": "^24.0.1",
    "@rollup/plugin-image": "^3.0.2",
    "@rollup/plugin-node-resolve": "^15.0.1",
    "@rollup/plugin-typescript": "^11.0.0",
    "@types/react": "^18.0.28",
    "react": "^18.2.0",
    "rollup": "^3.20.2",
    "rollup-plugin-dts": "^5.3.0",
    "rollup-plugin-postcss": "^4.0.2",
    "typescript": "^5.0.2"
  },
  "main": "dist/esm/index.js",
  "module": "dist/esm/index.js",
  "files": [
    "dist"
  ],
  "types": "dist/index.d.ts",
  "dependencies": {
    "@emotion/react": "^11.10.6",
    "@emotion/styled": "^11.10.6",
    "@hookform/resolvers": "^3.0.0",
    "@mui/material": "^5.11.14",
    "react-hook-form": "^7.43.7",
    "react-router-dom": "^6.9.0",
    "rollup-plugin-peer-deps-external": "^2.2.4",
    "tslib": "^2.5.0",
    "yup": "^1.0.2"
  },
  "peerDependencies": { <--- check if you have added this
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
"publishConfig": {
    "registry": "https://npm.pkg.github.com/githubusername"
  },
  "description": ""
}
Rahul Dev
  • 646
  • 2
  • 3
0

Suggestion

You must use your context(example- useAuth) inside the function call, writing it above your function call will give you an error {Cannot read properties of null (reading 'useContext')} You might be declaring your function call above the function definition Example:-

Incorrect way:-

import { useAuth } from '../../context/auth'
const [auth, setAuth] = useAuth();
const Header = () => {
  const handleLogout = () => {
    setAuth({
      ...auth,
      user: null,
      token: "",
    });
    localStorage.removeItem("auth");
    toast.success("Logout Successfully");
  };

Correct way:-

import { useAuth } from '../../context/auth'

const Header = () => {
const [auth, setAuth] = useAuth();
  const handleLogout = () => {
    setAuth({
      ...auth,
      user: null,
      token: "",
    });
    localStorage.removeItem("auth");
    toast.success("Logout Successfully");
  };

Hope it helps!

  • This does not seem to address the question (the question states that useContext is not used at all). While it might fix another error that produces the same error message, it does not look like this answer is useful in the context of the given question. Please check and update or delete. – Moritz Ringler May 21 '23 at 09:39