Search code examples
reactjsstyled-componentsreact-icons

How to change fontSize in react icon using styled components


I want to make hover effect with increase of icon size, icons are from react icons, I'm using styled components. How should I do it ?

 export const BottomBar = () => {
  const style = { fontSize: "180%" };
  return (
    <StyledBottomBar>
      <StyledIcon>
        <FaFacebookSquare style={style} />
      </StyledIcon>
      <StyledIcon>
        <GrInstagram style={style} />
      </StyledIcon>
      <StyledIcon>
        <CgMail style={style} />
      </StyledIcon>
      <StyledIcon>
        <BiPhoneCall style={style} />
      </StyledIcon>
    </StyledBottomBar>
  );
};

Thanks !!!


Solution

  • It's not possible to do inline style's actions like :hover. You could use JS approach onMouseEnter and onMouseLeave:

    const style = { fontSize: "180%",transition: 'font-size 0.5s'  };
    ...
    <FaFacebookSquare style={style} onMouseEnter={({target})=>target.style.fontSize= "180%"} 
      onMouseLeave={({target})=>target.style.fontSize= "100%"}/>
    

    Or you could divide them into Component <StyledIcon/> and then useRef, useEffect and useState to do the hover.

    const style = { fontSize: "180%",transition: 'font-size 0.5s' };
    export function StyledIcon(props){
    const [hover,setHover] = useState(false)
    const iconRef = useRef(null)
    
      useEffect(()=>{
        if(hover){
          iconRef.current.style.fontSize="200%"
        }
        else{
          iconRef.current.style.fontSize="180%"
        }
      },[hover]) // changing fontSize whenever the hover state is updated
    const handleIconType = ()=>{
        switch(props.type){
          case 'facebook':
            {
              return <FaFacebookSquare style={style} ref={iconRef} onMouseEnter={()=>{setHover(true)}} onMouseLeave={()=>{setHover(false)}}/>
            }
          ...// cases for different type of icon
          default:
            return null
        }
      }
      return(
      <>
         <FaFacebookSquare style={style} ref={iconRef} onMouseEnter={()=>{setHover(true)}} onMouseLeave={()=>{setHover(false)}}/>
      </>
      )
    }
    export const BottomBar = () => {
      
      return (
        <StyledBottomBar>
          <StyledIcon type="facebook">
          </StyledIcon>
          <StyledIcon type="instagram">
          </StyledIcon>
        </StyledBottomBar>
      );
    };