Error: JSX expressions must have one parent element in ReactJs

Dung Do Tien May 27 2022 451

Hello you guys. I am a newbie in ReactJs and I am learning about the state, I'm trying to create a small app to use useEffect and  useState method. I want to know how they work. Like this:

Couter.tsx

 import React, { useEffect, useState } from 'react';

export default function CountApp() {
  const [counter, setCounter] = useState(0);

    useEffect(() => {
      if (counter > 0) {
      console.log('count: ' + counter);
       }
    });
 
  return (
      <button onClick={() => setCounter(counter + 1)}>Click counter</button>
      <h1>Total count: {counter}</h1>
  );
} 

index.tsx

 import * as React from 'react';
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';

import CountApp from './CountApp';

const rootElement = document.getElementById('root');
const root = createRoot(rootElement);

root.render(
  <StrictMode>
    <CountApp />
  </StrictMode>
); 

But when I run this app, I get an exception throw JSX expressions must have one parent element.

What is that mean? I installed react version 18.0.8.

I really appreciate any help you can provide.

Have 1 answer(s) found.
  • s

    stoyo May 27 2022

    The error SX expressions must have one parent element occurs because your CountApp component returns many HTML tags. This is not alow in React.  A component cannot return multiple elements, just like a function can't return multiple values (unless they're wrapped in an array, which is a single value).

    you can wrap all HTML inside a div, like this:

     return (
        <div>
          <button onClick={() => setCounter(counter + 1)}>Click counter</button>
          <h1>Total count: {counter}</h1>
        </div>
      );

    Or using <React.Fragment> tag like a container tag, like this:

     return (
        <React.Fragment>
          <button onClick={() => setCounter(counter + 1)}>Click counter</button>
          <h1>Total count: {counter}</h1>
        </React.Fragment>
      );

    I hope these solutions will useful to you.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close