skip to Main Content

I have generated "@font-face { font-family: ‘RFDewiExpanded-Thin’;font-weight: 100;
font-style: normal; src: ……..}".
How can i apply it in React without external files?

Haven’t any idea how to solve this problem.
Dynamic CCS import needs external file as i know.

2

Answers


  1. I don’t know that you can do this natively, however, if using a CSS-in-JS library is possible you may be able to do that and keep things all to one file. Examples are JSS, Emotion, Styled JSX etc

    Is there a reason you are unable to import a separate .css file? You can do dynamic things in CSS with variables and CSS imports. One method I have used / would recommend is postcss-import

    Login or Signup to reply.
  2. You can directly define the @font-face rule in your React component.

    In the useEffect hook, a new FontFace object is created. It is then added to the document.fonts collection.
    To clean up the font resources when the component unmounts, you can return a cleanup function from the useEffect hook.

    Example:

    
        import { useEffect, useRef } from 'react';
    
        const MyComponent = () => {
    
            const elementRef = useRef(null);
    
            useEffect(() => {
                const fontFace = new FontFace(
                    'RFDewiExpanded-Thin',
                    'url(pathToYourFontFile.woff2)'
                );
    
                document.fonts.add(fontFace);
    
                fontFace.load()
                    .then(() => {
                        if (elementRef.current) {
                            elementRef.current.style.fontFamily = 'RFDewiExpanded-Thin';
                            elementRef.current.style.fontWeight = 100;
                            elementRef.current.style.fontStyle = 'normal';
                        }
                    });
    
                return () => {
                    fontFace.loaded.then(() => {
                        document.fonts.remove(fontFace);
                    });
                };
            }, []);
    
            return (
                <div ref={elementRef}>
                    My Component Here
                </div>
            );
        };
    
        export default MyComponent;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search