Search code examples
javascriptreactjstypescriptreact-nativenpm-package

Define dependencies in package.json so that the react package written in React v17 works in react 18 also


I have written an npm package in React v17.0.2. The package.json file looks like this

{
  "name": "shoe-store",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-icons": "^4.3.1",
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "devDependencies: {
    "react-scripts": "5.0.1"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ],
    "peerDependencies: {
      "react": ">=17.0.2",
      "react-dom": ">=17.0.2"
    }
  }
}

After publishing the package, the package works fine in React v17.0.2, but shows error when used in React v18.2.0. The error states mismatching version of React and renderer (such as React DOM) or you might have more than one copy of react in the same app.

My question is how can we write a package in React v17 or make changes to an existing package written in React v17 so that it works in React v17, React v18 and above(when it comes)

Thanks in advance to anyone who can provide a solution to this.


Solution

  • i think all looks gud you have react & react-dom specified as peerDependencies, you just need to remove react-dom & react from your dependencies, right now you are telling npm to explicitly install your deps version and not letting peerDependency do its thing and rely on app's react & react-dom version