Styling with react-jss based on intricate conditionals

After experimenting with react-jss for a few weeks, I am faced with the challenge of styling components efficiently. With numerous conditionals in these components, I am striving to avoid creating an excess of new components that essentially share the same code. The flexibility of incorporating logic in styles through JS is a major advantage compared to the traditional method of conditional class name application.

Here is an example of a complex style that I have been working on:

color:
    props.inactive && (props.buttonType === 'outline' || props.buttonColor === 'red')
    ? colors.greyscaleReg
    : props.buttonColor === 'red'
    ? colors.primaryRed
    : props.buttonType === 'outline'
    ? colors.primaryBlue
    : props.buttonType === 'lightFill'
    ? colors.primaryBlue
    : colors.white,

Personally, I am comfortable with ternaries and can easily navigate through this code. However, some of my colleagues are not fond of nested/chained ternaries like this.

Would it be recommended to extract this logic from the styles?

One suggestion was to create a function to house this code and then call that function within the styles (although an external function cannot be used for hover and may not calculate correctly).

I am not particularly fond of the following approach:

backgroundColor: () => {
        if (props.inactive) {
          return colors.greyscaleLight;
        }
        if (!props.loading && !props.inactive) {
          if (props.buttonType === 'outline') {
            return colors.secondaryPaleBlue;
          }
          if (props.buttonType === 'lightFill') {
            return colors.secondarySoftBlue;
          }
        } else if (props.buttonColor === 'red') {
          return colors.secondaryDarkRed;
        }
        return colors.darkPrimaryBlue;
      },

Answer №1

Avoiding excessive use of nested-ternary conditions is recommended. In the world of JavaScript coding, it is considered a best practice to steer clear of nested-ternary, as highlighted by the widely used linting rule eslint - no-nested-ternary. ESLint serves as a powerful static code analysis tool for identifying problematic patterns within JavaScript code.

When dealing with conditional statements, it is advisable to utilize switch..case or if..else if..else constructs.

For further information, check out these references:

Answer №2

Improve your code structure by separating conditional logic from individual styles using different classNames for various button types.

const styles = makeStyles(theme => ({
  inactive: { color: ..., ... },
  outline: { color: ..., ... },
  ...
}))

const CustomButton = ({ isDisabled, type }) => {
  const { inactive, outline, ... } = useStyles(styles)

  const className = [
    isDisabled && inactive,
    type === 'outline' && outline,
    ...
  ]
    .filter(Boolean)
    .join(' ')

  return (
    <button className={className}>
      ...
    </button>
  )
}

This example utilizes Material UI with hook-flavor JSS, but the concept is applicable to other frameworks as well.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: The function react__WEBPACK_IMPORTED_MODULE_6___default.a.useState is not defined as a function

Hey there! I have been working on some ReactJS code using material-ui, but it seems like I made a mistake with the placement of function handleClickOpen() and function handleClose(). Unfortunately, now my code doesn't compile. Can you help me fix it? ...

Using React.ReactNode as an argument in Storybook

