The following modules are used to implement CSS modules support for React Native:
- react-native-sass-transformer - Transforms CSS code to a React Native compatible style object and handles live reloading
- babel-plugin-react-native-platform-specific-extensions - Transforms ES6
import
statements to platform specificrequire
statements if the platform specific files exist on disk. - babel-plugin-react-native-classname-to-style - Transforms
className
property tostyle
property.
Make sure that you have react-native-cli
installed and XCode/Android Studio installed and working.
- Go to "Building Projects with Native Code" tab and follow the guide: https://facebook.github.io/react-native/docs/getting-started.html
e.g.
react-native init AwesomeProject
cd AwesomeProject
Start packager:
npm start
Run project on iOS simulator:
react-native run-ios
npm install babel-plugin-react-native-classname-to-style babel-plugin-react-native-platform-specific-extensions react-native-sass-transformer node-sass --save-dev
{
"presets": ["react-native"],
"plugins": [
"react-native-classname-to-style",
[
"react-native-platform-specific-extensions",
{
"extensions": ["scss", "sass"]
}
]
]
}
Add this to your rn-cli.config.js
(make one if you don't have one already):
module.exports = {
getTransformModulePath() {
return require.resolve("react-native-sass-transformer");
},
getSourceExts() {
return ["scss", "sass"];
},
};
styles.scss
:
.container {
flex: 1;
justify-content: center;
align-items: center;
background-color: #f5fcff;
}
.blue {
color: blue;
font-size: 30px;
}
Add style import and BlueText
component to App.js
:
import React, { Component } from "react";
import { Text, View } from "react-native";
import styles from "./styles.scss";
const BlueText = () => {
return <Text className={styles.blue}>Blue Text</Text>;
};
export default class App extends Component<{}> {
render() {
return (
<View style={styles.container}>
<BlueText />
</View>
);
}
}
Restart React Native packager and clear it's cache (important) to see the styles that you added.
npm start -- --reset-cache
If it throws an error for missing node_modules/react-native/local-cli/cli.js
, just run npm install
and then try again.