简体   繁体   中英

How do you pass props to a React component after importing it dynamically?

I'm running a Next.js, React, Ts project.

I have imported a React component dynamically into my page, with ssr set to false as the component contains references to window and these references to window would throw ReferenceError: window is not defined .

const myComponent = dynamic(
  () => import('../components/myComponent').then(mod => mod.myComponent),
  { 
    ssr: false ,
  }
)

export default function Home() {
return (
    <div>
      <Head>
        <title>My site</title>
      </Head>

      <main>
          <myComponent name="Damian" age={27} />
      </main>
    </div>
  )
}

However when I call it in my page I can't pass its properties to it and I get the error:

Type '{ name: string; age: number; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'.

I feel like I'm definitely missing something.

You can simply clone your component and can pass props of your choice.

let component = myComponent;
let props = { name: "Damian" age: 27 };

return (
    <div>
      <Head>
        <title>My site</title>
      </Head>

      <main>
        {React.cloneElement(component, props)}
      </main>
    </div>
  )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM