Home > Software engineering >  how to combine ternary and style objects in a single style property?
how to combine ternary and style objects in a single style property?

Time:12-14

i am trying to manipulate a few buttons's (TouchableOpacity) style each time a user is clicking one lets say if a user clicks button "1" out of 2 more, then this button will be colored green, and the others will be colored white. and if the user presses button "3" then button 3 will be colored green, and the others white. so im using a ternary inside the style property of the TouchableOpacity, and it works just fine the problem is i dont know how to add a non-changing style (like width, height, border etc...) all i need are the rules for that and an example. this is my code for button 1 (selectedCourseTypeButton is a useState hook):

  <TouchableOpacity
        style={selectedCourseTypeButton==="Starters" ? {backgroundColor:"green"}:{backgroundColor:"white"}}
        onPress={() => {
          mealTypeButtonHandler('Starters');
          setSelectedCourseTypeButton("Starters")
        }}
      >
        <Text style={selectedCourseTypeButton==="Starters" ? {color:"white"}:{color:"green"}}>Starters</Text>
      </TouchableOpacity>

i tried to add columns and semi columns while playing with arrays and objects inside the style propety and i had errors in the code while doing those.

CodePudding user response:

{
  backgroundColor: selectedCourseTypeButton === 'Starters' ? 'green' : 'white',
  width: '100px',
  // ...
}

CodePudding user response:

You can use the memo hook to (re-)compute the dependent styles only as needed. In addition to the performance optimization, this has the advantage of also helping keep your JSX markup more readable. Here's an example:

import { useMemo } from 'react';

function Component ({selectedCourseTypeButton}) {
  const computedStyles = useMemo(() => {
    const isStartersCourse = selectedCourseTypeButton === "Starters";

    return {
      touchable: {
        backgroundColor: isStartersCourse ? "green" : "white",
        // other entries, for example:
        // width: "100%",
      },
      text: {
        color: isStartersCourse ? "white" : "green",
        // etc.
      },
    };
  }, [selectedCourseTypeButton]);

  return (
    <TouchableOpacity
      style={computedStyles.touchable}
      onPress={() => {
        mealTypeButtonHandler("Starters");
        setSelectedCourseTypeButton("Starters");
      }}
    >
      <Text style={computedStyles.text}>Starters</Text>
    </TouchableOpacity>
  );
}

  • Related