Building a React Library with Webpack, TypeScript, and the Material UI framework

Developing a unique component library with react, typescript, and webpack

Encountering an issue when utilizing components outside of react

Received an error message: invalid hook call. Hooks can only be called inside the body of a function component.

Also experiencing occasional errors like:

TypeError: Cannot read properties of null (reading 'useContext') useContext /node_modules/react/cjs/react.development.js:1618

Attempted to resolve by adjusting versions of react and other dependencies

Package.json

{
  "name": "library",
  "version": "1.0.0",
  "main": "dist/index.js",
  "license": "MIT",
  "devDependencies": {
    "@types/react": "^17.0.43",
    "bootstrap": "^4.6.0",
    "html-webpack-plugin": "^5.5.0",
    "ts-loader": "^9.4.2",
    "typescript": "^4.9.4",
    "webpack": "^5.75.0",
    "webpack-cli": "^5.0.1",
    "webpack-node-externals": "^3.0.0"
  },
  "scripts": {
    "build": "webpack",
    "tsc": "tsc",
    "start": "react-scripts start"
  },
  "dependencies": {
    "@emotion/react": "^11.10.5",
    "@emotion/styled": "^11.10.5",
    "@material-ui/core": "^4.11.2",
    "@material-ui/lab": "4.0.0-alpha.61",
    "@material-ui/styles": "^4.11.5",
    "@mui/material": "^5.10.7",
    "@types/react-dom": "^18.0.10",
    "material-avatar": "^0.3.5",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-script": "^2.0.5"
  },
  "peerDependencies": {
    "react": "*",
    "react-dom": "*"
  },
  "files": [
    "./dist"
  ]
}

.tsx file

import React from "react";
import Button from '@mui/material/Button';

interface ButtonProps {
    items: itemsArrayInterface[];
    title: String
}

interface itemsArrayInterface {
     id: Number,
     addedBy: String,
     page: String,
     likes: String,
     unLikes: String,
     adminApproved: String,
     comments: String,
     time: string,
     rating: Number
}

export default function(props: ButtonProps){
 
    return (
        <>
        <Button>hello</Button>
        </>
    )
   
}

Webpack configuration

const path = require("path");
const HTMLWebpackPlugin = require("html-webpack-plugin");
const nodeExternals = require("webpack-node-externals");
module.exports = {
    entry: "./src/index.tsx",
    mode: "production",
    target: "node",
    output: {
        path: path.resolve(__dirname, "dist"),
        filename: "index.js",
        libraryTarget: "umd",
        library: "library",
    },
    plugins: [
        new HTMLWebpackPlugin({
            template: path.join(__dirname, "src", "index.html"),
        }),
    ],
    module: {
        rules: [
            {
                test: /\.tsx?/,
                use: [
                    {
                        loader: "ts-loader",
                        options: {
                            compilerOptions: {
                                noEmit: false,
                            },
                        },
                    },
                ],
            },
            {
                test: /\.css$/i,
                use: ["style-loader", "css-loader"],
            },
        ],
    },

    externals: [nodeExternals()],
    resolve: {
        extensions: [".tsx", ".ts", ".js", ".d.ts"],
    },
};

Typescript (ts) configuration

{
  "compilerOptions": {
    /* TypeScript Configuration */
    "target": "es6",
    "lib": [
      "es6",
      "dom"
    ],
    "jsx": "react",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "noImplicitThis": true,
    "skipLibCheck": true
  },
  "include": [
    "src"
  ]
}

Answer №1

It appears that you may be using React hooks in a way that goes against the rules. Please review the guidelines for using React hooks to resolve your issue. React Hooks Rules Guide Alternatively, consider updating your question with the code snippet showing how you are implementing React hooks.

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

MUI error notification keeps appearing, even though I specifically disabled it

I am currently facing some challenges with my code and could use some assistance. It appears that the error alert box is displaying even though it should be empty. I conducted some code "tests" to analyze the situation and displayed the results on this pa ...

I possess a pair of items that require merging together while combining any overlapping key values in their properties

I have a scenario where I need to merge two objects and concatenate strings if they have the same key. obj1 = { name: 'John', address: 'Cairo' } obj2 = { num : '1', address: 'Egypt' } After merging, the r ...

Error: The method 'replace' is not a valid function for the specified

Something strange happened to my DatePicker today. All of a sudden, when I try to open it, the entire DatePicker appears white and I'm getting this error: > ERROR Error: Uncaught (in promise): TypeError: format.replace is not a function TypeError: ...

