Also read:
- Media query
- Orientation
- I18n
- react-native-safe-area-view
- react-native-dark-mode;
- Typescript;
- Testing with Jest.
Use a makeUseStyles
function to create a hook function that can be used in react components
import { makeUseStyles } from "react-native-stylex";
export const useStyles = makeUseStyles((theme) => ({
root: {
color: theme.palette.xColor,
},
}));
You can use styles in function or class components:
import React, { Component } from "react";
import { useStyles } from "./styles";
// Functional component (hooks variant)
const Root = () => {
const styles = useStyles();
return <View style={styles.root} />;
};
export default Root;
// ----------------------------
// Class component (HOC variant)
class Root extends Component {
render() {
const { styles } = this.props;
return <View style={styles.row} />;
}
}
export default withStyles(useStyles)(Root);
You need wrap you're root component with ThemeProvider and pass theme
import { ThemeProvider } from "react-native-stylex";
const theme = {
palette: {
textColor: "black",
},
utils: {
fade(color, value) {
/*...*/
},
},
};
const App = () => (
<ThemeProvider value={theme}>
<Root />
</ThemeProvider>
);
export default App;
Then use a makeUseStyles
function and extract passed theme ⚡️
import { makeUseStyles } from "react-native-stylex";
import { minWidth } from "react-native-stylex/media-query";
// Theme-dependent styles
const useStyles = makeUseStyles(({ palette, utils }) => ({
root: {
color: palette.textColor,
...minWidth(320, {
color: utils.fade(palette.textColor, 0.7),
}),
},
}));
const Root = () => {
const styles = useStyles();
return <View style={styles.root} />;
};