Henok Tesfaye
Henok Tesfaye

Reputation: 9560

Early return a component inside a react functional component with hooks

const LecturesExerciseItem = props => {
  const hasMultipleVideos = hasSectionMultipleVideos(props.sectionUUID)
  if (!hasMultipleVideos) return <SectionListItem {...props} />

  // multiple videos
  const [isAccordionOpen, setIsAccordionOpen] = useState(false)
  ....
  return <h1> multiple videos </h1>
}

React Hook "useState" is called conditionally. React Hooks must be called in the exact same order in every component render.

How can early return some component based on condition inside functional component with hooks?

Upvotes: 0

Views: 1070

Answers (1)

kkesley
kkesley

Reputation: 3396

You have 2 options:

  1. Put hooks on top of the component
  2. Use a wrapper component e.g.
const LecturesExerciseItem = props => {
  const hasMultipleVideos = hasSectionMultipleVideos(props.sectionUUID)
  if (!hasMultipleVideos) return <SectionListItem {...props} />

  // multiple videos
  ....
  return <MultipleVideos {...props}/>
}

const MultipleVideos = props => {
  const [isAccordionOpen, setIsAccordionOpen] = useState(false)
  ....
  return <h1> multiple videos </h1>
}

Upvotes: 3

Related Questions