Adding css to font-awesome icons with react-styled components

Viewed 4362

I have been using styled components but there is a case where i had to add a font awesome icon and then add some css like font-size and color etc .I tried with the following approach but the css doesn't get applied to it.

IconComponent.js

import styled from "styled-components";
const NavIcon = () => {
  return <i className="fas fa-bars"></i>;
};
const NavIconDisplay = styled(NavIcon)`
  color: white;
  display: none;
  font-size: 20px;
`;

export {NavIconDisplay}

App.js import {NavIconDisplay} from './IconComponent'

<NavIconDisplay/>

but then i see the styling color:white and all doesnt get added to it, even when i inspect it there seems no class added to it as the styled components usally add (some random class names) to the elements

3 Answers

Without a Minimal, Reproducible Example you most likely won't get a helpful answer with styled components. So here are two alternatives to make it work:

FontAwesome has official React support that will do what you need: https://fontawesome.com/how-to-use/on-the-web/using-with/react

An alternative way is to use classic CSS, create a CSS class with your styles and apply it to your component: In style.css:

.nav-icon-display {
  color: white;
  display: none;
  font-size: 20px;
}

your component:

// Make sure to import your CSS
import from '../.../style.css';

// ...

<i className="fas fa-bars nav-icon-display"></i>

Here is an example of how you can do that

import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faBars } from '@fortawesome/free-solid-svg-icons'
import styled from 'styled-components';

const StyledFontAwesomeIcon = styled(FontAwesomeIcon)`
    color: white;
    font-size: 1.5rem;
    cursor: pointer;
`;

const Header = () => {
    return (
        <StyledFontAwesomeIcon icon={faBars}/>         
    );
};

export default Header;

Here are the docs for more information: https://fontawesome.com/v5/docs/web/use-with/react

Hope that helps!

import styled, { css, createGlobalStyle } from 'styled-components'; export const GlobalStyle = createGlobalStyle.fa-shopping-cart { color: white; display: none; font-size: 20px; };

Related