How to return text + icon from a function in React

Viewed 4551

I have written a function in Reactjs and I want to return text with an icon if a certain condition meets. Here is how I wrote it

if (actionNeeded) {
  return abbreviation + <i className={'fa fa-exclamation-circle fa-fw'} />;
 }

This returns text [object Object] instead of text (icon). How do I get it to work?

3 Answers

You need to return a JSX element to have your <i> rendered.

In you current case, it will see that abbreviation is a string and will concatenate your <i>as such, giving you the result of an Object.toString().

You can use React.Fragment to do so:

return (
    <React.Fragment>
        {abbreviation} <i className="fa fa-exclamation-circle fa-fw" />
    </React.Fragment>
);

You can use Font Awesome's npm packages for React. The benefit of doing it this way is that only the icons that you actually use will be added to the build.

Installation

npm i --save \
@fortawesome/fontawesome-svg-core \
@fortawesome/free-solid-svg-icons \
@fortawesome/react-fontawesome

main.js

import {faExclamationCircle, faFw} from '@fortawesome/free-solid-svg-icons';
import {library} from '@fortawesome/fontawesome-svg-core';

library.add(faExclamationCircle, faFw);
render(<App />, document.getElementById('root'));

component.js

import {FontAwesomeIcon} from '@fortawesome/react-fontawesome';
...
if (actionNeeded) {
    return (
        <>
            {abbreviation} <FontAwesomeIcon icon="exclamation-circle" />
        </>
    );
}

I know I am late to answer this.

But something that worked for me:

Installation

$ npm i --save @fortawesome/fontawesome-svg-core
$ npm i --save @fortawesome/free-solid-svg-icons
$ npm i --save @fortawesome/react-fontawesome

Import in INdex.js

import '@fortawesome/fontawesome-free/css/all.min.css';

component.js

 return (
            <div className="errorDiv">
                {showError &&
                <React.Fragment>
                    <FontAwesomeIcon icon={faTimes} />
                    <span> </span>
                    {error}
                </React.Fragment>

                }
            </div>
        );
Related