Coder Social home page Coder Social logo

phosphor-icons / react Goto Github PK

View Code? Open in Web Editor NEW
1.1K 1.1K 57.0 15.98 MB

A flexible icon family for React

Home Page: https://phosphoricons.com

License: MIT License

HTML 0.01% TypeScript 99.97% CSS 0.01% JavaScript 0.02%
icon-font icon-pack icons react reactjs svg svg-icons

react's Introduction

Important

As part of a major update, we will be replacing the existing phosphor-react package with @phosphor-icons/react. We recommend using this new version, as it has improved performance and a significantly smaller bundle size. No APIs have been changed, so drop-in replacement should be straightforward. The legacy package will continue to receive maintenance, but will not be updated with new icons upstream. Take me to the legacy version ➜

@phosphor-icons/react

Phosphor is a flexible icon family for interfaces, diagrams, presentations — whatever, really. Explore all our icons at phosphoricons.com.

NPM Travis

GitHub stars GitHub forks GitHub watchers Follow on GitHub

Installation

npm i @phosphor-icons/react

Usage

Simply import the icons you need, and add them anywhere in your render method. Phosphor supports tree-shaking, so your bundle only includes code for the icons you use.

import { Horse, Heart, Cube } from "@phosphor-icons/react";

const App = () => {
  return (
    <main>
      <Horse />
      <Heart color="#AE2983" weight="fill" size={32} />
      <Cube color="teal" weight="duotone" />
    </main>
  );
};

React Server Components and SSR

When using Phosphor Icons in an SSR environment, within a React Server Component, or in any environment that does not permit the use of the Context API (Next.js Server Component, for example), import icons from the /dist/ssr submodule:

import { Fish } from "@phosphor-icons/react/dist/ssr";

const MyServerComponent = () => {
  return <Fish weight="duotone" />;
};

Note

These variants do not use React Context, and thus cannot inherit styles from an ancestor IconContext.

Props

Icon components accept all props that you can pass to a normal SVG element, including inline style objects, onClick handlers, and more. The main way of styling them will usually be with the following props:

  • color?: string – Icon stroke/fill color. Can be any CSS color string, including hex, rgb, rgba, hsl, hsla, named colors, or the special currentColor variable.
  • size?: number | string – Icon height & width. As with standard React elements, this can be a number, or a string with units in px, %, em, rem, pt, cm, mm, in.
  • weight?: "thin" | "light" | "regular" | "bold" | "fill" | "duotone" – Icon weight/style. Can also be used, for example, to "toggle" an icon's state: a rating component could use Stars with weight="regular" to denote an empty star, and weight="fill" to denote a filled star.
  • mirrored?: boolean – Flip the icon horizontally. Can be useful in RTL languages where normal icon orientation is not appropriate.
  • alt?: string – Add accessible alt text to an icon.

Context

Phosphor takes advantage of React Context to make applying a default style to all icons simple. Create an IconContext.Provider at the root of the app (or anywhere above the icons in the tree) and pass in a configuration object with props to be applied by default to all icons:

import { IconContext, Horse, Heart, Cube } from "@phosphor-icons/react";

const App = () => {
  return (
    <IconContext.Provider
      value={{
        color: "limegreen",
        size: 32,
        weight: "bold",
        mirrored: false,
      }}
    >
      <div>
        <Horse /> {/* I'm lime-green, 32px, and bold! */}
        <Heart /> {/* Me too! */}
        <Cube /> {/* Me three :) */}
      </div>
    </IconContext.Provider>
  );
};

You may create multiple Contexts for styling icons differently in separate regions of an application; icons use the nearest Context above them to determine their style.

Note

The context will also pass any provided SVG props down to icon instances, which can be useful E.G. in adding accessible aria-labels, classNames, etc.

Note

React Context is not available in some environments. See React Server Components and SSR for details.

Composability

Components can accept arbitrary SVG elements as children, so long as they are valid children of the <svg> element. This can be used to modify an icon with background layers or shapes, filters, animations, and more. The children will be placed below the normal icon contents.

The following will cause the Cube icon to rotate and pulse:

const RotatingCube = () => {
  return (
    <Cube color="darkorchid" weight="duotone">
      <animate
        attributeName="opacity"
        values="0;1;0"
        dur="4s"
        repeatCount="indefinite"
      ></animate>
      <animateTransform
        attributeName="transform"
        attributeType="XML"
        type="rotate"
        dur="5s"
        from="0 0 0"
        to="360 0 0"
        repeatCount="indefinite"
      ></animateTransform>
    </Cube>
  );
};

Note

The coordinate space of slotted elements is relative to the contents of the icon viewBox, which is 256x256 square. Only valid SVG elements will be rendered.

Imports

You may wish to import all icons at once for use in your project, though depending on your bundler this could prevent tree-shaking and make your app's bundle larger.

import * as Icon from "@phosphor-icons/react";

<Icon.Smiley />
<Icon.Folder weight="thin" />
<Icon.BatteryHalf size="24px" />

For information on using Phosphor Icons in Server Components, see See React Server Components and SSR.

Custom Icons

It is possible to extend Phosphor with your custom icons, taking advantage of the styling and context abstractions used in our library. To create a custom icon, first design your icons on a 256x256 pixel grid, and export them as SVG. For best results, flatten the icon so that you only export assets with path elements. Strip any fill or stroke attributes, as these will be inherited from the wrapper.

Next, create a new React forwardRef component, importing the IconBase component, as well as the Icon and IconWeight types from this library. Define a Map<IconWeight, ReactElement> that maps each icon weight to the contents of each SVG asset, effectively removing the wrapping <svg> element from each. Name your component, and render an <IconBase />, passing all props and the ref, as well as the weights you defined earlier, as JSX props:

import { forwardRef, ReactElement } from "react";
import { Icon, IconBase, IconWeight } from "@phosphor-icons/react";

const weights = new Map<IconWeight, ReactElement>([
  ["thin", <path d="..." />],
  ["light", <path d="..." />],
  ["regular", <path d="..." />],
  ["bold", <path d="..." />],
  ["fill", <path d="..." />],
  [
    "duotone",
    <>
      <path d="..." opacity="0.2" />
      <path d="..." />
    </>,
  ],
]);

const CustomIcon: Icon = forwardRef((props, ref) => (
  <IconBase ref={ref} {...props} weights={weights} />
));

CustomIcon.displayName = "CustomIcon";

export default CustomIcon;

Note

If you have multiple child elements, wrap them in a Fragment. Typically our duotone icons have multiple elements, with the background layer at 20% opacity.

If Custom Icons are intended to be used in React Server Components, use <SSRBase /> instead of <IconBase /> as the render component.

Our Related Projects

Community Projects

If you've made a port of Phosphor and you want to see it here, just open a PR here!

License

MIT © Phosphor Icons

react's People

Contributors

adamtaylor13 avatar ajmnz avatar bjarkehs avatar dependabot[bot] avatar duongdev avatar hailwood avatar im-me avatar jiyagupta-cs avatar joansentisdev avatar nklhtv avatar rektdeckard avatar samepant avatar sharjeelfaiq avatar theo-staizen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react's Issues

Add modularized imports to the exports field

I was trying to make @phosphor-icons/react work with the new modularized imports feature in Next.js.

It should:

  1. Improve the bundle size
  2. Increase compilation speed thanks to skipping unused files.

I tried adding this configuration to my next.config.js:

