Volodymur
Volodymur

Reputation: 75

How can I make a check in input value (React)

I have and custom input that I use in my project. And I want to make check on input value before put it in props. I put in input value number which I get from mapping array. I want to make a check like if arrVal !== 0 put arrVal else put 1

{arr.map((it, i) => (
    <Input
        value={it.num} // here make a check like it.num !== 0 ? it.num : 1
    />
))}

Upvotes: 4

Views: 88

Answers (3)

marzzy
marzzy

Reputation: 788

You could pass the conditional Statement to the value, like this:

{arr.map((it, i) => (
   <Input
      value={it.num !== 0 ? it.num : 1}
   />
))}

or if the condition is more complicated you can store the result on a variable then use it, like this:

{arr.map((it, i) => {
   const result = it.num !== 0 ? it.num : 1;
   
   return (
      <Input value={result} />
   )})
}

Upvotes: 3

Drew Reese
Drew Reese

Reputation: 202836

You can use a guard clause with fallback value:

{arr.map((it, i) => (
  <Input key={i} value={(it && it.num) || 1} />
))}

Or use Optional Chaining with fallback value:

{arr.map((it, i) => (
  <Input key={i} value={it?.num || 1} />
))}

Don't forget the React key for the mapped elements.

Upvotes: 2

Surjeet Bhadauriya
Surjeet Bhadauriya

Reputation: 7156

Just add this value={it.num || 1}

{arr.map((it, i) => (
    <Input
        value={it.num || 1} 
    />
))}

Upvotes: 1

Related Questions