I'm getting the following error while trying to compile a code in Reactjs. I'm new to Reactjs.
Module not found: Error: Package path ./cjs/react.development is not exported from package /Users/mansi/letsgrowmore/to-do-list/my-react-app/node_modules/react (see exports field in /Users/mansi/letsgrowmore/to-do-list/my-react-app/node_modules/react/package.json)
ERROR in ./src/Components/Todolist.js 7:0-51
Module not found: Error: Package path ./cjs/react.development is not exported from package /Users/mansi/letsgrowmore/to-do-list/my-react-app/node_modules/react (see exports field in /Users/mansi/letsgrowmore/to-do-list/my-react-app/node_modules/react/package.json)
webpack compiled with 1 error
import React from 'react';
import useState from 'react/cjs/react.development';
import Todoform from './Todoform';
export default function TodoList() {
const [todos, setTodos] = useState([]);
const addTask = task => {
if (!task.text) {
return;
}
const newTodos = [task, ...todos];
setTodos(newTodos);
}
return (
<div>
<Todoform addTask={addTask}></Todoform>
</div>
);
}
I tried npm update, downgrading the version but still same error.
The issue in your code is that you are using functions that are never imported from React.
To resolve this issue, you need to import the functions that you are using from React.
To do this, we will use an importing technique called tree-shaking. This is basically the use of getting specific functions/variables from an import, instead of getting everything and only using a few things. This technique can greatly increase speed and reduce bundle size.
In your React file, replace this line of code:
import React from "react";
With this:
import React, { useState } from "react";
This will import the useState
function from the React library.
If you use another function from React (e.g. useEffect
), then you need to import it the same way as useState
was imported.
import React, { useState, useEffect } from "react";
Basically, every time you need to import a function/variable from React, separate it with a comma (,
) in the curly braces ({}
).
In conclusion, to resolve the issue, you need to import the functions/variables that you are using.