const config = {
// ...
  modularizeImports: {
    '@phosphor-icons/react': {
      transform: '@phosphor-icons/react/dist/icons/{{member}}',
    },
  },
// ... 
}

Unfortunately, it fails with the following error:

Error: Package subpath './Trash' is not defined by "exports" in /Users/[REDACTED]/node_modules/@phosphor-icons/react/package.json 

I was reading through @phosphor-icons/react package.json files and saw that that exports field only allows root import. Adding a new subpath fixed the issue:

{
  "exports": {
    ".": {
      "import": "./dist/index.es.js"
    },
    "./*": {
      "import": "./dist/icons/*.es.js"
    }
  },
}

I suggest adding this path to the exports field to allow users opt-in to the modularized imports if they want. I believe it's generally a good practice to allow this.

Importing icons from `@phosphor-icons/react/dist/ssr` renders the icons, but gives issues in the editor

This is the issue description I get from typing:
import { Fish } from '@phosphor-icons/react/dist/ssr';

Could not find a declaration file for module '@phosphor-icons/react/dist/ssr'. 'C:/Work/Projekty/Dezarto/dezarto-next/node_modules/.pnpm/@phosphor-icons[email protected][email protected][email protected]/node_modules/@phosphor-icons/react/dist/ssr/index.mjs' implicitly has an 'any' type.
There are types at 'c:/Work/Projekty/Dezarto/dezarto-next/node_modules/@phosphor-icons/react/dist/ssr/index.d.ts', but this result could not be resolved when respecting package.json "exports". The '@phosphor-icons/react' library may need to update its package.json or typings.ts(7016)

Despite that, the icon renders correctly in dev. It does, however, disable autocomplete suggestions in the editor, which makes working with icons harder.

UnhandledRejection Error: Cannot Find React Package

I'm encountering an unhandled rejection error with the following details:

64.64 unhandledRejection Error [ERR_MODULE_NOT_FOUND]: Cannot find package '/usr/src/app/node_modules/@phosphor-icons/react/dist/node_modules/.pnpm/[email protected]/node_modules/react/' imported from /usr/src/app/node_modules/@phosphor-icons/react/dist/node_modules/.pnpm/[email protected]/node_modules/react/cjs/react-jsx-runtime.production.min.mjs
64.64 Did you mean to import react/index.js?
64.64     at new NodeError (node:internal/errors:399:5)
64.64     at legacyMainResolve (node:internal/modules/esm/resolve:235:9)
64.64     at packageResolve (node:internal/modules/esm/resolve:876:14)
64.64     at moduleResolve (node:internal/modules/esm/resolve:938:20)
64.64     at defaultResolve (node:internal/modules/esm/resolve:1153:11)
64.64     at nextResolve (node:internal/modules/esm/loader:163:28)
64.64     at ESMLoader.resolve (node:internal/modules/esm/loader:838:30)
64.64     at ESMLoader.getModuleJob (node:internal/modules/esm/loader:424:18)
64.64     at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:77:40)
64.64     at link (node:internal/modules/esm/module_job:76:36) {
64.64   type: 'Error',
64.64   code: 'ERR_MODULE_NOT_FOUND'
64.64 }

It seems like the React package is not being found properly. The error suggests that it cannot locate the React package at a specific path. The message also includes a suggestion: "Did you mean to import react/index.js?"

OS: MacOs, Node.js, Docker
Stack:

  • @phosphor-icons/react version 2.1.4
  • Next.js version 13.4.7
  • React version 18.2.0
  • React-dom version 18.2.0

Global packages:

  • Node.js version 18.16.0
  • npm version 9.8.1

Any insights or guidance on resolving this issue would be greatly appreciated.

Found this issue when trying to build my library

Hello,
I try using this instead the previous phosphor-react but found an issue It's failing to compile with my project, and had to revert.
seems similar to this issue on vue: phosphor-icons/vue#23

My project is using
react 18
rollup v3

The error

ERROR in ./node_modules/@phosphor-icons/react/dist/lib/IconBase.es.js 25:16
Module parse failed: Unexpected token (25:16)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|       ref: i,
|       xmlns: "http://www.w3.org/2000/svg",
>       width: t ?? o,
|       height: t ?? o,
|       fill: s ?? w,
 @ ./node_modules/@phosphor-icons/react/dist/icons/XSquare.es.js 3:0-38 35:52-53
 @ ./node_modules/@phosphor-icons/react/dist/index.es.js
 @ ./stories/timeStone/icons/icons.stories.jsx
 @ ./stories sync ^\.(?:(?:^|\/|(?:(?:(?!(?:^|\/)\.).)*?)\/)(?!\.)(?=.)[^/]*?\.stories\.(js|jsx|ts|tsx))$
 @ ./.storybook/generated-stories-entry.js

bundle size

Hi, I've been using phosphor-react in some projects and I identified some bundle size problems.. Analysing the bundle I could realize that phosport-react is using almost 60% of the space used.

I don't know it's the expected behavior so I opened this issue to report this situation!

bundle-size-phosport

Invariant Violation: View config getter callback for component `path` must be a function (received `undefined`)

i am getting this error when i try to use any icon from this package ("@phosphor-icons/react": "^2.0.10") it works just fine when i use the previous phosphor-react-native": "^1.1.2".

I am getting the following error
Invariant Violation: View config getter callback for component path must be a function (received undefined). Make sure to start component names with a capital letter.

This error is located at:
in path
in svg (created by IconBase)
in IconBase (created by Star)
in Star (created by UserRecords)
in RCTView (created by View)
in View
in Unknown

My Env:

"react-native": "0.71.8",
"expo": "~48.0.18",

HandWaving icon does not handle `weight="fill"` properly

My code:

<HandWavingIcon size={32} color="#EDC281" weight="fill" />

Results:
image

By comparison I changed the import to a star and used the same alias (so that we keep the above HTML exactly the same) like so:

import {
  Star as HandWavingIcon,
} from 'phosphor-react';

results:
image

allow to add Contributing.md file.

Hi 👋 @rektdeckard Please allow me to add Contributing.md file. Please also check my PR #74 , if need any changes suggest me, Please Consider my contribution I am new in open source and Participating first time in Hacktoberfest and Hacksquad events, please merge it. Thanks

SSR Components missing default size="1em"

TL;DR: I believe the following line of code should change from size, to size = "1em",
https://github.com/phosphor-icons/react/blob/master/src/lib/SSRBase.tsx#L12


A very common pattern is that we have, is that we want our icons to follow the text font size, which works great for client components, since their width/height defaults to 1em. For example (using tailwind classes)

<a className="text-2xl" href="/docs">
  <ArrowRight />
  Go to Documentation
</a>

This does not work as expected for SSR components, because by default, they do not have width/height set to 1em.

I understand that the components fom dist/ssr are not using React Context, but we should still have the same sensible defaults even for SSR (something that we have for color and weight), but just not be able to change them, because we cant use context.

Export alias/tags for each icons similarly to how the search work in the documentation

I assume that since the search in the Phosphor icon documentation match or more than the name of the icon itself, the information to buidd those tags should already exist somewhere.

Screenshot 2022-10-31 at 11 42 59

Similarly to how we do :

Airplane.displayName = "Airplane";

we could do :

Airplane.tags = ["Airplane","Plane","Fight", ... ];


Use case :

