Error: The JSX element's 'children' attribute is expected to have a single child of type 'ReactNode', but it received multiple children

Currently, I am working on a webpage using Next JS.
During development, everything works smoothly without any errors. However, when I build the project for the production environment, I encounter the following error message:
Type error: The 'children' prop of this JSX tag expects a single child of type 'ReactNode', but multiple children were provided.
Here is a snippet of my code:

import React, { useState } from "react";
import { IconContext } from "react-icons";
import { AiOutlineClose } from "react-icons/ai";
import Modal from "react-modal";
import styled from "styled-components";
import styledButton from "../button/styledButton";
import { ModalCloseButton } from "./ModalCloseButton";

interface ShowModalProps {
    text: string,
    children: React.ReactNode
}

const StyledModal = styled(Modal)`
    position: relative;
    margin: 50px auto 0;
    text-align: center;
    width: 100%;
    height: 90%;
    padding: 5%;
    background-color: #555555;
    box-sizing: border-box;
    overflow-y: auto;
    
    @media screen and (min-width: 768px) {
        width: 40%;
        height: 100%;
        padding: 5%;
        margin: 0 auto;
    }
`

export default function ShowModal({ text, children }: ShowModalProps) {
    const [modalIsOpen, setIsOpen] = useState(false);
    
    return (
        <>
            <styledButton text={text} handleModalState={setIsOpen} />
            <StyledModal
                isOpen={modalIsOpen}
                style={{
                    overlay: {
                        display: 'flex',
                        justifyContent: 'center',
                        alignItems: 'center',
                        backgroundColor: 'rgba(0, 0, 0, 0.6)',
                    }
                }}
                onRequestClose={() => setIsOpen(false)}
                ariaHideApp={false}
                className="animate__animated animate__fadeIn"
            >
                <IconContext.Provider value={{
                    style: {
                        width: "100%",
                        height: "100%"
                    }
                }}>
                    <ModalCloseButton buttoncolor="#FFFFFF">
                        <AiOutlineClose onClick={() => setIsOpen(false)} />
                    </ModalCloseButton>
                </IconContext.Provider>
                <p>Modal</p>
                {children}
            </StyledModal>
        </>
    )
}

When I tried to modify the children type like this:
children: JSX.Element
or
children: JSX.Element|JSX.Element[]

It resulted in another error message like this:
Type error: 'Component' cannot be used as a JSX component.
Its element type 'ReactElement<any, any> | Component<{}, any, any> | null' is not a valid JSX element.
Type 'Component<{}, any, any>' is not assignable to type 'Element | ElementClass | null'.
Type 'Component<{}, any, any>' is not assignable to type 'ElementClass'.
The types returned by 'render()' are incompatible between these types.
Type 'React.ReactNode' is not assignable to type 'import("/home/runner/work/next-web/next-web/node_modules/@types/styled-components/node_modules/@types/react/index").ReactNode'.
Type '{}' is not assignable to type 'ReactNode'.

How can I resolve this issue?

Thank you!

Additional Note: This error occurred in the product environment hosted on AWS

Edit:

return (
<>
    <p>Click Button!</p>
    <ShowModal text="Next">
        <form onsubmit={onSubmit}>
            <input  
                type="text"  
                placeholder="write your first name"/>  
            <input  
                type="text"  
                placeholder="write your last name"/>  
            <button>submit</button>
        </form>
    </showModal>
</>
)

Answer №1

Are you currently utilizing the <ShowModal> component? It appears that you may be passing multiple children to the ShowModal component. To resolve this issue, make sure to enclose those components in a <div> or empty angle brackets <> when passing them as props to <ShowModal>.

If you need to pass multiple children, you can achieve this by placing them in an array. In this case, modify your interface to resemble the following:

interface ShowModalProps {
    text: string;
    children: React.ReactNode|React.ReactNode[];
}

This adjustment allows the children prop to accept either a single ReactNode or an array of ReactNodes.


Reviewing the code snippet where you implemented the <ShowModal> component, the closing tag is written as:

</showModal>

To maintain consistency, ensure that the closing tag is capitalized to match the opening tag, like so: </ShowModal>

For a demonstration of your modified code functioning correctly, refer to this example on codesandbox: View codesandbox

Answer №2

If you encounter this issue, it could be due to attempting to render an array of JavaScript objects rather than React nodes. Instead of using

<div>{myObjects}</div>
, you should try:

<ul>
  {myObjects.map(({ title }) => (<li>{title}</li>))}
</ul>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error display in Elastic Apm Rum Angular implementation

Having some issues with incorporating the @elastic/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f5948598d8878098d8949b9280999487b5c7dbc4dbc4">[email protected]</a> package into my project. Angular is throwing console ...

React throwing an error when attempting to iterate over child components

Can anyone help me figure out how to retrieve the image URL for a nested JSON object? I attempted using {post.image.url}, but I received an error stating url undefined I would greatly appreciate any assistance or guidance that can be provided. I am new t ...

