简体   繁体   中英

Type JSX.Element is not assignable to type React.ReactNode when using customed conditional render component

I'm using next: "12.1.6" and react: "18.2.0".

I have a template component for conditional rendering.

// Show.tsx
interface Props {
  when: boolean;
  fallback?: React.ReactNode;
  children: React.ReactNode;
}

function Show(props: Props) {
  if (props.when) {
    return props.children;
  }
  return props.fallback ?? null;
}

export default Show;

and I use the template componenet like this but has an issue.

<Show
  when={connectionStatus}
  fallback={
    <div className="border rounded bg-red-400 py-2 px-5">
      ❌ disconnected
    </div>
    }
  >
  <div className="border rounded bg-green-400 py-2 px-5">
    ✅ connected
  </div>
</Show>

at fallback attribute, IDE represents an error "Type JSX.Element is not assignable to type React.ReactNode".

Both React.ReactElement and JSX.Element is a result of React.createElement so I thought there is no specific difference between them except namespace. But it seems React.ReactNode cannot cover JSX.Element .

Waht should I update or change?

ReactNode is a ReactElement, a ReactFragment, a string, a number or an array of ReactNode

But in here you are returning an HTML template which is not part of above mentioned categories. Hence you need to change the type to JSX.Element

fallback?: JSX.Element

Use Function to wrap fallback JSX Element,

like this:

<Show
  when={connectionStatus}
  fallback={() => {
    return <div className="border rounded bg-red-400 py-2 px-5">
      ❌ disconnected
    </div>
    }}
  >
  <div className="border rounded bg-green-400 py-2 px-5">
    ✅ connected
  </div>
</Show>

And update Props interface to:

interface Props extends React.PropsWithChildren<{
  when: boolean;
  fallback?: () => JSX.Element;
}> {}

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