Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React native: How to combine external and inline styles?

This is a part of a _renderRow-function. I have some basic styles for a button, and also a style that is read from a variable on the row. In this example it's '#f00' but it could be a variable, like thisColor. How can I combine an external style with an inline style?

Something like this, but this doesn't work:

<TouchableHighlight style={[styles.button]{ backgroundColor: '#f00'}}   

Or do I have to nest it with a container inside the TouchableHightlight and put the inline style on that element instead?

like image 642
Niclas Avatar asked Oct 18 '16 20:10

Niclas


People also ask

How do you combine two styles in React Native?

import { StyleSheet } from 'react-native'; const styleJoiner = (... arg) => StyleSheet. flatten(arg); By using my styleJoiner anywhere you can combine any type of style and combine styles.

Can you use inline and external CSS at the same time?

Obviously inline styles work at the same time with external style classes.

How do you add multiple inline styles in React Native?

Use the spread syntax to combine multiple inline style objects in React, e.g. style={{...style1, ... style2}} . The spread syntax will unpack the key-value pairs of the objects into a final object and the styles will get applied to the element.

What are the disadvantages of inline styles?

Disadvantages of Inline CSS:Adding CSS rules to every HTML element is time-consuming and makes your HTML structure messy. Styling multiple elements can affect your page's size and download time.


3 Answers

Your brackets are wrong. If you intend to continue to use the array syntax, Use this instead:

<TouchableHighlight style={[styles.button,{ backgroundColor: '#f00'}]} 
like image 165
Alex Harrison Avatar answered Oct 07 '22 06:10

Alex Harrison


Can use the spread syntax:

<TouchableHighlight style={{ ...styles.button, backgroundColor: '#f00'}}
like image 37
Jeff McCloud Avatar answered Oct 07 '22 05:10

Jeff McCloud


This is the correct answer, tested in React Native 0.44.2:

<TouchableHighlight style={{...styles.button, ...{backgroundColor: '#f00'}}}>
like image 3
andoni vianez Avatar answered Oct 07 '22 07:10

andoni vianez