Home > OS >  Create React element from object attribute (with props)
Create React element from object attribute (with props)

Time:09-16

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 ?

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

CodePudding user response:

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

CodePudding user response:

Try this

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

CodePudding user response:

If you want to render a component instance, you have to:

  1. pass: component: <MyComponent />
  2. use: {component}

If you have to pass a component:

  1. pass: Component: MyComponent
  2. use: <Component />

If you want to pass a render prop:

  1. pass: component: (params) => <MyComponent {...params} />
  2. use: {component()}
  • Related