skip to Main Content

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 
        },

2

Answers


  1. 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 = () => {
      const [bgColor, setBgColor] = useState(_COLORS.blue);
      const [fontTheme, setFontTheme] = useState(_FONT_COLORS.red);
    
      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>
      );
    }
    
    Login or Signup to reply.
  2. One cleaner way is to pass values in styles as follows:

    
    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
        })
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search