In React Native, you import components using JavaScript's import
statement.
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;
For better code organization, you can create reusable custom components in separate files.
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;
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;
as
)You can rename imported components using as
.
import { Text as RNText, View as RNView } from 'react-native';
<RNView>
<RNText>Hello with alias!</RNText>
</RNView>
{}
)// MyComponent.js
export default function MyComponent() {
return <Text>Hello!</Text>;
}
// Import it without curly braces
import MyComponent from './MyComponent';
{}
)// MyComponents.js
export const Header = () => <Text>Header</Text>;
export const Footer = () => <Text>Footer</Text>;
// Import specific components
import { Header, Footer } from './MyComponents';
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" />
*
)You can import all exports from a module as a single object.
import * as MyComponents from './MyComponents';
<MyComponents.Header />
<MyComponents.Footer />
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'; |