0

I have some conditional styling based on if a certain value exist. The value can exist or can be null

background-color: ${myPropValue.myKey !== null ? 'pink' : 'green'};

This works fine. However I need to add some more conditional styling based on the same logic in this file.

I try to create a function which I can reuse:

const hasMyPropValue = ({ myPropValue }: Pick<MyType, 'myPropValue'>) =>
  myPropValue.myKey !== null;

When I want to use it like background-color: ${hasMyPropValue() ? 'pink' : 'green'}; I get a linting error: Expected 1 arguments, but got 0.ts(2554)

I just want it to return true or false?

meez
  • 3,783
  • 5
  • 37
  • 91

4 Answers4

0

According to my opinion, you define css properties with a class name. When ${myPropValue.myKey !== null then you add particular class what you want. From this you able to define multiple properties.

0

I try to create a function which I can reuse: ... I don't want to pass any argument I just want it to return true or false?

With the two statements you made, the myPropValue has to either be passed an argument or be available in the scope where hasMyPropValue is located because you've typed it as required.

Pourya Da
  • 54
  • 2
  • 5
0

When you do not want to pass any arguments, then you can define the params as optional parameters like below and also can provide default values to the parameters.

function hasMyPropValue({
  myPropValue = {
    myKey: null
  }
}: {
  myPropValue? : Object
} = {}) {
  return myPropValue.myKey !== null;
}

console.log(hasMyPropValue() ? 'pink': 'green');
Nithish
  • 5,393
  • 2
  • 9
  • 24
  • thanks. And when I pass an argument like `${hasMyPropValue({myPropValue}) ? 'pink' : 'green'};` can we write a less verbose function? – meez Feb 28 '21 at 07:40
  • We can create another function which makes a call to `hasMyPropValue` to get the respective class name. – Nithish Feb 28 '21 at 07:44
  • If it is just a styling change, then this approach is good enough. – Nithish Feb 28 '21 at 11:40
  • What I meant previously was, if `${hasMyPropValue({myPropValue}) ? 'pink' : 'green'};` this is the condition you are using more than once, then you can create another function say `getColor` which returns either `pink` or `green` based on the return value of `hasMyPropValue`. – Nithish Feb 28 '21 at 11:43
0

My initial function was almost correct:

const hasMyPropValue = ({ myPropValue }: Pick<MyType, 'myPropValue'>) =>
  myPropValue.myKey !== null;

But here I check if type is not of type null and if it's undefined. That doesn't work in this case.

I changed the comparison operator (!= instead of !==) and then my function works. You can read more about it here.

const hasMyPropValue = ({ myPropValue }: Pick<MyType, 'myPropValue'>) =>
 myPropValue.myKey != null;
meez
  • 3,783
  • 5
  • 37
  • 91