React Error – jsx expressions must have one parent element

Total
0
Shares

React throws the error, jsx expressions must have one parent element, when you try to return JSX without having any enclosing container element. This is a very common error and its solution is simple.

Why it occurs?

React expects the components to return only a single element. This element could have nested elements and that’s not a problem. So, suppose you are rendering 3 buttons and returning from a component without any parent, then react will throw an error. This below code won’t work –

export default function App(){
  return(
    <button>Ironman</button>
    <button>Thor</button>
    <button>Hulk</button>
  );
}

The problem here is that App can’t return 3 button components.

Also, if you return an expression then react will throw error –

export default function App(){
  return(
    {'Iron Man'}
  );
}

Solution

Enclose everything within one parent.

So, in our example, we can render the button if we enclose them within a div.

export default function App(){
  return(
    <div>
      <button>Ironman</button>
      <button>Thor</button>
      <button>Hulk</button>
    </div>
  );
}

What if we don’t want to use any parent?

There may be situations when you can’t use a parent. For example, a component is returning few list items. Here, you can’t enclose them in <div> otherwise that will be syntactically invalid. List items should only be enclosed within <ul> or <ol>. Check this example –

export default function App(){

  const ReturnOnlyLI = () => {
    return(
      <li>Ironman</li>
      <li>Thor</li>
      <li>Hulk</li>
    )
  }

  return(
    <div>
      <ul>
        <li>Captain America</li>
        <ReturnOnlyLI />
      </ul>
    </div>
  );
}

In this code, we can’t enclose li returned by ReturnOnlyLI component within ul or ol because one list item, Captain America was not returned by it. So, we can’t enclose them in any element. We need something which enclose the list items but won’t render on DOM.

React provides a solution for this. It has <React.Fragment> component and <> component which can be used to enclose elements and they won’t render on DOM.

So, in our example, we can simply use –

export default function App(){

  const ReturnOnlyLI = () => {
    return(
      <React.Fragment> // or simply <>
        <li>Ironman</li>
        <li>Thor</li>
        <li>Hulk</li>
      </React.Fragment> // or </>
    )
  }

  return(
    <div>
      <ul>
        <li>Captain America</li>
        <ReturnOnlyLI />
      </ul>
    </div>
  );
}

    Tweet this to help others

With these solutions, you can solve the error of jsx expressions must have the parent element.

Live Demo

Open Live Demo