JavaScript

JavaScript

By DeepSource

Validation of JSX maximum depth JS-0415

Anti-pattern

Nesting JSX elements too deeply can confuse developers reading the code. To make maintenance and refactoring easier, DeepSource recommends limiting the maximum JSX tree depth to 3.

Code that looks like this is nearly unreadable for someone unfamiliar:

function App() {
  return <Foo>
    <Bar>
      <Baz>
        <Barz/>
      </Baz>
    </Bar>
  </Foo>
}

Bad Practice

function FormContainer() {
  // This JSX tree is too deep
  return <FormWrapper>
    <Form>
      <FormEntry>
        <Label>Name</Label>
        <FormInput type="text" / >
      </FormEntry>
    </Form>
  </FormWrapper>
}

Recommended

function FormContainer() {
  // the FormEntry component has been modified to accept the labelName and inputType.
  // It now returns JSX that contains a label and a field.
  return <FormWrapper>
    <Form>
      <FormEntry labelName="Name" inputType="text">
      </FormEntry>
    </Form>
  </FormWrapper>
}