CodeBlanks Logo Icon CodeBlanks

File extension

Learn platform-specific files with .ios.js and .android.js.

File extension

React Native automatically picks platform-specific files by looking at file extensions. If you have two files Button.ios.js and Button.android.js, when you write import Button from './Button' React Native knows which platform it is on and loads the right file.

You do not write the extension in the import path; the base name ./Button is enough. This method is useful when you need to write completely different components for the two platforms. Each file must export the same interface.

Practice Your turn: import a platform file

Import MyButton from the path './MyButton' (without extension). Use it inside a <View> as <MyButton title="Click" />.

Starter code

App.js
// import MyButton without extension

function Screen() {
  return (
    <View>
      {/* use MyButton */}
    </View>
  );
}

Sample solution

App.js
import MyButton from './MyButton';
import { View } from 'react-native';

function Screen() {
  return (
    <View>
      <MyButton title="Click" />
    </View>
  );
}

Common interface

When using the file extension method both files must export the same interface. That is, Button.ios.js and Button.android.js both export a component with the same name. This way the importing side does not need to know which file is loaded.

The two files can have different implementations: the iOS version might use TouchableOpacity and the Android version TouchableNativeFeedback. What matters is that both accept the same props and show the same behavior. This hides the platform difference from the user.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When is the Button.ios.js file loaded?

App.js
import Button from './Button';
  • Only on iOS Correct answer
  • Only on Android
  • On the web
  • Always

Explanation: The .ios.js extension is loaded only on iOS.

2 Fill in the blank: import without extension

Question
import { Button } from ____;
Answer
import { Button } from './Button';

Explanation: You import without an extension; RN picks automatically.

3 Match: extension and platform

Term Meaning
.ios.js iOS file
.android.js Android file
.js common file

All lessons in Beginner