How do you import components in React Native?

Importing Components in React Native

In React Native, you import components using JavaScript's import statement.


1. Importing Built-in Components

React Native provides core components like View, Text, Button, etc.

import { View, Text, Button } from 'react-native';

* Example Usage :

import React from 'react';
import { View, Text, Button } from 'react-native';

const App = () => {
  return (
    <View>
      <Text>Hello, React Native!</Text>
      <Button title="Click Me" onPress={() => alert('Button Pressed!')} />
    </View>
  );
};

export default App;

2. Importing Custom Components

For better code organization, you can create reusable custom components in separate files.

Step 1: Create a Component (MyComponent.js)
import React from 'react';
import { Text } from 'react-native';

const MyComponent = () => {
  return <Text style={{ fontSize: 20 }}>Hello from MyComponent!</Text>;
};

export default MyComponent;
Step 2: Import and Use the Component
import React from 'react';
import { View } from 'react-native';
import MyComponent from './MyComponent'; // Importing the custom component

const App = () => {
  return (
    <View>
      <MyComponent />
    </View>
  );
};

export default App;

3. Importing Components with Aliases (as)

You can rename imported components using as.

import { Text as RNText, View as RNView } from 'react-native';
* Usage :
<RNView>
  <RNText>Hello with alias!</RNText>
</RNView>

4. Importing Default vs Named Exports
* Default Export (Import without {})
  • Used when a module exports a single component.
// MyComponent.js
export default function MyComponent() {
  return <Text>Hello!</Text>;
}

// Import it without curly braces
import MyComponent from './MyComponent';
* Named Export (Import with {})
  • Used when a module exports multiple components.
// MyComponents.js
export const Header = () => <Text>Header</Text>;
export const Footer = () => <Text>Footer</Text>;

// Import specific components
import { Header, Footer } from './MyComponents';

5. Importing Components from Third-Party Libraries

If you install a library like react-native-vector-icons:

npm install react-native-vector-icons

You import components like this:

import Icon from 'react-native-vector-icons/FontAwesome';

<Icon name="home" size={30} color="blue" />

6. Importing Everything (*)

You can import all exports from a module as a single object.

import * as MyComponents from './MyComponents';

<MyComponents.Header />
<MyComponents.Footer />

Summary of Import Methods
Import Type Syntax
Core Component import { View, Text } from 'react-native';
Custom Component import MyComponent from './MyComponent';
Named Exports import { Header, Footer } from './MyComponents';
Import with Alias import { Text as RNText } from 'react-native';
Import All (*) import * as MyComponents from './MyComponents';