Skip to content Skip to sidebar Skip to footer

Conditional Rendering Of Nested Components Based On Condition

Unsure how to write the following nested if/else as a nested ternary within a React app, i.e. if (jobId === 1) { if (activeFlag === 1) { } else if (active

Solution 1:

A more readable solution could be create an inline render function as

const renderThisThing = () => {
  if (jobId !== 1) {
    returnnull
  }

  if (activeFlag === 1) {
    return <RenderA />
  }

  if (activeFlag === 2) {
    return <RenderB />
  }

  if (activeFlag === 3) {
    return <RenderC />
  }

  returnnull
}


const elementToIncludeInTheJSX = renderThisThing()

and then put {elementToIncludeInTheJSX} in the place you want to render the component. You can inline this function in the body of your component, or make it a real React component, and pass jobId and activeFlag as props.

functionComplexRenderComponent({ jobId, activeFlag }) {
  if (jobId !== 1) {
    returnnull
  }

  if (activeFlag === 1) {
    return<RenderA />
  }

  if (activeFlag === 2) {
    return<RenderB />
  }

  if (activeFlag === 3) {
    return<RenderC />
  }

  returnnull
}

and you use it as <ComplexRenderComponent jobId={jobId} activeFlag={activeFlag} /> in your component.

Solution 2:

Try this jobId === 1 ? activeFlag === 1 ? <RenderA /> : activeFlag === 2 ? <RenderB /> : activeFlag === 3 && <RenderC /> : ""

Post a Comment for "Conditional Rendering Of Nested Components Based On Condition"