Converting Mesh to Object3D: A step-by-step guide

Currently utilizing Typescript alongside Webpack. To create a 3D floor using three.js, I have integrated multiple plane objects (100 in total) with a seamless image serving as their background: import { Scene, PerspectiveCamera, WebGLRenderer, ...

Setting new query parameters while maintaining existing ones without deleting them in Next.js v13

"use client"; import { useCallback, useEffect, useState } from "react"; import Accordion from "../accordion/accordion"; import { useRouter, usePathname, useSearchParams, useParams, } from "next/navigation"; i ...

Automatically selecting the country phone code based on the country dropdown selection

When the country dropdown is changed, I want the corresponding phone code dropdown to be dynamically loaded. <div class="row"> <div class="col-sm-8 col-md-7 col-lg-6 col-xl-5 pr-0"> <div class="form-group py-2"> <l ...

Type guard does not narrow down the union type

Explore the following code snippet: type UnionType = 'foo' | 'bar' | 'baz' const obj = { foo: 'huh', bar: 'hmm' } function func(input: UnionType) { if(input in obj) { input } } In ...

The Hydration error is caused by dynamic imports in NextJS v14.2.3

While updating NextJS from v13 to v14, I encountered a Hydration error due to dynamic imports. Is there a way to resolve this issue? const MyComponent = dynamic(() => import('../components/MyComponent')) Is there a fix that allows for both la ...

Fill up a database with information retrieved from a graphql api

I am currently working on populating a database with data retrieved from an existing GraphQL API. The technology stack for my project includes Next.js, PostgreSQL, Apollo for GraphQL, and Prisma for connecting everything together. I have successfully fetch ...

Symfony using Vite with Vue 3 encounters an error: Uncaught ReferenceError - exports is undefined

Currently, I am in the process of developing a Symfony 3 Application with Vite and Vue3 integrated with TypeScript. To replace Symfony's Webpack Encore, I opted for the Vite Buildtool using this convenient plugin: https://github.com/lhapaipai/vite-bu ...

A guide to limiting the input range in React Native's TextInput field

Is there a way to limit user input to a minimum value of 0 and a maximum value of 100? I've tried validating the data during the onTextChanged event, but it's causing the UI to re-render, which is not the desired effect. I want the same behavior ...

Trouble encountered when attempting to call a function within another function in StencilJS

I am currently following a tutorial on building a drag and drop file uploader using StencilJS for some practice and fun. However, I have encountered an error in the code. Below is a snippet of the code, but I can provide more if necessary. @Component({ ...

Experiencing problems with the Next 13 app API router displaying error 404

I've developed an app to explore the latest Next 13 updates. In this app, there's a service I use to make calls to an API route. interface DrawCardsProps { deck_id: string; } export async function drawCards(deck_id: DrawCardsProps) { console ...

Streamlining Typescript

Within our typescript code base, there is a recurring code pattern: public async publish(event: myEvent, myStr: string): Promise<void> { return new Promise<void>(async (resolve, reject) => { try { await this.doCoolStuff( ...

Encountering issues with @typescript-eslint/typescript-estree due to using a non-officially supported version of TypeScript after updating Nuxt

After upgrading Nuxt in my project using the command npx nuxi upgrade, I encountered an issue while running eslint .. The output displayed a warning regarding the TypeScript version: ============= WARNING: You are currently running a version of TypeScript ...

RouterModule is a crucial external component that is essential for integrating

If I have a very simple component that is part of an Angular component library, it might look like this: mycomponent.module.html <div> <a routerLink="/"> </div> mycomponent.component.ts import { Component, OnInit, Input } from &a ...

Implementing Service Communication

I created an Angular Application using the Visual Studio Template. The structure of the application is as follows: /Clientapp ./app/app.module.shared.ts ./app/app.module.client.ts ./app/app.module.server.ts ./components/* ./services/person-data.service. ...

Creating a custom 404 handler for NextJS using route.js

I am currently running NextJS solely as an API installation. Is there a way to modify the error handler in this setup to receive a JSON response instead of the standard html 404 page provided by NextJS? For instance, when accessing ...

Generate Interface from Current Direct Literal

Imagine having an object literal like this: const defaultConfig = { size: 'medium', shape: 'circle', material: 'metal' } Is there a simple method to generate an interface for this object, instead of manually creating o ...

Are all React libraries compatible with Node.js when requiring them?

Imagine a scenario where I can easily import a library in React by using the following code: import {Something} from someLibrary But the question arises, can I also utilize this same library in my Node.js backend like so? const someLibrary = require(someL ...

Building SVG components in React with TypeScript and styling them using SCSS

I've been experimenting with using Webpack to import SVG files as components in React Typescript. However, I'm running into trouble when it comes to styling the SVGs with SCSS. I've tried targeting a custom attribute in my CSS selector, but ...