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

Create React element from object attribute (with props)

In the following code I would like to pass props to the e.component element
But i’m getting an error :

Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

How can i do that ?

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

element={<MainComponent msg={msg} />} works but it does not meet my needs ❌❌
The element must be called like this e.component ✔️✔️

const routes = [
  {
    name: `main`,
    path: `/main`,
    component: <MainComponent />,
  },
]

function MainComponent(props) {
  return <h2>{`Hello ${props.msg}`}</h2>
}

function App() {
  const msg = `world`
  return (
    <BrowserRouter basename="/">
      <Routes>
        {routes.map((e, j) => {
          return (
            <Route
              key={`${j}`}
              path={e.path}
              // want to pass "msg" props to e.component ???????
              element={<e.component msg={msg} />}
            />
          )
        })}
      </Routes>
    </BrowserRouter>
  )
}

>Solution :

If you want to be able to pass additional props at runtime then you can’t pre-specify MainComponent as JSX. Instead you could specify MainComponent as a reference to the component instead of JSX, and then render it as JSX when mapping. Remember that valid React components are Capitalized or PascalCased.

Example:

const routes = [
  {
    name: 'main',
    path: '/main',
    component: MainComponent,
  },
];

function MainComponent(props) {
  return <h2>Hello {props.msg}</h2>;
}

function App() {
  const msg = 'world';
  return (
    <BrowserRouter basename="/">
      <Routes>
        {routes.map((e, j) => {
          const Component = e.component;
          return (
            <Route
              key={j}
              path={e.path}
              element={<Component msg={msg} />}
            />
          )
        })}
      </Routes>
    </BrowserRouter>
  );
}
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