React Native Dynamic Styling

Daniel Chang
Always Be Coding
Published in
3 min readAug 20, 2017

--

Recently I started on a React Native project. I found myself doing a lot of inline styling as I start out the project. After a certain point, I wanted to refactor the styling, but it became painfully obvious inline styling was not really the way to go.

Dynamic Styling

Stylesheets

Unlike developing for a website, there is no one CSS or stylesheet to reference. Luckily React Native comes with a StyleSheet abstraction so you can build your own.

The nice thing about React Native is that it is pretty much Javascript so you can import/require other files. The React Native StyleSheet documentation doesn’t provide an example, but by using basic Javascript concepts you can construct a universal ‘stylesheet’ that your application can draw from.

Creating Style.js

For my project I named it Style.js. The goal here is just to create a StyleSheet abstraction just like the React Native documentation lays out. Below is the code for this file.

// Style.js

// Bring in StyleSheet abstraction from React Native
import {
StyleSheet,
} from 'react-native';

// Declare a var/const that is the StyleSheet abstraction
const styles = StyleSheet.create({
// All the style content goes here, I've only included one 'class'
noticeModal: {
marginBottom: 200,
marginLeft: 200,
marginRight: 200,
backgroundColor: 'dimgray',
borderLeftWidth: 2,
borderRightWidth: 2,
borderBottomWidth: 2,
borderBottomRightRadius: 4,
borderBottomLeftRadius: 4,
borderStyle: 'solid',
borderColor: 'goldenrod',
justifyContent: 'center',
alignItems: 'center',
},
rightNavContainer: {
flex: 1
},
});
// !!!Important!!! This makes styles available as an export
module.exports = styles;

As the comments layout, the last part is pretty important. It allows us to have access to styles when we import our ‘stylesheet’.

Import styles

Now all you need to do is import Styles.js and you not have access to styles.

// appfile

// bring in Style.js
import styles from './Styles.js'

export default class DataEntry extends Component {

render() {
return (
// few examples of attaching styles
<View style={ styles.noticeModal }>
<View style={styles.rightNavContainer}>
<RightNav
currentRound={this.state.currentRound}
recordPlayerAction={this.recordPlayerAction.bind(this)}
saveGame={this.saveGame.bind(this)}
displayMenu={this.displayMenu.bind(this)} />
</View>
</View>
);
}
}

And there you have it, an abstracted out stylesheet where you can keep all the styling decisions for you application.

Not Quite The Same

Is isn’t quite the same as a have a style.css, but it gets you a huge part of the way. The cascading and class/id/element nature of CSS isn’t present here so if you were a pro at leveraging those things, you’ll probably feel like it’s missing something. However the fact we are now in a Javascript files enables us to do some interesting things. In short, anything you could normally do with Javascript you can do in this file.

Unfortunately we don’t have access to a lot of arguments in our current implementation, it is theoretically possible to implement styles as a function and pass in arguments from within the component file. This does take a little more forethought and planning.

Dynamic Styling

Even with our current implementation, it’s possible to provide dynamic styling style. In my example, I was looking to dynamically change the background color for certain views based on some configuration.

// snippet for the actually element being styled
<TouchableHighlight
key={optionIndex}
// the styles prop takes in an array of objects
// I'm actually mapping over option, so option.color is a property
style={[styles.resultButtonContainer, {backgroundColor: option.color}]}
onPress={ () => {
this.props.recordPlayerAction(null, {
'time': new Date(),
'playerNo': this.props.playerNo,
'action': this.props.action.actionName,
'result': option.name
})
this.setModalVisible(!this.state.modalVisible)
} }>
<Text style={{ textAlign: 'center' }}>{option.name}</Text>
</TouchableHighlight>

The crux of this implementation is that it is possible to pass an array into the style prop.

For reference, below is my collection that I’m mapping over.

resultOptions: {
generic: [
{name: 'Good', color: 'darkgreen'},
{name: 'Neutral', color: 'darkgray'},
{name: 'Bad', color: 'darkred'},
],
}

And there you have it!

Just One Implementation

As mentioned earlier, there are potentially a number of different ways to implement dynamic styling for a React Native project. I went with the current implementation because I valued configuration objects over being automatically dynamic.

I’d actually be interested in seeing some other implementations. If after (or even before) reading this you find yourself doing a different implementation, drop a note in the comments.

Had fun reading this? Found it useful? Recommend or share on Facebook/Twitter! Check out more posts on Always Be Coding.

--

--

Code monkey always looking to learn more, avid car enthusiast celebrating #WRXmas all year long, amateur chef, professional eater.