0

This is my case:

<Form onSubmit={submit}>
                    {something === 0 ?
                        (someData.length && someData.length > 0) ?
                            doSomething() : null :
                        (someOtherData.length && someOtherData.length > 0) ?
                            doSomethingElse() : null
                    }
</Form>

However, eslint rule is giving me error: Do not nest ternary expressions.

How can this be avoided? Can if - else be written in return (...) which renders data?

storagemode11
  • 875
  • 7
  • 11
  • 1
    Duplicate of [if-else-statement-inside-jsx-reactjs](https://stackoverflow.com/questions/44046037/if-else-statement-inside-jsx-reactjs) or [how-to-do-a-nested-if-else-statement-in-reactjs-jsx](https://stackoverflow.com/questions/37312122/how-to-do-a-nested-if-else-statement-in-reactjs-jsx) – sugars Nov 08 '19 at 01:11
  • If your logic gets increasingly complex, you could always just move it outside the render into a function and call the function in the render – Jon Warren Nov 08 '19 at 01:15

2 Answers2

1

could you do the validations before the return of the render method

render () {
  myComponent = <></>;

  if (something === 0) {
      if (someData.length && someData.length > 0) {
        myComponent = doSomething();
      }
  } else if (someOtherData.length && someOtherData.length > 0) {
      myComponent = doSomethingElse();
  }

  return (
    <Form onSubmit={submit}>
      {<myComponent/>}
    </Form>
  )
}

If you want the validations within the component you could try it this way

<Form onSubmit={submit}>
    {
      something === 0 && someData.length && someData.length > 0
        ? doSomething()
        : something !== 0 && someOtherData.length && someOtherData.length > 0 && doSomethingElse()
    }
</Form>
  • @storagemode11 try it `{ something === 0 && someData.length && someData.length > 0 ? doSomething() : something !== 0 && someOtherData.length && someOtherData.length > 0 && doSomethingElse() }` – Jorge Martinez Jimenez Nov 08 '19 at 01:37
1

Encapsulate the behaviour into a function on the component

renderComponent() {
  return something ?
    someOtherData.length && doSomethingElse() :
    someData.length && doSomething();
}

render() {
  ...
  return (
    <Form onSubmit={submit}>
      {renderComponent()}
    </Form>
  );
}

Tip - you don't need to explicitly pass null, React supports conditional rendering

James
  • 80,725
  • 18
  • 167
  • 237