Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Component inside a component

I am working with React.js

I want to use a component x inside app component(app.js) that is inside index.js.

It does not work.
**

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Error
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.
Check the render method of `App`.

**

index.js

    import { StrictMode } from "react";
import { createRoot } from "react-dom/client";

import App from "./App";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
  <StrictMode>
    <App />
  </StrictMode>
);

App.js

import "./styles.css";
import {SubComponent} from "./components/Subcomponent";

export default function App() {
  return (
    <SubComponent/>
  );
}

Subcomponent

const HelloWorld = ()=>{ return(<p>Hello World !</p>)}
export default HelloWorld();

Subcomponent folder is :

enter image description here

>Solution :

Your subcomponent:

  • needs to export the same name as what’s being imported in App – either use the same named import/export in both places, or use default import/export in both places. (You’re currently importing a named SubComponent but default exporting)
  • needs to export a component, which is a function, so that it can be called with React.createElement inside App. Don’t invoke the function yourself.

App.js

import {SubComponent} from "./components/Subcomponent";

Subcomponent

export const SubComponent = () => {
  return(<p>Hello World !</p>)
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading