Inheriting styles in React Native components

Styling in React Native

const MyComponent = (props) => {
return <Text style={{backgroundColor: 'green'}}>{props.title}</Text>
}
<MyComponent title="Hello world"/>
<MyComponent title="Hello world" style={{backgroundColor: 'red'}}/>

Merging styles in a component

const MyComponent = ({style, title}) => {
return <Text style={{backgroundColor: 'green', ...style}}>{title}</Text>
}
const MyComponent = ({style, title}) => {
return <Text style={[{backgroundColor: 'green'}, style]}>{title}</Text>
}
const MyComponent = ({style, title}) => {
return <Text style={[{backgroundColor: 'green'}, styles.myText, style]}>{title}</Text>
}
const styles = StyleSheet.create({
myText: {
color: 'white'
}
})

But what happened to the rest of the props?

const MyComponent = ({style, title, ...rest}) => {
return <Text {...rest} style={[{backgroundColor: 'green'}, styles.myText, style]}>{title}</Text>
}
const styles = StyleSheet.create({
myText: {
color: 'white'
}
})

...
<MyComponent title="Hello world" style={{backgroundColor: 'red'}} onPress={() => console.log('Howdy')} />

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Adam Wattis

Adam Wattis

Javascript developer. Passionate learner.