Im having troubles importing an img using a local data.json file which has a path object (REACT)

Viewed 26

I cant import a photo in my react app, the error says 'Error: Cannot find module './../assets/planet-mercury.svg''

Im using a json file to get the path of the img

My app think that my path looks like this './../assets/planet-mercury.svg', but when I try to log it I see this path './assets/planet-mercury.svg' (which is the path in my json file). Which means my complete path should be something like this '../../assets/planet-mercury.svg'

Code:

const [currentPlanet,setCurrentPlanet]=useState(data[0])
    const {name} = useParams();
    useEffect(() => {
        const planet = data.find((item)=>item.name===name)
        setCurrentPlanet(planet);
    }, [name])
const photo = require('../.'+currentPlanet.images.planet).default
    return (
        <section id={planetStyle.planet}>
            <div className="container">
                <div>
                    <img alt={currentPlanet.name} src={photo} />
                </div>
            </div>
        </section>
    )
1 Answers

You are using "require" in order to import your image file.

This will not work in a React app, at least not out of the box.

I understand what you're trying to do, I think that a better solution for that will be to use a custom react hook to import your image. like this:

function useDynamicSVGImport(name, options = {}) {
  const ImportedIconRef = useRef();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState();

  const { onCompleted, onError } = options;
  useEffect(() => {
    setLoading(true);
    const importIcon = async () => {
      try {
        ImportedIconRef.current = (
          await import(`./${name}.svg`)
        ).ReactComponent;
        if (onCompleted) {
          onCompleted(name, ImportedIconRef.current);
        }
      } catch (err) {
        if (onError) {
          onError(err);
        }
        setError(err);
      } finally {
        setLoading(false);
      }
    };
    importIcon();
  }, [name, onCompleted, onError]);

  return { error, loading, SvgIcon: ImportedIconRef.current };
}
Related