Home > Blockchain >  How can I use conditional styling properly in react native stylesheet
How can I use conditional styling properly in react native stylesheet

Time:12-03

I have button themes called green,blue and red .my solution works but it looks messy. how can I use them like in objects instead if arguments


 const buttonBG = theme === 'green' ? COLORS.green : theme === "blue" ? COLORS.blue : ""

 const fontTheme = theme === 'green' ? FONTS.green : theme === "blue" ? FONTS.blue : ""

    const styles = StyleSheet.create({
        button: {
            backgroundColor: buttonBG,
            borderRadius: 12,
            paddingVertical: 16,
            paddingHorizontal: 20,
            lineHeight: 24,
            font: fontTheme 
        },

CodePudding user response:

I imagine you pick the color of the theme inside the <ThemedBtn/>, perhaps doing it outside the component will make the code inside <ThemedBtn/> look cleaner?

App Component

import React, {useState} from 'react';
import {View} from 'react-native';

import ThemedBtn from './components/ThemedBtn';

const _COLORS = {
  blue: 'blue',
  red: 'red',
  green: 'green',
};

const _FONT_COLORS = {
  blue: 'blue',
  red: 'red',
  green: 'green',
};

const App = () => {
  // edit start -> My best guess how you would like to alter the theme
  const [bgColor, setBgColor] = useState(_COLORS.blue);
  const [fontTheme, setFontTheme] = useState(_FONT_COLORS.red);
  // edit end ->

  return (
    <View>
      <ThemedBtn bgColor={bgColor} fontTheme={fontTheme} />
    </View>
  );
};

export default App;

ThemeBtn Component

export default function ThemedBtn({btnBg, fontTheme}) {
  const {btnStyles} = useMemo(
    () =>
      StyleSheet.create({
        btnStyles: {
          backgroundColor: btnBg,
          borderRadius: 12,
          paddingVertical: 16,
          paddingHorizontal: 20,
          lineHeight: 24,
          font: fontTheme,
        },
      }),
    [btnBg, fontTheme],
  );

  return (
    <TouchableOpacity style={btnStyles} title="Press Me">
      <Text style={{color: btnStyles.font}}>Press Me</Text>
    </TouchableOpacity>
  );
}

CodePudding user response:

One cleaner way to pass values in styles is as follow


import { StyleSheet, Text, View } from 'react-native'
import React from 'react'

const App = () => {
  return (
    <Button 
        style={styles.btn('red')}
    />
  )
}

export default App

const styles = StyleSheet.create({
    btn : (color) => ({
        color : color
    })
})
  • Related