skip to Main Content

I have to add some functionality to a small project and it’s a pretty weird project I have to mention. As soon as I bring useState to any component, the component breaks. Even a simple one:

import React, { useState } from 'react';

export function Example() { 
  const [count] = useState(0);
  return ( <div>{count}</div> );
}

gives an error:

Uncaught ReferenceError: exports is not defined

telling that some other component can’t import and use Example component.

I can normally use other hooks (I actually use useEffect in some of components), but whenever I use useState I immediatelly get the error mentioned above. Since the project is very small, only a few components, there were no useStates before I started woking on it. Maybe there’s somthing wrong with webpack config, I don’t know.

Please help me fix this strange bug!

2

Answers


  1. This is a fix for your code. Adding default to the export.

    import React, { useState } from 'react';
    
    export default function Example() { 
      const [count] = useState(0);
      return ( <div>{count}</div> );
    }
    
    

    or

    import React, { useState } from 'react';
    
    function Example() { 
      const [count] = useState(0);
      return ( <div>{count}</div> );
    }
    
    export default Example;
    
    

    If you intend to export the component as such:

    import React, { useState } from 'react';
    
    export function Example() { 
      const [count] = useState(0);
      return ( <div>{count}</div> );
    }
    

    you will have to import it this way:

    import { Example } from "ACTUAL_PATH"
    
    Login or Signup to reply.
  2. Please try these three steps:

    webpac.config.js file.

    module: {
      rules: [
        {
          test: /.js$/,
          exclude: /node_modules/,
          use: {
            loader: 'babel-loader',
          },
        },
      ],
    }
    

    Run that as Terminal.

    npm install --save-dev @babel/core @babel/preset-env @babel/preset-react babel-loader
    

    And as .babelrc file.

    {
      "presets": ["@babel/preset-env", "@babel/preset-react"]
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search