Home > Software design >  React v18 causes error without code changes, JSX no longer accepted?
React v18 causes error without code changes, JSX no longer accepted?

Time:05-30

Since React 18 I have some errors when rendering the application and can't nest any elements as it seems. For example, I have the following code in my application:

return (
        <Card>
            <div className={`flex flex-row justify-content-center align-items-center`}>
                {props.icon}
                <h2>{props.text}</h2>
            </div>
            <div className={"flex justify-content-center align-items-center"}>
                <Button onClick={() => props.onButtonClick()} className={"w-2"} label={props.buttonText}/>
            </div>
        </Card>


    );

This code worked fine up to React 18, now from 18 version I get the following error: enter image description here

Likewise, element arrays can no longer be rendered, again, the following code worked fine in React17:

  <DataTable metaKeySelection={false} selectionMode={"single"} onSelectionChange={e => {
                                setSelection(e.value)
                            }} selection={selection} stripedRows={true} showGridlines={true} size={"small"}
                                       value={artifacts}>
                                {colModels}
                            </DataTable>

And now since React18 the following problem occurs: enter image description here

It seems to me that with v18 React expects React Nodes everywhere and JSX as such is no longer accepted. These errors disappear as soon as I enclose said elements with a React fragment, is this really the only way to solve this problem?

Thanks in advance!

CodePudding user response:

Yes React 18 did make some changes I am not sure about your second issue but your first issue with card can be fixed like this...

Just add <> and </> React Fragment as the singlular child.

<Card>
   <>
            <div className={`flex flex-row justify-content-center align-items-center`}>
                {props.icon}
                <h2>{props.text}</h2>
            </div>
            <div className={"flex justify-content-center align-items-center"}>
                <Button onClick={() => props.onButtonClick()} className={"w-2"} label={props.buttonText}/>
            </div>
  </>
</Card>
  • Related