user11913526
user11913526

Reputation:

How to import self-made component into index.js in React

I'm learning react and i'm stuck on how to import a self-made component.

So I made this into src/components/Part/Part.jsx

And in my index.js file I import this like that import { Part } from './components/Part/Part.jsx';

const Part = (props) =>{
    return (
    <p>{props.part + " " + props.exec}</p>
    )
  }

  export default Part

Upvotes: 0

Views: 741

Answers (2)

Sajeeb Ahamed
Sajeeb Ahamed

Reputation: 6418

If your folder structure like -

src
|_components
  |__Part
    |__Part.jsx
    |__index.js

And want to export the Part.jsx from index.js then you can write this line into the index.js file.

// At src/components/Part/index.js file
export {default} from './Part.jsx';

And now you can import the Part component from anywhere like-

import Part from 'path/to/components/Part';

Update: You can follow the structure this allows you to import the component like import Part from './components/Part' instead of import Part from './components/Part/Part.jsx'.

Upvotes: 1

TDK
TDK

Reputation: 91

In your import statement remove curly brackets. It will work then. :)

Update this:

import { Part } from './components/Part/Part.jsx';

To:

import Part from './components/Part/Part.jsx';

For better understanding read named exports and default exports here: https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export

Upvotes: 1

Related Questions