Reputation: 529
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 :).
Upvotes: 26
Views: 78266
Reputation: 1
Not a big issue, it took me almost 2 hr and the problem is not with the code it's just your node modules are installed outside the project folder on the same level as of project folder, just copy paste the modules and problem solved
Upvotes: -1
Reputation: 1
I had the same issues and realized it was because I didn't install the peer dependencies listed in the docs. For example, for @mui/x-charts
, I had to install the following peer dependencies too:
"peerDependencies": {
"@mui/material": "^5.4.1",
"@mui/system": "^5.4.1",
"react": "^17.0.0 || ^18.0.0",
"react-dom": "^17.0.0 || ^18.0.0"
}
https://www.npmjs.com/package/@mui/x-charts
Upvotes: 0
Reputation: 28151
I had this same problem using workspaces with bun (my solution below might work for yarn also). The solution evolved:
Deleting node_modules
from all workspace packages including the root node_modules
then running bun install
Making react and react-dom peerDeps in each of the packages:
"peerDependencies": {
"react": "*",
"react-dom": "*"
}
Adding react and react-dom as dependency of the main workspace package.json
Bun install from the root.
Upvotes: 0
Reputation: 1
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!
Upvotes: -2
Reputation: 906
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": ""
}
Upvotes: 0
Reputation: 457
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()],
},
];
Upvotes: 4
Reputation: 25120
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
Upvotes: 41
Reputation: 529
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
Upvotes: 7