Home > Enterprise >  How can I implement an error-free dynamic in-line style in react with typescript?
How can I implement an error-free dynamic in-line style in react with typescript?

Time:06-06

Even though the code works, the following problem is shown by typescript:

Type '{ flexDirection: string; justifyContent: string; alignItems: string; marginLeft: string; minHeight: string; } | null' is not assignable to type 'CSSProperties | undefined'.
  Type 'null' is not assignable to type 'CSSProperties | undefined'.ts(2322)

What I want to do is flexibly change the style of an element based on a boolean prop:

<nav style={refs.vertical === true ? verticalStyle : null} className={styles.navWrapper}>

And "verticalStyle" is defined as the following:

  const verticalStyle = {flexDirection: 'column',
  justifyContent:'space-evenly',
  alignItems: 'flex-start',
  marginLeft: '2rem',
  minHeight: 'inherit'
}

Since the code runs perfectly fine (and did so earlier in the pure JS version), I wonder why TS struggles with recognizing that I am, in fact, passing valid CSS properties. Apart from silencing the error, is there any way to solve this elegantly and error-free?

CodePudding user response:

Instead of returning null, return an empty object or undefined since the Type is CSSProperties | undefined.

<nav style={refs.vertical === true ? verticalStyle : {}} className={styles.navWrapper}>

or

<nav style={refs.vertical === true ? verticalStyle : undefined} className={styles.navWrapper}>

CodePudding user response:

So after quite some searching, I finally found the answer. Basically, it is not possible to pass the style as a variable in Typescript. Instead, the style has to be applied directly inline. I couldn't find out exactly why that is, but here's the solution:

<nav style={refs.vertical === true ? {
      flexDirection: 'column',
      justifyContent: 'space-evenly',
      alignItems: 'flex-start',
      marginLeft: '2rem',
      minHeight: 'inherit'
    }
      : undefined}
  • Related