How to Import Component in React: Simple Guide
In React, you import a component using the
import statement followed by the component name and the file path. For example, import MyComponent from './MyComponent' imports the default export from the file MyComponent.js.Syntax
The basic syntax to import a React component is:
import ComponentName from './path/to/Component'for default exports.import { ComponentName } from './path/to/Component'for named exports.
The import keyword brings the component into your file so you can use it in your JSX.
javascript
import ComponentName from './ComponentName'; // or for named exports import { ComponentName } from './ComponentName';
Example
This example shows how to import and use a default exported component called Greeting from another file.
javascript
// Greeting.js import React from 'react'; export default function Greeting() { return <h1>Hello, friend!</h1>; } // App.js import React from 'react'; import Greeting from './Greeting'; export default function App() { return ( <div> <Greeting /> </div> ); }
Output
<h1>Hello, friend!</h1>
Common Pitfalls
Common mistakes when importing React components include:
- Using incorrect file paths, causing module not found errors.
- Confusing default and named exports, leading to undefined components.
- Forgetting to export the component in the source file.
Always check the export style and file location.
javascript
// Wrong: importing default as named import { Greeting } from './Greeting'; // Error if Greeting is default export // Correct: import Greeting from './Greeting';
Quick Reference
| Import Type | Syntax | Use When |
|---|---|---|
| Default Import | import Component from './Component'; | When the component is exported as default |
| Named Import | import { Component } from './Component'; | When the component is exported by name |
| Import All | import * as Components from './Component'; | To import all named exports as an object |
Key Takeaways
Use
import Component from './Component' for default exported components.Use
import { Component } for named exports.Check file paths carefully to avoid import errors.
Always export your component from its file before importing.
Match import style with export style to prevent undefined components.