What is the most efficient way to retrieve a single type from a union that consists of either a single type or an array of types

Is there a way to determine the type of an exported union type by extracting it from an array, as illustrated in the example above? How can this be achieved without directly referencing the non-exported Type itself? interface CurrentType { a: string; b ...

Utilizing TypeScript in a browser with a .NetCore WebApplication

After going through numerous articles, I have not been successful in finding a solution. My challenge lies with a .net core WebApplication that utilizes typescript code instead of javascript. Here are the specific requirements: I need to be able to debu ...

Can anyone tell me how to find the total number of rows in a material react table component using a prop?

displayDataRowsCount I need a way to display the total number of rows in the table above the data ...

Select the object attribute to use as a value in MUI 5 Autocomplete

Here are the available options: const choices = [ { "Type": "Option A" }, { "Type": "Option B" } ] Implementation: const [selectedOption, setSelectedOption] = useState(''); <Autocomplet ...

What is the method for retrieving the value of the Material-ui auto-complete component in a React.js

How can I retrieve the value of Material-UI auto-complete in react.js? I have tried productName: this.refs.productName.value productName: this.refs.productName.getValue() but neither of them seem to be working <AutoComplete hintText="Produ ...

Best Practices for Converting TypeScript to JavaScript

What is the recommended approach to converting this JavaScript code into TypeScript? JAVASCRIPT: function MyClass() { var self = this, var1 = "abc", var2 = "xyz"; // Public self.method1 = function () { return "somethin ...

What's the reason behind my REST API delivering a 401 error code?

New Update After being encouraged to implement debug logs, I have discovered that the issue lies with Spring reporting an invalid CSRF token for the notices controller. I have compared the headers generated by Postman and the fetch requests, but found no ...

Declaration of function with extra attributes

Is there a way to define a type for a function that includes additional properties like this? foo({ name: 'john' }) foo.type I tried the following solution, but TypeScript seems to think that foo only returns the function and cannot be called wi ...

Converting a string to Time format using JavaScript

I am working with a time format of 2h 34m 22s which I need to parse as 02:34:22. Currently, I am achieving this using the following code: const splitterArray = '2h 34m 22s'.split(' '); let h = '00', m = '00', s = &a ...

Assign Monday as the selected day of the week in the MUI Datepicker 6

I am currently using version 6 of the material ui Datepicker and I am trying to configure it so that the week starts on Monday. import React from "react"; import { DatePicker as DatePickerDestop } from "@mui/x-date-pickers/DatePicker"; ...

How do you eliminate row highlighting on the <TableRow> component within Material-UI's <Table> using ReactJS?

I am facing an issue with a table and row highlighting in my code. Even after clicking on a row, it remains highlighted. I attempted to use the <TableRow disableTouchRipple={true}> but it didn't work as expected. What can I do to remove the high ...

Display or conceal <ul> with a click using AngularJS

I am struggling to display a menu on my HTML page. Currently, it is showing all the submenu options instead of just the options related to the clicked item. Here is the code from my home.html file: <ul class="navbar-nav"> <li data-toggle=" ...

When trying to update a form field, the result may be an

Below is the code for my component: this.participantForm = this.fb.group({ occupation: [null], consent : new FormGroup({ consentBy: new FormControl(''), consentDate: new FormControl(new Date()) }) }) This is th ...

Enhance your property by adding the isDirty feature

Managing changes to properties of classes in TypeScript can be optimized by tracking only the fields that have actually changed. Instead of using an array to keep track of property changes, I am exploring the idea of implementing an isDirty check. By incor ...

Steps for customizing shadows in Material UI themes:1. Determine which shadows you

import { createMuiTheme, responsiveFontSizes, } from "@material-ui/core/styles"; let theme = createMuiTheme({ palette: { primary: { main: "#000", }, secondary: { main: "#ccc", }, }, typogra ...

Tips on customizing a Drawer with Material-UI v5

When working with Material-UI v4, you could style the Drawer component like this: <Drawer variant="persistent" classes={{paper: myClassNameHere}} > The myClassNameHere is generated by using useStyles, which in turn is created using mak ...

React Query mutation encountered a TS2554 error: Type argument was not valid

I'm a beginner when it comes to TypeScript and I am using react-query. I tried using mutate, but it is causing an error. TS2554: Expected 1-2 arguments, but got 3. interface: interface ChangePassword{ email: string; password: string; conf ...