Home > Back-end >  NextJs and Typescript passing values to parent
NextJs and Typescript passing values to parent

Time:02-21

I've made a component

        <ConnectWallet setConnected={(t: boolean) => console.log(t)}>
          <>test</>
        </ConnectWallet>

The component starts like

import { useState, useEffect } from 'react';
import type { NextPage } from 'next';

declare global {
  interface Window {
    ethereum: any;
  }
}

export interface PropsShape {
  setConnected: (t: boolean) => void;
  children: ReactNode;
}

const ConnectWallet: NextPage = ({ setConnected, children }: PropsShape) => {
...

Error on the parent is

Type '{ children: Element; setConnected: (t: boolean) => void; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'.
  Property 'setConnected' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; }'.ts(2322)

Error on the child is

Type '({ setConnected, children }: PropsShape) => JSX.Element' is not assignable to type 'NextPage<{}, {}>'.
  Type '({ setConnected, children }: PropsShape) => JSX.Element' is not assignable to type 'FunctionComponent<{}> & { getInitialProps?(context: NextPageContext): {} | Promise<{}>; }'.
    Type '({ setConnected, children }: PropsShape) => JSX.Element' is not assignable to type 'FunctionComponent<{}>'.
      Types of parameters '__0' and 'props' are incompatible.
        Property 'setConnected' is missing in type '{ children?: ReactNode; }' but required in type 'PropsShape'.ts(2322)
ConnectWallet.tsx(13, 3): 'setConnected' is declared here.

CodePudding user response:

Pass the props type to NextPage:

const ConnectWallet: NextPage<PropsShape> = ({ setConnected, children }) => {

But should this really be a page if it's a child component?

CodePudding user response:

If you want to reuse ConnectWallet between 2 different pages, I'd extract it to a separate component. Right now, you're trying to render one page inside of, presumably, another.

To fix the immediate issue you have, try to change:

const ConnectWallet: React.FC<PropsShape> = ({ setConnected, children }) => {

Also, you don't have to define children inside of PropsShapre

  • Related