Home > Software design >  Passing both props.children and a component as prop in React/Nextjs
Passing both props.children and a component as prop in React/Nextjs

Time:12-20

User.tsx is a kind of navigation bar that passes all children components through via {props.children}. I also want to pass a breadcrumb component through to it as well but I'm getting an error that says:

JSX element type 'props.component' does not have any construct or call signatures

Layout.tsx:

 import UserShell from "./account/User
 import Breadcrumb from "./navigation/Breadcrumb";
 <User component={Breadcrumb}>{props.children}</User>;

User.tsx:

type ShellProps = {
  children: React.ReactNode | React.ReactNode[];
  component?: React.ComponentType;


export default function UserShell(props: ShellProps) {
 return (
    <>
      <props.component />
      ^^^^^^^^^^^^^^^^^^//error is here

      <div>{props.children}</div>
    </>
}

Any clue on how to fix this?

CodePudding user response:

try updating to this

Layout.tsx:

 import UserShell from "./account/User
 import Breadcrumb from "./navigation/Breadcrumb";
 <User Breadcrumb={Breadcrumb}>{props.children}</User>; //use Breadcrumb or Component (capital C)

User.tsx

type ShellProps = {
  children: React.ReactNode | React.ReactNode[];
  Breadcrumb?: React.ElementType; //covers all elements


export default function UserShell({Breadcrumb, children}) {
 return (
    <>
      <Breadcrumb/>
      <div>{children}</div>
    </>
}

CodePudding user response:

import React from 'react'

type ShellProps = {
    children: React.ReactNode | React.ReactNode[];
    component?: React.ComponentType;
}

function UserShell(props: ShellProps) {
    return (
        <>
            {props.component ? <props.component /> : null}
            <div>{props.children}</div>
        </>
}

playground

you probably need to capitalize the component (Component)

  • Related