Home > Back-end >  Cannot import components in pages react js
Cannot import components in pages react js

Time:07-24

I can't import the components to the page because this error happens

ERROR in ./src/pages/Home.jsx 4:0-37
Module not found: Error: Can't resolve './components/Card' in '/home/c4p1/blog/src/pages'

my project structure [structure folders][1] [1]: https://i.stack.imgur.com/dJqqK.png

my routes.js

import { BrowserRouter, Route, Routes } from "react-router-dom";
import Home from './pages/Home'

function Rotas(){
   return(
               
       <BrowserRouter>
           <Route path="/" component={Home} />
       </BrowserRouter>
   );
}

export default Rotas;

my app.js

import Routes from "./routes";

function App() {
  return (
    <Routes/>
  );
}

export default App;

my Home.js

import Card from './components/Card';
import Header from './components/Header';

const sections = [
    { title: 'Blog', url: '#' },
    { title: 'About', url: '#' },
    { title: 'Portifolio', url: '#' },
  ];


export default function Home() {
    return (
        <>
            <Header title="C4p1" sections={sections}></Header>
            <Card/>
            <Card/>
        </>
    );
  }

CodePudding user response:

./components/Card is src/pages/components/card since it is relative to the document's current directory

You should change it to ../components/Card which is src/components/card

../ will navigate to parent directory which is src in your case

CodePudding user response:

You're looking into the same directory by doing "./".

"./" this means to look up at the same directory(pwd) and to look up at one level up you have to do "../".

For example: enter image description here

Let's say I want to import file5.js into file4.js. I would do something like this

import file5 from "./file5.js"

and let's say I need to import file3.js into file1.js. I'll do this

import file3 from "../folder2/folder5/file3.js"

In your case, you need to go back one level up to access the components folder from pages

import Card from "../components/Card.jsx
  • Related