0

Is there any way so that I can minimize the following code-

    <div className="App">
      <Checkbox parameter={parameter1} setParameter={setParameter1}></Checkbox>

      { parameter1.country && parameter1.category ?
        <ShowData parameter1={parameter1}></ShowData>
        : ""
      }
      { parameter1.country && parameter1.category ?
        <Chart1></Chart1>
        : ""
      }
      { parameter1.country && parameter1.category ?
        <Chart2></Chart2>
        : ""
      }

    </div>

Here I have mentioned parameter1.country && parameter1.category three times. I want to write just single time.

enter image description here

  • 3
    those three "conditions" are all the same - so why not just lump all the html into one block between `?` and `:` – Jaromanda X Oct 08 '20 at 05:16

3 Answers3

1

<div className="App">
  <Checkbox parameter={parameter1} setParameter={setParameter1}></Checkbox>
  { parameter1.country && parameter1.category &&
    <React.Fragment>
      <ShowData parameter1={parameter1}></ShowData>
      <Chart1></Chart1>
      <Chart2></Chart2>
    </React.Fragment>
  }
</div>

Based on your code sample, parameter1.country && parameter1.category is common for all conditions and rather use ? ternary operator, I would like to suggest && will reduce empty string on your code.

Use <React.Fragment> to combined all the similar components.

ankitkanojia
  • 3,072
  • 4
  • 22
  • 35
1
<div className="App">
      <Checkbox parameter={parameter1} setParameter={setParameter1}></Checkbox>
      { 
        parameter1.country && parameter1.category &&
        <>
        <ShowData parameter1={parameter1}></ShowData>
        <Chart1></Chart1>
        <Chart2></Chart2>
        </>
      }
    </div>
Piyush Rana
  • 631
  • 5
  • 8
0

There is the same condition that you applied thrice in your code. And in all the three places you are showing nothing in case of the false condition.

I think you can do it by below code -

<div className="App">
  <Checkbox parameter={parameter1} setParameter={setParameter1}></Checkbox>
  { parameter1.country && parameter1.category ?
    <div>
     <ShowData parameter1={parameter1}></ShowData>
     <Chart1></Chart1>
     <Chart2></Chart2>
    </div>
    : ""
  }
</div>
Alok Mali
  • 2,821
  • 2
  • 16
  • 32