This is a unique button component type that I have created import React from 'react' export type ButtonProps = { label: string; color?:'primary' | 'secondary' | 'tertiary'; size?:'mobile' | 'tabl ...

Position the div element below the navigation bar

I am attempting to embed a Leaflet map within a standard Sails.js view. Sails.js automatically includes a page header on every page. Currently, with a fixed height, the map appears like this: #mapid { height: 400px; } https://i.sstatic.net/pzOdql.jpg ...

Using Special Characters in React JS Applications

When handling CSV uploads with accented characters such as émily or ástha, I encountered the need to encode and pass them to the backend. Experimenting with different approaches, I tried adjusting the file type in FormData from 'text/plain' to ...

"Gone in a Scroll: Div vanishes as page moves

Fiddle: http://jsfiddle.net/ud6hejm6/ I was tasked with creating a website for a video game tournament. By opening the fiddle link provided, you can preview the page layout. A central div is featured in the design: <div class="middle teko" id="mezzo"& ...

I'm struggling to get my React application deployed on GitHub

As a newcomer to React, I have successfully developed several applications but face challenges when attempting to upload my app to Github. The primary issue arises when running npm run build or npm run deploy I consistently encounter the following error ...

ESLint's no-unused-vars rule is triggered when Typescript object destructuring is employed

I'm encountering an issue with my Typescript code where I am destructuring an object to extract a partial object, but it's failing the linter check. Here is the problematic code snippet: async someFunction(username: string): Promise<UserDTO> ...

Looking to recreate this style of table using HTML and CSS?

https://i.sstatic.net/nDrxq.png Trying to replicate the layout from this image for my blog, but struggling with the source code. Any suggestions on how to achieve a similar design without using divs within table rows? Looking for a cleaner solution. ...

When implementing FakeJSON into my React application, it results in the message 'Token is missing - Error'

Has anyone here used the platform app.fakejson.com to generate sample data for their application? I'm attempting to make a post request following the instructions on their site, but I keep receiving an error message stating "Error - token missing", e ...

Can you identify the reason for the hydration issue in my next.js project?

My ThreadCard.tsx component contains a LikeButton.tsx component, and the liked state of LikeButton.tsx should be unique for each logged-in user. I have successfully implemented the thread liking functionality in my app, but I encountered a hydration error, ...

What is the best way to center images horizontally in CSS and HTML?

I'm looking to create a driver's page where the desktop view displays images horizontally instead of vertically. I've tried adjusting the display attribute with limited success, and so far, the grid display is the closest I've come to a ...

Using Meteor with React and createContainer

Utilizing react in combination with meteor, I have a main component named App which encompasses the page layout (Header, Sidebar, Right-sidebar). export default class App extends Component { render() { return ( <div> <nav clas ...

Tips for customizing the background of form inputs in React-Bootstrap

Currently, I have a next.js project with react-bootstrap. I am attempting to change the default blueish gray background color (#e8f0fe or rgb(232, 240, 254)) that bootstrap uses for form inputs to white. To achieve this, I am customizing the bootstrap var ...

Building custom components in Vue.js/NuxtJS can be a breeze when using a default design that can be easily customized through a JSON configuration

Currently, I am in the process of developing a NuxtJS website where the pages and components can either have a generic design by default or be customizable based on client specifications provided in the URL. The URL structure is as follows: http://localh ...

Can you explain the meaning of the code snippet: ` <TFunction extends Function>(target: TFunction) => TFunction | void`?

As I delve into the contents of the lib.d.ts file, one particular section caught my attention: declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void; The syntax in this snippet is a bit perplexing to m ...

"What could be the reason for web3.eth.getAccounts() method returning an empty array when used with console.log

Upon executing web3.eth.getAccounts().then(console.log);, I encountered an empty array and also received a warning stating ./node_modules/web3-eth-accounts/src/scrypt.js Critical dependency: the request of a dependency is an expression. The project began w ...

Button appears and disappears sporadically while browsing in Safari

I created a slider using SCSS, JavaScript, and HTML. You can view the demo at this link: https://jsfiddle.net/rr7g6a1b/ let mySlider = { initializeSlider: function (options) { let slider = options.container; let slides = slider.querySelectorAll( ...

The navigation bar in Bootstrap has unique behavior with links

I am currently in the process of creating a navigation bar using Bootstrap, you can view it here All the links on the navbar are behaving similarly except for the 'Save and exit' link. How can I adjust it to look consistent with the other links? ...

Child div height (with embedded iframe) - issue with responsiveness

I have been working on a simple code for a day now, trying to solve a problem with no progress :( My goal is to display an iframe with a background image. However, the snippet code I have is not showing the background image as intended. You can view the li ...

Is storing HTML tags in a database considered beneficial or disadvantageous?

At times, I find myself needing to modify specific data or a portion of it that originates from the database. For instance: If there is a description (stored in the DB) like the following: HTML 4 has undergone adjustments, expansions, and enhancements b ...