Allowing users in an app to pick an icon for a given primitive. Enabling a search by tag in the front end would be great.
Same in the Figma library, adding those tags to the icon description would make it so much easier to search

Jest test fails if importing directly from `/dist` folder

(This was already reported in a related issue, #62, but I think it's different because I don't use NextJS).

I am trying to use @swc/plugin-transform-imports to automatically transform the imports and hoping to speed up my Jest tests.

However it's always failing with the same error as the OP of the related issue, Cannot find module '@phosphor-icons/react/dist/csr/Horse' from ....

The reason why I'm doing this is that it seems barrel imports can be a huge slow down for Jest tests, as explained in jestjs/jest#11234.

              '@swc/plugin-transform-imports',
              {
                '@phosphor-icons/react': {
                  transform: '@phosphor-icons/react/dist/{csr|ssr}/{{member}}',
                  skip_default_conversion: true,
                },
                '@mui/icons-material': {
                  transform: '@mui/icons-material/{{member}}',
                },
              },

Note that it's also failing if I don't use @swc/plugin-transform-imports at all, and try to import the full path directly in my component as

import { Horse } from '@phosphor-icons/react/dist/csr/Horse';

If it helps, this is the transformed code:

const _Horse = _interop_require_default._(require("@phosphor-icons/react/dist/csr/Horse"));

For comparison, using the MUI icons, we can import directly as

import StarIcon from  '@mui/icons-material/Star'

and that will import the CommonJS icon.

Would you know if that can be supported somehow?

I see they're all compiled in a single file in @phosphor-icons/react/dist/index.cjs, thus maybe the solution would be to have all icons in different dist/cjs/*.js files instead, and that @phosphor-icons/react/dist/index.cjs requires them from there instead? I can attempt a PR if that makes sense!

Amazing library by the way!

Error caused by `exports` field in `package.json`

Describe the bug
Using the latest version of the package (v2.0.4) along with esbuild and Next.js v13 this error pops up in the console when trying to import any icon from the library.

Package path . is not exported from package /my_pc_project_path/node_modules/@phosphor-icons/react (see exports field in /my_pc_project_path/node_modules/@phosphor-icons/react/package.json)

Looking up the path reported I can see this entry

// other stuff...
"exports": {
  ".": {
    "import": "./dist/index.es.js"
  }
},
// more stuff...

To Reproduce
It is quite the hassle, it invlolves setting up a monorepo with Turborepo and creating different apps and packages. If necessary I can provide a link to my repository.

Expected behavior
I expect the app to work without throwing any errors both in developement and production.

Desktop:

  • OS: Fedora Linux 36 (Workstation Edition)
  • Browser: Brave
  • Version: Version 1.48.164 Chromium: 110.0.5481.100 (Official Build) (64-bit)

Cannot find package on node 20

Describe the bug

When I try to use the icons in a nextjs project on node 20.12.0 I get the following error.

Cannot find package '/pathtoproject/node_modules/@phosphor-icons/react/dist/node_modules/.pnpm/[email protected]/node_modules/react/package.json'

Steps to Reproduce

Try using it in a node 20 react project

Expected behavior

No errors

Context (please complete the following information):

  • OS: Mac OS 14.4
  • @phosphor-icons/react
  • Version 2.1.4

use as font

It's possible to use as font? to pass as component parameter without pass as object?

Tree shaking

The whole package will be included when I import any icons from phosphor-react.

Could you please consider supporting tree shaking? Thank you.

./node_modules/@phosphor-icons/react/dist/lib/context.mjs Can't import the named export 'createContext' from non EcmaScript module (only default export is available)

Describe the bug

Unable to build the project after doing npm install with latest build v2.1.4

Steps to Reproduce

Install v2.1.4 and try to run react project you will find the issue in console

./node_modules/@phosphor-icons/react/dist/lib/context.mjs
Can't import the named export 'createContext' from non EcmaScript module (only default export is available)

Expected behavior

No error should be reported in console or in browser. It should work as normal.

Screenshots

image image

Context (please complete the following information):

  • OS: Windows 11 Home
  • Browser: Chrome
  • Library: @phosphor-icons/react
  • Version: v2.1.4

Issue updating past 2.1.3

Describe the bug

After updating from 2.1.3 to 2.1.4 I can no longer run my vitests within a react 18 + node v20 + vite 5 repo, as phosphor starts throwing import errors.

Steps to Reproduce

Upgrade from 2.1.3 to 2.1.4 and watch vitest fail to resolve imports within phosphor.

Expected behavior

No import issues in vitest, like in 2.1.3.

Screenshots

Context (please complete the following information):

    "react": "^18.0.0",
    "react-dom": "^18.0.0",
    "react-router-dom": "^6.3.0"
    "@phosphor-icons/react": "2.1.4",
    "vite": "^5.2.7",
    "vitest": "^1.4.0",

Screenshot 2024-04-16 at 12 38 42 PM

Error: Cannot find package '/Users/johnshankman/Documents/manifoldxyz/studio-app-devtools/node_modules/@phosphor-icons/react/dist/node_modules/.pnpm/[email protected]/node_modules/react/package.json' imported from /Users/johnshankman/Documents/manifoldxyz/studio-app-devtools/node_modules/@phosphor-icons/react/dist/node_modules/.pnpm/[email protected]/node_modules/react/cjs/react-jsx-runtime.production.min.mjs
Did you mean to import react/index.js?

Additional notes

Downgrading back to 2.1.0 exactly produces no issues.

Incorrect exports specified in `package.json`

Discussed in #95

Originally posted by diegolauar April 23, 2024
If you get this error: Failed to resolve entry for package "@phosphor-icons/react". The package may have incorrect main/module/exports specified in its package.json.

Try install: npm install phosphor-react

Use: import { . . . } from "phosphor-react"

SSR component types are not resolving

When I attempt to use the dist/ssr icons, i see this error:

Could not find a declaration file for module '@phosphor-icons/react/dist/ssr'. 'node_modules/@phosphor-icons/react/dist/ssr/index.mjs' implicitly has an 'any' type.
  There are types at '/node_modules/@phosphor-icons/react/dist/ssr/index.d.ts', but this result could not be resolved when respecting package.json "exports". The '@phosphor-icons/react' library may need to update its package.json or typings.ts(7016)

After some brief searching i found this thread and this tool which illustrates only the dist/ssr package error.

Screen Shot 2023-10-11 at 11 50 10 AM

thanks!

Error: EMFILE: too many open files

Moving from "phosphor-react" to "@phosphor-icons/react", I've got the following issues when deploying on Vercel in a Nextjs application:

[Error: EMFILE: too many open files, open '/var/task/node_modules/@phosphor-icons/react/dist/icons/SidebarSimple.es.js'] {
  errno: -24,
  code: 'EMFILE',
  syscall: 'open',
  path: '/var/task/node_modules/@phosphor-icons/react/dist/icons/SidebarSimple.es.js',
  page: '/guides'
}
RequestId: 2c953896-3cf8-4f3a-8bb0-86de2ca6662c Error: Runtime exited with error: exit status 1
Runtime.ExitError

I'm still using the /pages directory, haven't moved to /app yet in my codebase.

Tried to upgrade my Node server from v16 to v18, no luck.

SidebarSimple is not even used in my code.

Looks like it's bugging when I need to check the auth state with NextAuthjs. So perhaps there's a conflict with the signIn and signOut methodes from this other library, as I can see a lot of similar errors in my logs.

Let me know if I can bring more context.

React warning after update to 2.1.4

Describe the bug

After an update from 2.1.3 to 2.1.4 (but also NextJS/React updates so I can't precisely trace the reason) I've started to receive this warning:

Warning: React does not recognize the `dataSlot` prop on a DOM element. 
If you intentionally want it to appear in the DOM as a custom attribute, 
spell it as lowercase `dataslot` instead. If you accidentally passed 
it from a parent component, remove it from the DOM element.
    at svg
    at IconBase
    at HiOutlineUsers
    at div

I don't have dataSlot anywhere in the code so it should be something internal to the library.

Unble to dynamic import icons .mjs extensions

This always throws errors when try to dynamicly import, i think its because of the files extesion .mjs but cant figure it out, already tried cra clean projects, vite clean projects etc

import { Suspense, lazy } from "react";
import "./styles.css";

function IconTest (props: any) {
  const { icon } = props;

  const IconComponent = lazy(() =>
    import(`@phosphor-icons/react/dist/csr/${icon}`).then((r) => {
      console.log("r", r);
      return { default: r[icon] ? r[icon] : () => null };
    })
  );

  // check suspense needed
  return (
    <span role="img" className="test-icon">
      <Suspense fallback="...">
        <IconComponent />
      </Suspense>
    </span>
  );
}

// HOW WOULD WE USE IT:
export default function App() {
  return (
    <>
      <IconTest icon="Infinity" />
      <IconTest icon="Activity" />
      <IconTest icon="AddressBook" />
    </>
  );
}

image

is csr the wrong folder for dynamic import?
very simple to replicate

yarn create react-app my-app --template typescript
yarn add @phosphor-icons/react
add the dynamic import to some icon
yarn start

already tried with other libs example remixicon-react works fine, cant seem to find whats the problem with phosphor package for it to dont work

for now importing this way but the bundle size and app startup its huge, page loading like 40mb download because its importing all existing icons...

 import(`@phosphor-icons/react`).then

'use client' in client icons and IconContext

Describe the bug

Not really a bug, but rather a feature request.

When using an icon with Next.js App Router, one would need to either use the server component version (under /dist/ssr) or make the outer component a client component. The former doesn't support the use of IconContext, and the latter is a mild inconvenience. Would be very nice to be able to use the client icons directly inside server components.

An approach to this is to have 'use client' at the top of every client icon file and introduce a IconProvider component (with use client), which simply forwards all icon props to the underlying IconContext. I am unsure if these additions will make for a breaking change, but they are pretty straightforward for massive DX improvement.

A React Server Component can then be written concisely like so:

// page.tsx
import { IconProvider, User as UserIcon } from '@phosphor-icons/react';

export default function UserPage() {
  return (
    <IconProvider size={20}>
      <div className="blah blah">
        <UserIcon />
      </div>
    </IconProvider>
  );
}

Steps to Reproduce

N/A

Expected behavior

N/A

Screenshots

N/A

Context (please complete the following information):

N/A

Additional notes

I can certainly help with this, but need to know any potential implications on users who don't use React Server Components or Next.js

Invalid hook call when using in Gutenberg

Trying to use these in a Gutenberg block (new WordPress editor - which is React essentially). Followed instructions on Github.
Getting:
react-dom.min.js?ver=17.0.1:9 Error: Minified React error #321; visit https://reactjs.org/docs/error-decoder.html?invariant=321 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
at Object.it (react-dom.min.js?ver=17.0.1:9:43163)
at e.useContext (react.min.js?ver=17.0.1:9:10470)
at Object.render (IconBase.esm.js:15:31)
at X (element.min.js?ver=47162ff4492c7ec4956b:9:6463)
at X (element.min.js?ver=47162ff4492c7ec4956b:9:6459)
at Z (element.min.js?ver=47162ff4492c7ec4956b:9:7257)
at B (element.min.js?ver=47162ff4492c7ec4956b:9:6804)
at X (element.min.js?ver=47162ff4492c7ec4956b:9:6197)
at xr (blocks.min.js?ver=69022aed79bfd45b3b1d:10:4703)
at blocks.min.js?ver=69022aed79bfd45b3b1d:10:33666

import { Horse } from "phosphor-react"; import { useBlockProps } from '@wordpress/block-editor'; export default function Edit() { return ( <div { ...useBlockProps() }> { __( 'Phosphor Icons – hello from the editor!', 'phosphor-icons' ) } <Horse /> </div> ); }
Error only occurs once I add Horse component
Any ideas here?

CHANGELOGS

Please implement a CHANGELOG. There are breaking changes happening (export renaming) on minor versions and having to go through commits to figure out why, or if it'll affect someone, is less-than-ideal.

Thank you.

React native support?

Is react native supported? If so can we add the integration steps in the documentation.
Usually font icons works on react native using react native vector icons library. But Phosphor icon support is not there yet.

Refactoring and some suggestions for improvements.

  • I'll bring modifications for start a PR refac of the exportations in the src/index.ts, because a lot of lines repeat.
  • a proposal for new name of "GameController" because it more generic and I encountered "Joystick" to fit well in this case and compatible with the visual icon.
  • at the core\src\icons.ts I think it more comprehensible the legacy icons being presented in the list as such as this example:
 name: "file-dashed",
    pascal_name: "FileDashed",
    legacy: {
      alias_name: "file-dotted",
      pascal_name: "FileDotted",
      changed_in: 2.0,
    },

And the prop changed_in a propose for register knowing when the legacy started (the future we don't know).


And some cases that the icon is published the first time, it's not necessary to fill prop updated_in cause it occurred at the same time this new implementation.

  { ...........,
    published_in: 1.4,
    updated_in: 1.4,
  },

would be only for this case

  { ..........,
    published_in: 1.4,
  },

What do you say about that ? Can assign me for this work ? I almost finished it.

Support next.js app router/RSC

Since the icons require context to work they fail in a server component.

Adding "use client" to them should fix it, as I didn't manage to get it to work with a custom context...

Export the SVG files

Is there any way to import the SVGs directly from phosphor-react? I looked in the other Phosphor packages but couldn't find a way. For those using Next.js with SVGR this would allow such usage with dynamic import.

const svg = {
  heart: dynamic<SVGProps<SVGSVGElement>>(() =>
    import('phosphor-react/svgs/heart.svg').then((mod) => mod.ReactComponent)
  ),
  ...
}

const Icon = ({ icon, ...props }) => {
  const Svg = svg[icon];

  return <Svg {...props} />;
};

Could not find a declaration file when using SSR

When trying to import from @phosphor-icons/react/dist/ssr, I get the following error:

Could not find a declaration file for module '@phosphor-icons/react/dist/ssr'. '<redacted>/node_modules/@phosphor-icons/react/dist/ssr/index.mjs' implicitly has an 'any' type.
  There are types at '<redacted>/node_modules/@phosphor-icons/react/dist/ssr/index.d.ts', but this result could not be resolved when respecting package.json "exports". The '@phosphor-icons/react' library may need to update its package.json or typings.ts(7016)

Found this issue: microsoft/TypeScript#52363
Seems to be something introduced in TypeScript 5.0 that package maintainers need to update. I am using TypeScript 5.2.2.

Can anyone confirm this?

Icon instance className overwrites context className

If I specify a className in my context provider, eg.

    <IconContext.Provider
      value={{ className: 'icon' }}
      ...
   />

And then specify a className when I use my icon, eg. <CalendarCheck className="foo" />,
... then my icon only gets the foo className and I can no longer target the element with the .icon selector.

I'd propose bringing in a small library like clsx and updating IconBase to merge the two className values on the <svg> element, eg. className={clsx(contextClassName, className)}.

I'd be happy to create a PR with the proposed changes, given a bit of guidance on how to contribute to this project (and an okay for adding a third-party dependency).

PhosphorIcon 2.0.9 - require() of ES modules is not supported

In our Design System we have an icon package that uses PhosphorIcon. This package is built both in cjs and esm.

With the 2.0.9 version, presumably after the insertion of type: “module” in the package.json file, we encountered this error when trying to build a Next.js app with our DS icon package.

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /app/node_modules/@phosphor-icons/react/dist/index.umd.js
require() of ES modules is not supported.
require() of /app/node_modules/@phosphor-icons/react/dist/index.umd.js from /app/node_modules/@docsity/ui-kit-icons/lib/cjs/index.js is an ES module file as it is a .js file whose nearest parent package.json contains “type”: “module” which defines all .js files in that package scope as ES modules.
Instead rename index.umd.js to end in .cjs, change the requiring code to use import(), or remove “type”: “module” from /app/node_modules/@phosphor-icons/react/package.json.
    at new NodeError (internal/errors.js:322:7)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1131:13)
    at Module.load (internal/modules/cjs/loader.js:979:32)
    at Function.Module._load (internal/modules/cjs/loader.js:819:12)
    at Module.require (internal/modules/cjs/loader.js:1003:19)
    at require (internal/modules/cjs/helpers.js:107:18)
    at Object.<anonymous> (/app/node_modules/@docsity/ui-kit-icons/lib/cjs/index.js:7:17)
    at Module._compile (internal/modules/cjs/loader.js:1114:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1143:10)
    at Module.load (internal/modules/cjs/loader.js:979:32) {
  code: ‘ERR_REQUIRE_ESM’
}
error Command failed with exit code 1.

Reverting to 2.0.8 solved the problem but we are concerned about the impossibility to use the latest version of your library if we can't find a solution.

We are using:
yarn 1.22.19
react 17.0.2
typescript 4.3.2
lerna 4.0.0

Add support for server components

With the release of React 18 (and NextJS 13), server components are supported and will most certainly get utilized more going forward. It would be nice of phosphor-react to support this. It does currently seem to be limited by the usage of React.Context.

Possible solutions would be to use the "use client" directive (reactjs/rfcs#227) or in some way make the context optional.

Cannot read properties of undefined (reading 'createContext')

Hello we're seeing an issue when consuming our toolkit library in a new project.

Screenshot 2023-09-14 at 15 27 17

I'll try to give a brief description of the project structure since it's quite big.

Our Component Toolkit Lib

This library contains lots of react components as well as Icons and is bundled and then consume via npm in the child application. The library is using styled-components and uses a ThemeProvider to wrap our application.

Since we're using many different Icons from phosphor and want to "theme" them in a common way, we created a component called Icon which accepts a recognised IconName. We then use that name to map it to an Icon within @phosphor/react

Example of our icon-map.ts file:

import { Armchair, Baby } from '@phosphor/react'

const iconMap: Record<IconName, Icon> = {
  armchair: Armchair,
  baby: Baby
}

export default iconMap

And then to consume these icons we look them up in the Icon.tsx file:

// This is a simplified version but the pattern is correct

type IconProps = {
  name: 'armchair' | 'baby'
  color: string
}

const Icon: FC<IconProps> = ({ name, color }) => {
  const Component = iconMap[name]
  
  return <Component color={color} />
}

The problem then occurs when we use our library in the consuming applications.

export const start = () => {
  ReactDOM.render(
    <ThemeProvider theme='default'>
      <div>This is our application</div>
    </ThemeProvider>,
    document.getElementById('root'),
  )
}

And then we see the problem. Any ideas?

These are the main versions we're using in our application:

"dependencies": {
  "@reduxjs/toolkit": "^1.9.5",
  "react": "^18.0.2",
  "react-dom": "^18.0.2",
  "react-redux": "^8.1.2",
  "@phosphor-icons/react": "^2.0.6"
},
"devDependencies": {
  "@babel/cli": "^7.21.0",
  "@babel/core": "^7.21.0",
  "@babel/plugin-proposal-class-properties": "^7.0.0",
  "@babel/plugin-proposal-decorators": "^7.8.3",
  "@babel/plugin-syntax-dynamic-import": "^7.0.0",
  "@babel/plugin-transform-runtime": "^7.21.0",
  "@babel/preset-env": "^7.20.2",
  "@babel/preset-react": "^7.18.6",
  "@babel/preset-typescript": "^7.21.0",
  "@pmmmwh/react-refresh-webpack-plugin": "^0.5.10",
  "@types/node": "^20.5.9",
  "babel-loader": "8.1.0",
  "babel-plugin-import": "^1.13.6",
  "clean-webpack-plugin": "^4.0.0",
  "copy-webpack-plugin": "^11.0.0",
  "css-loader": "^6.7.3",
  "dotenv-webpack": "^8.0.1",
  "html-replace-webpack-plugin": "^2.6.0",
  "html-webpack-plugin": "^5.5.0",
  "mini-css-extract-plugin": "^2.7.2",
  "process": "0.11.10",
  "react-hot-loader": "^4.13.1",
  "react-refresh": "^0.14.0",
  "sass": "^1.66.1",
  "sass-loader": "^13.2.0",
  "tsconfig-paths-webpack-plugin": "^4.0.1",
  "typescript": "^5.2.2",
  "webpack": "^5.0.0",
  "webpack-cli": "^4.3.0",
  "webpack-dev-server": "^4.11.1",
  "webpack-merge": "^5.8.0"
}

lib is not exported from package.json

I had trouble with tree shaking with next.js so I had to use

  modularizeImports: {
    '@phosphor-icons/react': {
      transform: '@phosphor-icons/react/dist/icons/{{member}}',
    },
}

in my next.config.js to make the tree shaking work, but that broke IconContext because it tried to import it from icons as well.
so I exported it in package.json and now I can import like so:
import { IconContext } from '@phosphor-icons/react/dist/lib/context'

I think the lib inside dist should be exported like the icons.

Error 504 (Gateway Timeout) when using icon component

I have this error when using the phosphor-icons lib with vitte, I've used it before with a project with webpack and I've never had this error, does anyone know why?

image

i use component like this, importing from '@phosphor-icons/react'
image

I added this configuration in the json package to try to solve it but without success
image

Cannot import Pulse icon

Hello,

Pulse icon seems not to be part of importable icons in phosphor-react (1.4.1).
I can import several other icons but trying to import Pulse is returning an error.

Full import command:

Details

import {
BellSimple,
Bird,
CalendarBlank,
CaretLeft,
ChatCentered,
ChatCircleDots,
CoinVertical,
DotsThreeCircleVertical,
Fire,
GenderFemale,
Ghost,
Hash,
Medal,
Megaphone,
StarFour,
User,
Pulse,
} from "phosphor-react";

Terminal output:
export 'Pulse' (imported as 'Pulse') was not found in 'phosphor-react'

Full terminal output:

Details

export 'Pulse' (imported as 'Pulse') was not found in 'phosphor-react' (possible exports: Activity, AddressBook, Airplane, AirplaneInFlight, AirplaneLanding, AirplaneTakeoff, AirplaneTilt, Airplay, Alarm, Alien, AlignBottom, AlignBottomSimple, AlignCenterHorizontal, AlignCenterHorizontalSimple, AlignCenterVertical, AlignCenterVerticalSimple, AlignLeft, AlignLeftSimple, AlignRight, AlignRightSimple, AlignTop, AlignTopSimple, Anchor, AnchorSimple, AndroidLogo, AngularLogo, Aperture, AppStoreLogo, AppWindow, AppleLogo, ApplePodcastsLogo, Archive, ArchiveBox, ArchiveTray, Armchair, ArrowArcLeft, ArrowArcRight, ArrowBendDoubleUpLeft, ArrowBendDoubleUpRight, ArrowBendDownLeft, ArrowBendDownRight, ArrowBendLeftDown, ArrowBendLeftUp, ArrowBendRightDown, ArrowBendRightUp, ArrowBendUpLeft, ArrowBendUpRight, ArrowCircleDown, ArrowCircleDownLeft, ArrowCircleDownRight, ArrowCircleLeft, ArrowCircleRight, ArrowCircleUp, ArrowCircleUpLeft, ArrowCircleUpRight, ArrowClockwise, ArrowCounterClockwise, ArrowDown, ArrowDownLeft, ArrowDownRight, ArrowElbowDownLeft, ArrowElbowDownRight, ArrowElbowLeft, ArrowElbowLeftDown, ArrowElbowLeftUp, ArrowElbowRight, ArrowElbowRightDown, ArrowElbowRightUp, ArrowElbowUpLeft, ArrowElbowUpRight, ArrowFatDown, ArrowFatLeft, ArrowFatLineDown, ArrowFatLineLeft, ArrowFatLineRight, ArrowFatLineUp, ArrowFatLinesDown, ArrowFatLinesLeft, ArrowFatLinesRight, ArrowFatLinesUp, ArrowFatRight, ArrowFatUp, ArrowLeft, ArrowLineDown, ArrowLineDownLeft, ArrowLineDownRight, ArrowLineLeft, ArrowLineRight, ArrowLineUp, ArrowLineUpLeft, ArrowLineUpRight, ArrowRight, ArrowSquareDown, ArrowSquareDownLeft, ArrowSquareDownRight, ArrowSquareIn, ArrowSquareLeft, ArrowSquareOut, ArrowSquareRight, ArrowSquareUp, ArrowSquareUpLeft, ArrowSquareUpRight, ArrowUDownLeft, ArrowUDownRight, ArrowULeftDown, ArrowULeftUp, ArrowURightDown, ArrowURightUp, ArrowUUpLeft, ArrowUUpRight, ArrowUp, ArrowUpLeft, ArrowUpRight, ArrowsClockwise, ArrowsCounterClockwise, ArrowsDownUp, ArrowsHorizontal, ArrowsIn, ArrowsInCardinal, ArrowsInLineHorizontal, ArrowsInLineVertical, ArrowsInSimple, ArrowsLeftRight, ArrowsOut, ArrowsOutCardinal, ArrowsOutLineHorizontal, ArrowsOutLineVertical, ArrowsOutSimple, ArrowsVertical, Article, ArticleMedium, ArticleNyTimes,
Asterisk, AsteriskSimple, At, Atom, Baby, Backpack, Backspace, Bag, BagSimple, Balloon, Bandaids, Bank, Barbell, Barcode, Barricade, Baseball, Basketball, Bathtub, BatteryCharging, BatteryChargingVertical, BatteryEmpty, BatteryFull, BatteryHigh, BatteryLow, BatteryMedium, BatteryPlus, BatteryWarning, BatteryWarningVertical, Bed, BeerBottle, BehanceLogo, Bell, BellRinging, BellSimple, BellSimpleRinging, BellSimpleSlash, BellSimpleZ, BellSlash, BellZ, BezierCurve, Bicycle, Binoculars, Bird, Bluetooth, BluetoothConnected, BluetoothSlash, BluetoothX, Boat, Book, BookBookmark, BookOpen, Bookmark, BookmarkSimple, Bookmarks, BookmarksSimple, Books, BoundingBox, BracketsAngle, BracketsCurly, BracketsRound, BracketsSquare, Brain, Brandy, Briefcase, BriefcaseMetal, Broadcast, Browser, Browsers, Bug, BugBeetle, BugDroid, Buildings, Bus, Butterfly, Cactus, Cake, Calculator, Calendar, CalendarBlank, CalendarCheck, CalendarPlus, CalendarX,
Camera, CameraRotate, CameraSlash, Campfire, Car, CarSimple, Cardholder, Cards, CaretCircleDoubleDown, CaretCircleDoubleLeft, CaretCircleDoubleRight, CaretCircleDoubleUp, CaretCircleDown,
CaretCircleLeft, CaretCircleRight, CaretCircleUp, CaretDoubleDown, CaretDoubleLeft, CaretDoubleRight, CaretDoubleUp, CaretDown, CaretLeft, CaretRight, CaretUp, Cat, CellSignalFull, CellSignalHigh, CellSignalLow, CellSignalMedium, CellSignalNone, CellSignalSlash, CellSignalX, Chalkboard, ChalkboardSimple, ChalkboardTeacher, ChartBar, ChartBarHorizontal, ChartLine, ChartLineUp, ChartPie, ChartPieSlice, Chat, ChatCentered, ChatCenteredDots, ChatCenteredText, ChatCircle, ChatCircleDots, ChatCircleText, ChatDots, ChatTeardrop, ChatTeardropDots, ChatTeardropText,
ChatText, Chats, ChatsCircle, ChatsTeardrop, Check, CheckCircle, CheckSquare, CheckSquareOffset, Checks, Circle, CircleDashed, CircleHalf, CircleHalfTilt, CircleNotch, CircleWavy, CircleWavyCheck, CircleWavyQuestion, CircleWavyWarning, CirclesFour, CirclesThree, CirclesThreePlus, Clipboard, ClipboardText, Clock, ClockAfternoon, ClockClockwise, ClockCounterClockwise, ClosedCaptioning, Cloud, CloudArrowDown, CloudArrowUp, CloudCheck, CloudFog, CloudLightning, CloudMoon, CloudRain, CloudSlash, CloudSnow, CloudSun, Club, CoatHanger, Code, CodeSimple, CodepenLogo, CodesandboxLogo, Coffee, Coin, CoinVertical, Coins, Columns, Command, Compass, ComputerTower, Confetti, Cookie, CookingPot, Copy, CopySimple, Copyleft, Copyright, CornersIn, CornersOut,
Cpu, CreditCard, Crop, Crosshair, CrosshairSimple, Crown, CrownSimple, Cube, CurrencyBtc, CurrencyCircleDollar, CurrencyCny, CurrencyDollar, CurrencyDollarSimple, CurrencyEth, CurrencyEur, CurrencyGbp, CurrencyInr, CurrencyJpy, CurrencyKrw, CurrencyKzt, CurrencyNgn, CurrencyRub, Cursor, CursorText, Cylinder, Database, Desktop, DesktopTower, Detective, DeviceMobile, DeviceMobileCamera, DeviceMobileSpeaker, DeviceTablet, DeviceTabletCamera, DeviceTabletSpeaker, Diamond, DiamondsFour, DiceFive, DiceFour, DiceOne, DiceSix, DiceThree, DiceTwo, Disc, DiscordLogo,
Divide, Dog, Door, DotsNine, DotsSix, DotsSixVertical, DotsThree, DotsThreeCircle, DotsThreeCircleVertical, DotsThreeOutline, DotsThreeOutlineVertical, DotsThreeVertical, Download, DownloadSimple, DribbbleLogo, Drop, DropHalf, DropHalfBottom, Ear, EarSlash, Egg, EggCrack, Eject, EjectSimple, Envelope, EnvelopeOpen, EnvelopeSimple, EnvelopeSimpleOpen, Equalizer, Equals, Eraser, Exam, Export, Eye, EyeClosed, EyeSlash, Eyedropper, EyedropperSample, Eyeglasses, FaceMask, FacebookLogo, Factory, Faders, FadersHorizontal, FastForward, FastForwardCircle, FigmaLogo,
File, FileArrowDown, FileArrowUp, FileAudio, FileCloud, FileCode, FileCss, FileCsv, FileDoc, FileDotted, FileHtml, FileImage, FileJpg, FileJs, FileJsx, FileLock, FileMinus, FilePdf, FilePlus, FilePng, FilePpt, FileRs, FileSearch, FileText, FileTs, FileTsx, FileVideo, FileVue, FileX, FileXls, FileZip, Files, FilmScript, FilmSlate, FilmStrip, Fingerprint, FingerprintSimple, FinnTheHuman, Fire, FireSimple, FirstAid, FirstAidKit, Fish, FishSimple, Flag, FlagBanner, FlagCheckered, Flame, Flashlight, Flask, FloppyDisk, FloppyDiskBack, FlowArrow, Flower, FlowerLotus, FlyingSaucer, Folder, FolderDotted, FolderLock, FolderMinus, FolderNotch, FolderNotchMinus, FolderNotchOpen, FolderNotchPlus, FolderOpen, FolderPlus, FolderSimple, FolderSimpleDotted, FolderSimpleLock, FolderSimpleMinus, FolderSimplePlus, FolderSimpleStar, FolderSimpleUser, FolderStar, FolderUser, Folders, Football, ForkKnife, FrameCorners, FramerLogo, Function, Funnel,
FunnelSimple, GameController, GasPump, Gauge, Gear, GearSix, GenderFemale, GenderIntersex, GenderMale, GenderNeuter, GenderNonbinary, GenderTransgender, Ghost, Gif, Gift, GitBranch, GitCommit, GitDiff, GitFork, GitMerge, GitPullRequest, GithubLogo, GitlabLogo, GitlabLogoSimple, Globe, GlobeHemisphereEast, GlobeHemisphereWest, GlobeSimple, GlobeStand, GoogleChromeLogo, GoogleLogo, GooglePhotosLogo, GooglePlayLogo, GooglePodcastsLogo, Gradient, GraduationCap, Graph, GridFour, Hamburger, Hand, HandEye, HandFist, HandGrabbing, HandPalm, HandPointing, HandSoap, HandWaving, Handbag, HandbagSimple, HandsClapping, Handshake, HardDrive, HardDrives, Hash, HashStraight, Headlights, Headphones, Headset, Heart, HeartBreak, HeartStraight, HeartStraightBreak, Heartbeat, Hexagon, HighlighterCircle, Horse, Hourglass, HourglassHigh, HourglassLow, HourglassMedium, HourglassSimple, HourglassSimpleHigh, HourglassSimpleLow, HourglassSimpleMedium, House, HouseLine, HouseSimple, IconContext, IdentificationBadge, IdentificationCard, Image, ImageSquare, Infinity, Info, InstagramLogo, Intersect, Jeep, Kanban, Key, KeyReturn, Keyboard, Keyhole, Knife, Ladder, LadderSimple, Lamp, Laptop, Layout, Leaf, Lifebuoy, Lightbulb, LightbulbFilament, Lightning, LightningSlash, LineSegment, LineSegments, Link, LinkBreak, LinkSimple, LinkSimpleBreak, LinkSimpleHorizontal, LinkSimpleHorizontalBreak, LinkedinLogo, LinuxLogo, List, ListBullets, ListChecks, ListDashes, ListNumbers, ListPlus, Lock, LockKey, LockKeyOpen, LockLaminated, LockLaminatedOpen, LockOpen, LockSimple, LockSimpleOpen, MagicWand, Magnet, MagnetStraight, MagnifyingGlass, MagnifyingGlassMinus, MagnifyingGlassPlus, MapPin, MapPinLine, MapTrifold, MarkerCircle, Martini, MaskHappy, MaskSad, MathOperations, Medal, MediumLogo, Megaphone, MegaphoneSimple, MessengerLogo, Microphone, MicrophoneSlash, MicrophoneStage, MicrosoftExcelLogo, MicrosoftPowerpointLogo, MicrosoftTeamsLogo, MicrosoftWordLogo, Minus, MinusCircle, Money, Monitor, MonitorPlay, Moon, MoonStars, Mountains, Mouse, MouseSimple, MusicNote, MusicNoteSimple, MusicNotes, MusicNotesPlus, MusicNotesSimple, NavigationArrow, Needle, Newspaper, NewspaperClipping, Note, NoteBlank, NotePencil, Notebook, Notepad, Notification, NumberCircleEight, NumberCircleFive, NumberCircleFour, NumberCircleNine, NumberCircleOne, NumberCircleSeven, NumberCircleSix, NumberCircleThree, NumberCircleTwo, NumberCircleZero, NumberEight, NumberFive, NumberFour, NumberNine, NumberOne, NumberSeven, NumberSix, NumberSquareEight, NumberSquareFive, NumberSquareFour, NumberSquareNine, NumberSquareOne, NumberSquareSeven, NumberSquareSix, NumberSquareThree, NumberSquareTwo, NumberSquareZero, NumberThree, NumberTwo, NumberZero, Nut, NyTimesLogo, Octagon, Option, Package, PaintBrush, PaintBrushBroad, PaintBrushHousehold, PaintBucket, PaintRoller, Palette, PaperPlane, PaperPlaneRight, PaperPlaneTilt, Paperclip, PaperclipHorizontal, Parachute, Password, Path, Pause, PauseCircle, PawPrint, Peace, Pen, PenNib, PenNibStraight, Pencil, PencilCircle, PencilLine, PencilSimple, PencilSimpleLine, Percent, Person, PersonSimple, PersonSimpleRun, PersonSimpleWalk, Perspective, Phone, PhoneCall, PhoneDisconnect, PhoneIncoming, PhoneOutgoing, PhoneSlash, PhoneX, PhosphorLogo, PianoKeys, PictureInPicture,
Pill, PinterestLogo, Pinwheel, Pizza, Placeholder, Planet, Play, PlayCircle, Playlist, Plug, Plugs, PlugsConnected, Plus, PlusCircle, PlusMinus, PokerChip, PoliceCar, Polygon, Popcorn, Power, Prescription, Presentation, PresentationChart, Printer, Prohibit, ProhibitInset, ProjectorScreen, ProjectorScreenChart, PushPin, PushPinSimple, PushPinSimpleSlash, PushPinSlash, PuzzlePiece, QrCode, Question, Queue, Quotes, Radical, Radio, RadioButton, Rainbow, RainbowCloud, Receipt, Record, Rectangle, Recycle, RedditLogo, Repeat, RepeatOnce, Rewind, RewindCircle, Robot, Rocket, RocketLaunch, Rows, Rss, RssSimple, Rug, Ruler, Scales, Scan, Scissors, Screencast,
ScribbleLoop, Scroll, Selection, SelectionAll, SelectionBackground, SelectionForeground, SelectionInverse, SelectionPlus, SelectionSlash, Share, ShareNetwork, Shield, ShieldCheck, ShieldCheckered, ShieldChevron, ShieldPlus, ShieldSlash, ShieldStar, ShieldWarning, ShoppingBag, ShoppingBagOpen, ShoppingCart, ShoppingCartSimple, Shower, Shuffle, ShuffleAngular, ShuffleSimple,
Sidebar, SidebarSimple, SignIn, SignOut, Signpost, SimCard, SketchLogo, SkipBack, SkipBackCircle, SkipForward, SkipForwardCircle, Skull, SlackLogo, Sliders, SlidersHorizontal, Smiley, SmileyBlank, SmileyMeh, SmileyNervous, SmileySad, SmileySticker, SmileyWink, SmileyXEyes, SnapchatLogo, Snowflake, SoccerBall, SortAscending, SortDescending, Spade, Sparkle, SpeakerHigh, SpeakerLow, SpeakerNone, SpeakerSimpleHigh, SpeakerSimpleLow, SpeakerSimpleNone, SpeakerSimpleSlash, SpeakerSimpleX, SpeakerSlash, SpeakerX, Spinner, SpinnerGap, Spiral, SpotifyLogo, Square, SquareHalf, SquareHalfBottom, SquareLogo, SquaresFour, Stack, StackOverflowLogo, StackSimple, Stamp, Star, StarFour, StarHalf, Sticker, Stop, StopCircle, Storefront, Strategy, StripeLogo, Student, Suitcase, SuitcaseSimple, Sun, SunDim, SunHorizon, Sunglasses, Swap, Swatches, Sword, Syringe, TShirt, Table, Tabs, Tag, TagChevron, TagSimple, Target, Taxi, TelegramLogo, Television, TelevisionSimple, TennisBall, Terminal, TerminalWindow, TestTube, TextAa, TextAlignCenter,
TextAlignJustify, TextAlignLeft, TextAlignRight, TextBolder, TextH, TextHFive, TextHFour, TextHOne, TextHSix, TextHThree, TextHTwo, TextIndent, TextItalic, TextOutdent, TextStrikethrough,
TextT, TextUnderline, Textbox, Thermometer, ThermometerCold, ThermometerHot, ThermometerSimple, ThumbsDown, ThumbsUp, Ticket, TiktokLogo, Timer, ToggleLeft, ToggleRight, Toilet, ToiletPaper, Tote, ToteSimple, TrademarkRegistered, TrafficCone, TrafficSign, TrafficSignal, Train, TrainRegional, TrainSimple, Translate, Trash, TrashSimple, Tray, Tree, TreeEvergreen, TreeStructure, TrendDown, TrendUp, Triangle, Trophy, Truck, TwitchLogo, TwitterLogo, Umbrella, UmbrellaSimple, Upload, UploadSimple, User, UserCircle, UserCircleGear, UserCircleMinus, UserCirclePlus,
UserFocus, UserGear, UserList, UserMinus, UserPlus, UserRectangle, UserSquare, UserSwitch, Users, UsersFour, UsersThree, Vault, Vibrate, VideoCamera, VideoCameraSlash, Vignette, Voicemail, Volleyball, Wall, Wallet, Warning, WarningCircle, WarningOctagon, Watch, WaveSawtooth, WaveSine, WaveSquare, WaveTriangle, Waves, Webcam, WhatsappLogo, Wheelchair, WifiHigh, WifiLow, WifiMedium, WifiNone, WifiSlash, WifiX, Wind, WindowsLogo, Wine, Wrench, X, XCircle, XSquare, YinYang, YoutubeLogo)

Create a Phosphor icons array, which can be later on accessed by index in JSX

Hi I'm creating a Slider Component in which I'd like to render some content (phosphor icon included). Slider hook, which I've created, gives me access to the current index at which the slider points. Would it be possible to render an icon by referencing it from icons array with current slider index? I've tried it already, but types do not match Type 'ForwardRefExoticComponent<IconProps & RefAttributes>' is not assignable to type 'ReactNode' . Thank you for your response.

Compatibility with Astro framework

I'm trying to use Phosphor icons in an Astro project. Astro is a meta-framework similar to Next.js, which allows you to decide whether a React component is generated on the server (SSG), rendered on the server for every request (SSR) or shipped to the client like adefault React SPA.

By default, a React component in Astro will be generated on the server and then shipped to the client as static HTML.

However, this does currently not work with Phosphor Icons. There is an error in the build process:

I've prepared a minimal example: https://stackblitz.com/edit/github-rbetns?file=src%2Fcomponents%2FIconContainer.tsx

 error   Cannot use import statement outside a module
/home/projects/github-rbetns/node_modules/@phosphor-icons/react/dist/index.es.js:1
import { IconContext as o } from "./lib/context.es.js";
^^^^^^

SyntaxError: Cannot use import statement outside a module

This seems to be related to the IconContext – even though I haven't added any. Is there a way to disable/not use the Context at all and still import the React components for the icons?

@phosphor-icons/react doesn't have support for modules, only CommonJS

I was using phosphor-react on my NPM pakcage, and I want to migrate to @phosphor-icons/react, so I can get more icons.
On my package, there is a file src/icons/index.ts where I just export the icons from Phosphor. With phosphor-react, it was working:

export * from 'phosphor-react';

But when I change to @phosphor-icons/react, it gives me the following error message:

TS1479: The current file is a CommonJS module whose imports will produce 'require' calls; however, the referenced file is an ECMAScript module and cannot be imported with 'require'. Consider writing a dynamic 'import("@phosphor-icons/react")' call instead. To convert this file to an ECMAScript module, change its file extension to '.mts', or add the field "type": "module" to 'C:/Users/roich/dev/bioma/bioma-ui/lib/package.json'.

I tried to change the file name to index.mts and add the "type": "module" to my package.json, and none of them were the solution I was looking for.

I suggest this new package supports both CommonJS format and ECMAScript modules.

Jest test fails if files are imported from `/dist` folder

I have this simple test file:

// File: __tests__/index.test.tsx

import * as React from 'react';
import { render, screen } from '@testing-library/react';

import Page from '../src/page';

import '@testing-library/jest-dom';

describe('Home', () => {
  it('renders a heading', () => {
    render(<Page />);

    const heading = screen.getByRole('heading', {
      name: /Redefining SaaS/i,
    });

    expect(heading).toBeInTheDocument();
  });
});

And this component:

// File: src/page.tsx

import * as React from 'react';
import CheckIcon from '@phosphor-icons/react/dist/icons/Check';

export default function Page() {
  return (
    <div>
      <h1>Redefining SaaS</h1>
      <div>
        <CheckIcon />
      </div>
    </div>
  );
}

Apparently the test fails if I try to import the file from /dist/icons folder.

● Test suite failed to run

    Cannot find module '@phosphor-icons/react/dist/icons/Check' from 'src/page'

It works if I change the import line to:

import { Check as CheckIcon } from '@phosphor-icons/react';

Checking the package.json file of this module, it seems that ./dist/* import is allowed.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.