@navinc/base-react-components
Version:
Nav's Pattern Library
25 lines (20 loc) • 960 B
JavaScript
import React, { lazy, Suspense, useMemo } from 'react'
import propTypes from 'prop-types'
import styled from 'styled-components'
const Null = () => null
export const Icon = ({ name = '', ...props }) => {
const IconComponent = import(`./icons/${name}.js`)
const LazyIcon = lazy(() => IconComponent)
// Without a memoized version, rerendering of the same SVG icon sometimes causes a flicker. This stableizes it so it doesn't even try to rerender the same icon
const StableIcon = useMemo(
() => <LazyIcon width="24" height="24" viewBox="0 0 24 24" data-testid={`icon:${name}`} {...props} />,
// eslint doesn't recognize that what is happening here actually is being exhaustive in the dependency array
// eslint-disable-next-line react-hooks/exhaustive-deps
[name, ...Object.values(props)]
)
return <Suspense fallback={<Null />}>{StableIcon}</Suspense>
}
Icon.propTypes = {
name: propTypes.string,
}
export default styled(Icon)``