react-native-themed-styles icon indicating copy to clipboard operation
react-native-themed-styles copied to clipboard

Use on Class Components with dynamic theme

Open jpcodr opened this issue 4 years ago • 1 comments

Not issue but a question.

How do you use themed stylesheets on class components with dynamic theme? Can you show an example, if possible?

jpcodr avatar Jun 15 '20 21:06 jpcodr

@jpcodr you can create function like below

export function withTheme<T, N extends string, S extends NamedStyles<S> | NamedStyles<any>>(
  data: StyleSheetData<N, T, S>,
  name?: N,
): Function {
  const resolvedName = name || data.appearanceProvider()
  const theme = data.themes[resolvedName]
  if (!theme) {
    throw new Error(`Theme not defined: ${resolvedName}`)
  }
  const styles = data.styles[resolvedName]

  return (WrappedComponent: React.ComponentClass) => {
    return (props: any) => <WrappedComponent styles={styles} {...props}/>
  }
}

and on your component do like below

export default withTheme(themedStyles)(AppIntroSlider)

after that you can access the styles from your props

<Text style={this.props.styles.yourawesomestyle}>Awesome</Text>

fachrihawari avatar Sep 09 '20 14:09 fachrihawari