Skip to content

Files

Latest commit

 

History

History
122 lines (91 loc) · 3.14 KB

setup-sass.md

File metadata and controls

122 lines (91 loc) · 3.14 KB

Setup CSS modules for React Native (with Sass support)

The following modules are used to implement CSS modules support for React Native:

Step 1: Install depencies to run React Native

Make sure that you have react-native-cli installed and XCode/Android Studio installed and working.

Step 2: Create a new React Native app and test that it works

e.g.

react-native init AwesomeProject
cd AwesomeProject

Start packager:

npm start

Run project on iOS simulator:

react-native run-ios

Step 3: Install dependencies for React Native CSS modules

npm install babel-plugin-react-native-classname-to-style babel-plugin-react-native-platform-specific-extensions react-native-sass-transformer node-sass --save-dev

Step 4: Setup your project's .babelrc

{
  "presets": ["react-native"],
  "plugins": [
    "react-native-classname-to-style",
    [
      "react-native-platform-specific-extensions",
      {
        "extensions": ["scss", "sass"]
      }
    ]
  ]
}

Step 5: Setup rn-cli.config.js in your project

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"];
  },
};

Step 6: Add some Sass to your project and use it inside a React component

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>
    );
  }
}

Step 7: Restart packager and clear cache

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.