2

I have a react component that contains an SVG image. and i import it like this

import MessageIcon from '../static/styles/svg/messageIcon';

However as part of code splitting, i want to dynamically import it instead of static import.

I tried like this but does not work

import('../static/styles/svg/messageIcon').then(MessageIcon => { return <MessageIcon /> });

can anyone tell me how i can dynamically import and call this component? thanks in advance

1 Answer 1

1

You can import dynamical like this :

import React, { useEffect, useState } from "react";

const App = () => {
    const [state, setState] = useState<any>();

    useEffect(() => {
        (async () => {
            const i = await import("../../assets/img/user.svg");
            setState(i);
        })();
    }, []);
    
    return <img alt={"test dynamic"} src={state?.default} />;
};
export default App;

Also, you can write it with ref too:

    import React, { useEffect, useRef } from "react";

    const App = () => {
        const ref = useRef<any>();

        useEffect(() => {
            (async () => {
                const i = await import("../../assets/img/user.svg");
                ref.current.src = i.default;
            })();
        }, []);
        
        return <img alt={"test dynamic"} ref={ref} />;
    };
    export default App;

import dynamical React component

import React from "react";

const App = () => {
      const nameIcon = "iconMessage";
      const IconMessage = React.lazy(() => import(/* webpackChunkName: "icon" */ `./${nameIcon}`));

      return <IconMessage />;
};
export default App;

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks ijavad for the reply. I understood your solution. But in my case, the SVG itself a react component. import MessageIcon from '../static/styles/svg/messageIcon'; the above 'MessageIcon' is a react component which I need to dynamically import and call
oh sorry dude it is my mistake I didn't see it a component react, so you can use React lazy, I will update this Awnser

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.