Vikas Kumar
Vikas Kumar

Reputation: 138

How Can make this JSX compact?

{
  this.state.isLoadingInputDropDown &&
  <option value="-1" disabled >Loading...</option >
}

{/* TODO : was not able to combine below statements */}
{
  !this.state.isLoadingInputDropDown
  && <option value="-1" >--Select a Accessorial Charge first --</option>
}
{                                            
  !this.state.isLoadingInputDropDown
  && this.state.allInputs.length > 0
  && this.state.allInputs.map(
    (input) => (<option value={input.id} key={input.id}>{input.name}</option>)
  )
}

trying to make this JSX one-liner or something compact. I tried every possible (which I can think of) structure

Upvotes: 0

Views: 197

Answers (3)

Tobias
Tobias

Reputation: 954

Maybe you declare the content before returning jsx.

const dropdown = this.state.isLoadingInputDropDown ? <option value="-1" disabled >Loading...</option > : <option value="-1" >--Select a Accessorial Charge first --</option>;

const otherOptions = this.state.isLoadingInputDropDown || !(this.state.allInputs.length > 0) ? null : this.state.allInputs.map(
    (input) => (<option value={input.id} key={input.id}>{input.name}</option>)
);

return (
    <select>
        { dropdown }
        { otherOptions }
    </select>
);

Upvotes: 0

Sulthan
Sulthan

Reputation: 130102

Ideally, split the whole function into two parts:

let options;

if (this.state.isLoadingInputDropDown) {
   const defaultOption = <option value="-1" disabled >Loading...</option>;
   options = [defaultOption];
} else {
   const defaultOption = <option value="-1" >--Select a Accessorial Charge first --</option>;
   const choices = this.state.allInputs.map(
       (input) => (<option value={input.id} key={input.id}>{input.name}</option>)
   )
   options = [defaultOption, ...choices];
}

return (
   <select>
      {options}
   </select>
);

The this.state.allInputs.length > 0 check is not necessary.

Don't try to make this a one-liner. It's not important how long code is. The important thing is to make it readable. You should actually consider splitting this piece of code into multiple functions.

Upvotes: 1

TryingToImprove
TryingToImprove

Reputation: 7407

You could do something like this;

return (
    <select>
        {this.state.isLoadingInputDropDown
            ? <option value="-1" disabled >Loading...</option>
            : [{ id: -1, name: '--Select a Accessorial Charge first --'}, ...this.state.allInputs].map(
                (input) => (<option value={input.id} key={input.id}>{input.name}</option>)
            )}
    </select>
) 

Upvotes: 0

Related Questions