Moshe
Moshe

Reputation: 6991

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?

Upvotes: 4

Views: 263

Answers (2)

Dupocas
Dupocas

Reputation: 21317

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

Upvotes: 4

ravibagul91
ravibagul91

Reputation: 20755

You can also do this,

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

  const UseComponent = MyComponent

  return (
    <>
        {isSet && <UseComponent />}
    </>
  )
}

Upvotes: 2

Related Questions