Home > Software engineering >  React.js cant find image with variable in it's path
React.js cant find image with variable in it's path

Time:07-09

I didn't use React before, so my question could be silly, but anyway, i have simple project with TailwindCSS, i want to check if image exists and set a class pointing to that image, but Reacts gives me an error.

App.js:

import './App.css';
import Header from './Header';
import Tools from './Tools';

function App() {
  return (
    <div>
      <header>
        <Header/>
      </header>
      <main className='flex w-[80vw] mx-auto'>
        <div id='tools'>
          <Tools/>
        </div>
      </main>
    </div>
  );
}

export default App;

Tools.js:

const Tools = () => {
    return (
        <main className="my-4">
            <h1 className="text-4xl">Инструменты</h1>
            <div>
                <ul>
                    {Box("Big test", "TESTS ARE COOL", "construction.png", "#!")}
                </ul>
            </div>
        </main>
    )
}

const Box = ({name, desc, img, href}) => {
    let imgExists;
    try{
        require(`./img/tools/${img}`);
        imgExists = true;
    }
    catch(err){
        imgExists = false;
    }
    return (
        <li>
            <a href={href}>
                <div>
                    <h2>{name}</h2>
                    <p>{desc}</p>
                </div>
                <div className={imgExists === true ? `bg-[url('./img/tools/${img}')]` : "not-found"}></div>
            </a>
        </li>
    )
}

export default Tools

(There are no errors in Header.js)

Error:

Failed to compile.

Module not found: Error: Can't resolve './img/tools/${img}' in '/home/anime/PRACTICE/ddracenet/src'
ERROR in ./src/index.css (./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[5].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[5].use[2]!./node_modules/source-map-loader/dist/cjs.js!./src/index.css) 5:36-82
Module not found: Error: Can't resolve './img/tools/${img}' in '/home/anime/PRACTICE/ddracenet/src'

webpack compiled with 1 error

CodePudding user response:

Check the path of the image, because if React says it can't resolve that means it can't find, in most cases.

Module not found: Error: Can't resolve './img/tools/${img}' in '/home/anime/PRACTICE/ddracenet/src'

CodePudding user response:

Error occurs when webpack is bundling your javascript code. Webpack searches all the dependencies and because the required image doesn't exists, it throws error. To solve the problem, you should send request to the image src and check the result.

Here's my code.

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

const Tools = () => {
    return (
        <main className="my-4">
            <h1 className="text-4xl">Инструменты</h1>
            <div>
                <ul>
                    <Box name="Big test" desc="TESTS ARE COOL" img="construction.png" href="#!" />
                </ul>
            </div>
        </main>
    )
}

const Box = ({name, desc, img, href}) => {
    const [imgExists, setImgExists] = useState(true);

    useEffect(() => {
        Axios.get(`./img/tools/${img}`).then(() => {
            setImgExists(true);
        }).catch(() => {
            setImgExists(false);
        })
    }, []);

    return (
        <li>
            <a href={href}>
                <div>
                    <h2>{name}</h2>
                    <p>{desc}</p>
                </div>
                <div className={imgExists === true ? `bg-[url('./img/tools/${img}')]` : "not-found"}></div>
            </a>
        </li>
    )
}

I haven't run this code but I'm sure it works perfectly.

  • Related