Home > Software engineering >  how to use font awesome in react with map()
how to use font awesome in react with map()

Time:03-02

I am very new in RectJs and so this may be a very beginner question, However, I have got an array of objects called MyArr like this:

const MyArr =[
   {picture:'faUser' ,  text:'something'},
   {picture:'faUser' ,  text:'something'} ]
export default MyArr

I want to use the value of "picture" in another component to declare which icon from #FontAwesome should be shown. so I made another component in which I pass that Array of Objects as a props value to the destination, like this

import React, { Component } from 'react'
import MyArr from './MyArr'
import ShowFontAwesome from './ShowFontAwesome'

 class Body extends Component {

  render() {
   return(
        <div>
          <ShowFontAwesome myValue={MyArr} />          
        </div>
)
}}
export default Body

so the component called "ShowFontAwesome" is where I am going to show the result; this is the component's code

import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import * as FontAwesome from '@fortawesome/free-solid-svg-icons';
import React, { Component } from 'react'

 class ShowFontAwesome extends Component {
   constructor(props){
     super(props);}
render() {
    return (
<div>
{this.props.myValue.map(
          (myValues, index)=>{
            return(
<div>
<FontAwesomeIcon icon={`FontAwesome.${myValues.picture}`} />
</div>
)})
</div>
)}}
export default ShowFontAwesome

finally, it logs this error in the console ** could not find icon {prefix: 'fas', iconName: 'FontAwesome.faUser'} **

CodePudding user response:

Update:

first add this to your component:

import {fas} from '@fortawesome/free-solid-svg-icons'
import { library } from "@fortawesome/fontawesome-svg-core";

library.add(fas);

and change the picture value from "faUser" to just "user", so you array will be like this:

const MyArr =[
   {picture:'user' ,  text:'something'},
   {picture:'user' ,  text:'something'} ]
export default MyArr

and then use it like this:

<FontAwesomeIcon icon={myValues.picture} />
  • Related