Passing a ref through a FontAwesomeIcon to access SVGElement
Related the component FontAwesomeIcon
Integration with APIs that use DOMElement (like the Tooltip of reactstrap)
7 - This year
Feature request: moar cowbell)Added to this, I think there is value in forwarding all the native element props:
// Seperate FA props from SVG element props
const { icon: iconArgs, mask: maskArgs, symbol, className, title, ...svgProps } = props;
// ..
// Inject svg props on render
return <svg {...svgProps} >//...
Currently, in order to detect events such as onMouseEnter and onHover, it's required to wrap the FontAwesomeIcon component in a span element.
Abstracting the svg element doesn't look to add any value and makes using the component more complicated.
Libraries such as reactjs-popup are unable to use <FontAwesomeIcon /> as trigger since FA doesn't forward ref. I'm now required to wrap FA icons in span for trigger to work.
Looks like this was implemented in #220 and released recently in v1.1.10. I just wired it up in a project and it's working as expected, thanks :)
I'm still getting this error:
index.js:1 Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
Check the render method of `Icon___StyledFontAwesomeIcon`.
in FontAwesomeIcon (created by Icon___StyledFontAwesomeIcon)
in Icon___StyledFontAwesomeIcon (at Icon.js:32)
in ForwardRef (at Task.js:165)
I'm rendering an icon like this:
const Icon = React.forwardRef((props, ref) => {
return <FontAwesomeIcon ref={ref} {...props}></FontAwesomeIcon>;
});
export default Icon;
My package versions:
"dependencies": {
"@fortawesome/fontawesome-svg-core": "^1.2.30",
"@fortawesome/free-brands-svg-icons": "^5.14.0",
"@fortawesome/free-regular-svg-icons": "^5.14.0",
"@fortawesome/free-solid-svg-icons": "^5.14.0",
"@fortawesome/react-fontawesome": "^0.1.11",
Any ideas?
Edit: After carefully reviewing the PR, I understood had to use it like this:
const Icon = React.forwardRef((props, ref) => {
return <FontAwesomeIcon forwardedRef={ref} {...props}></FontAwesomeIcon>;
});
export default Icon;
React-Bootstrap's OverlayTrigger expects being able to use ref. Which forces us to write this in a very ugly way:
const FaInfoCircle = forwardRef((props, ref) => <FontAwesomeIcon forwardedRef={ref} icon={faInfoCircle} {...props} />)
FaInfoCircle.displayName = 'FaInfoCircle'
[...]
<OverlayTrigger overlay={<Tooltip id='somme-id'>Tooltip content</Tooltip>}>
<FaInfoCircle />
</OverlayTrigger>
[...]
rather than
<OverlayTrigger overlay={<Tooltip id='somme-id'>Tooltip content</Tooltip>}>
<FontAwesomeIcon icon={faInfoCircle} />
</OverlayTrigger>
Most helpful comment
Libraries such as
reactjs-popupare unable to use<FontAwesomeIcon />as trigger since FA doesn't forward ref. I'm now required to wrap FA icons in span for trigger to work.