Search code examples
javascriptreactjspackageimport-libraries

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


Solution

  • 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