Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React import multiple components from a folder

I am trying to import 2 components from the components folder. Both components' class are export default .

However, I got an error message that I should use the curly braces in my import statement. However, both components above are not using named export so curly braces is not needed when importing them.

Why isn't it working? How can I make this work?

Line 4 error Main app

Login component

like image 612
Chong Onn Keat Avatar asked Feb 02 '26 23:02

Chong Onn Keat


1 Answers

as @casimirth stated above since those components are from different files, even though on the same folder, then you need to import them separately as below

import Login from "./components/Login"
import Question from "./components/Question"

But i think i know what you're looking for, being able to import them all on one line right?

below are couple of the ways

1 .put them all on single file and use exports, since in one file only one component can use export default

// ./components/componentfile.js
export const Login = () => {...
export const Question = () => {...

then where you're using them you can import them as

import {Login, Question} from '.components/componentfile'

if one of the file is exported with default as below

const Login = () => {...
export const Question = () => {...
export default Login;

then the using them will be as below

import Login , { Question } from './components/componentfile'

2. You wish to keep this two files separately and still import on one line

then you need to add another file in components file, prefered index.js since if you name a directory without specifying a file, index.js is one being called by default

So, you components directory will have three files,

./components
   -index.js
   -login.js
   -questions.js

then without editing anything on your login.js,questions.js import them on your index.js and export them from it as below

import Login from './login'
import Question from './question'

export {Login, Question}

then where you're using them you just import them as below

import {Login, Question} from './components' //note with index.js no need to mention //it on import
like image 122
ndotie Avatar answered Feb 05 '26 13:02

ndotie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!