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.
**

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>)
};

Leave a Reply