Search code examples
javascriptreactjsreact-component

Can't Assign Component to Variable When Checking for Prop


This code works:

import React from 'react'
import { MyComponent } from './components'


export const NewComponent = props => {
  const {
    isValid,
  } = props

  const UseComponent = MyComponent

  return (
    <>
        <UseComponent />
    </>
  )
}

But this code does not work:

import React from 'react'
import { MyComponent } from './components'


export const NewComponent = props => {
  const {
    isSet,
  } = props

  const UseComponent = isSet && MyComponent

  return (
    <>
        <UseComponent />
    </>
  )
}

I.e., I am trying to see whether or not the prop isSet is being used or not. If it is being used, then I want to render the component. If not, then not.

But when I try to do this vis-a-vis assigning it to a variable, I get the following error message:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Is there a way to assign my component to a variable so that it renders if the prop is used, but does not render if it is not used?


Solution

  • isSet && MyComponent asserts to a boolean (forced conversion). Use a ternary operator

    const UseComponent = isSet ? MyComponent : React.Fragment
    

    Or good old if

    let UseComponent = React.Fragment
    
    if(isSet) UseComponent = MyComponent
    

    But usually in a use case like yours we just use conditional rendering

    return isSet ? <MyComponent /> : null