Home > Enterprise >  Next.js Link error when try to put FontAwesome in the body
Next.js Link error when try to put FontAwesome in the body

Time:10-29

I use react-fontawesome library in my Next.js project. When I try to put any icon inside the Link component there is an error and I don't understand it at all. Can someone explain me why I can't do that? Besides that error, app works fine - it redirects to correct page.

Error (shows only in browser console - there is nothing in terminal about it):
[]

Code:

import Link from 'next/link'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faHeart } from '@fortawesome/free-regular-svg-icons'

const Component = () => {
    return (
        // ...
        <Link href='/followed'>
            <FontAwesomeIcon icon={faHeart} />
        </Link>
        // ...
    )
}

CodePudding user response:

As per the official documentation, you should forwardRef to the child if it is a functional component (FontAwesomeIcon here). Meaning, functional components by default do not accept ref prop passed by the Link component. This is not required if the Link component wraps native elements (e.g div,a) , but since you are using a functional component (either from a third-party library or self-written), it is required to forwardRef the component as the error states.

import Link from 'next/link'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faHeart } from '@fortawesome/free-regular-svg-icons'
import React from 'react'
const Component = () => {
    const MyLinkComponent = React.forwardRef(({ onClick, href }, ref) => {
    return (
      <FontAwesomeIcon icon={faHeart} />
    )
    })
    return (
        // ...
        <Link href='/followed' passHref>
            <MyLinkComponent/>
        </Link>
        // ...
    )
}

Also note that, I've used passHref prop in the Link component that forces Link to send the href property to its child. Default value is false.

CodePudding user response:

Link Component pass attributes that FontAwesomeIcon don't accept, You need to wrap the FontAwesomeIcon on native html element in this case like span

import Link from 'next/link' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faHeart } from '@fortawesome/free-regular-svg-icons'

c

onst Component = () => {
    return (
        // ...
        <Link href='/followed'>
            <span><FontAwesomeIcon icon={faHeart} /></span>
        </Link>
        // ...
    )
}
  • Related