skip to Main Content

I want to render a Home component if certain condition is met.

I tried to use the Inline If-Else with Conditional Operator provided by React.

My code looks like this:

import Home from './components/Home';

...

<Box component="main" sx={{ flexGrow: 1, p: 3 }}>
  {menudata === "Home" && <Home />}
</Box>

Apparently react expects a string after the && (conditional operator). The error I get is:

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

My Home.js component

import React from 'react'

const Home = () => {
  return (
    <div>Home</div>
  )
}

export default Home

Using React 18.2.0 with MUI.

2

Answers


  1. Chosen as BEST ANSWER

    I recreated the Home.js file and now it works


  2. The error message suggests that the component "Home" is not being recognized as a valid component by React.

    Try to use following ways

    • Please check the path of "./components/Home"
    • Please check the export statement in the Home component file
      export default Home, or spell checking*
    • Please try this
      Change {menudata === "Home" && } to {menudata === "Home" ? : null}
    • If you still encounter issues, finally try this
      Change name Home.js to Home.jsx

    Happy coding

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search