0

I need to pass props into Styles. So I created StyleSheet inside the class. But normal practice would be to create StyleSheet outside from the class.

I want to know are there any performance drawbacks by having StyleSheet.create inside the class ?

import React from 'react'
import { StyleSheet, View } from 'react-native'
import { connect } from 'react-redux'
import { Text } from 'native-base'
import p from '../../assets/colors/pallets'

const EmptyContainer = (props) => {
  const texts = props.texts

  const styles = StyleSheet.create({
    emptyContainer: {
      flex: 1,
      alignItems: 'center',
      justifyContent: 'center',
      padding: 20,
      backgroundColor: p.background2[props.theme],
    },
    text: {
      color: p.text1[props.theme],
    },
  })

  return (
    <View style={styles.emptyContainer}>
      {texts.map((text) => (
        <Text style={styles.text} key={Math.random()}>
          {text}
        </Text>
      ))}
    </View>
  )
}

const mapStateToProps = (state) => {
  const { theme } = state

  return {
    theme: theme.theme,
  }
}

export default connect(mapStateToProps)(EmptyContainer)

Edited: There are several ways to pass props into StyleSheet.

  1. Having StyleSheet inside class itself.
  2. Pass props as function parameter to styles i.e. styles(props.theme). emptyContainer

What would be the best way by considering the performance of the app ?

TylerH
  • 20,799
  • 66
  • 75
  • 101
John Stuart
  • 950
  • 5
  • 11
  • 28
  • similar to your query https://stackoverflow.com/a/51123464/9444013 – shammi Jun 06 '21 at 09:31
  • @shammi yes, but it does not answer my question exactly. I want to know are there any performance drawbacks using this method. `styles(this.props).icon` passing like this also possible, but in that case styles is working as function and are there any performance drawbacks ? – John Stuart Jun 06 '21 at 09:35
  • if you want to not lose performance then you can use inline style – shammi Jun 06 '21 at 09:39
  • @shammi If you use objects or arrays for styling (inline style), they will create new instances with each new render. You should use a StyleSheet in React Native, the advantage is in this way always passes a reference instead of a new object or array creation and allocation. – John Stuart Jun 06 '21 at 09:45

0 Answers0