U
U
uRoot2021-01-18 14:51:18
React
uRoot, 2021-01-18 14:51:18

How to set if-else in styles?

There is this:

<p
  style={{ bottom:  (669 * size) / SIZES.MAX }}
>

How to write { bottom: (669 * size) / SIZES.MAX } in if, and add other values ​​in style for else?
To get something like:
<p
  style={SIZES.MAX > 0 
     ?
     { bottom:  (669 * size) / SIZES.MAX } 
     : 
    { bottom:  (669 * size) } 
  }
>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Valery Kulakov, 2021-01-18
@uroot

As Valery noted , the error is most likely because you are passing a number. Try passing a string (you can use "back quotes "):

<p
    style={
        SIZES.MAX > 0 ? {
            bottom:  `${(669 * size) / SIZES.MAX}px`,
            color: `red`
        } : {
            bottom:  `${(669 * size)}px`,
            color: `blue`
        }
    }
>

But in general, if there are a lot of styles, I would take it out of "inline". For example, through a function:
class MyParagraph extends React.Component {
  render() {
    //init values
    const SIZES = {MAX: 45};
    const size = 1;
    
    //get styles
    function getParagraphStyles(condition) {
      if (condition > 0) {
        return {
          bottom: `${(669 * size) / SIZES.MAX}px`,
          color: `red`,
        }
      } else {
        return {
          bottom: `${(669 * size)}px`,
          color: `blue`,
        }
      }
    }
    
    return (
      <p style={getParagraphStyles(SIZES.MAX)}>
        Paragraph
      </p>
    )
  }
};

It's even better to put getParagraphStyles() in a method (if you're using a class approach) or a hook (if you're using a functional approach). Instead of if .. else, you can also use a ternary. You can also write an arrow - it will be even shorter. But I did it in more detail for clarity. And yes, as Valery noted , do not forget to specify units of measurement (px, most likely). React like CSS checks and doesn't miss the wrong one.

V
Valery, 2021-01-18
@vmakhnyuk

<p style={{bottom: SIZES.MAX > 0 ? `${(669 * size) / SIZES.MAX}` : `${669 * size}`}}

values ​​for css fields should be strings. Also, you need to add units (px, em, rem...) for these values

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question