Jsx expressions must have one parent element как исправить

React throws error, jsx expressions must have one parent element, if a component returns JSX without any enclosing container element.

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

This is Akash Mittal, an overall computer scientist. He is in software development from more than 10 years and worked on technologies like ReactJS, React Native, Php, JS, Golang, Java, Android etc. Being a die hard animal lover is the only trait, he is proud of.

Related Tags
  • Error,
  • react js short,
  • reactjs error

The error JSX expressions must have one parent element in React occurs when you do not guarantee encapsulation of a component with a parent element. This article will give you solutions to this error with detailed code examples.

The reason for the error JSX expressions must have one parent element in React

This error occurs when you leave the tags discrete in a React function component or a React class component without being wrapped by a parent tag. This will lose the encapsulation of a component, so the IDE will give us an error like the example below.

Code:

import React from 'react';

const App = () => {
    return (
        <div id="header">Header</div>
        <div id="content">Content</div>
        <div id="footer">Footer</div>
    );
};

export default App;

Output:

As in the example above, we are leaving three discrete div tags in the JSX file, so when pointing to any div tag, the error JSX expressions must have one parent element in React will appear. Follow along to the next part of the article to know the solutions to this error

How to fix this error

Wrapping JSX element in an enclosing tag

This way, we can enclose tags in JSX such as <>, <React.fragment>. Here are some tags used to wrap the child tags to ensure the encapsulation of the React component. Let’s see how we use it in the code examples below.

Code:

import React from "react";

const App = () => {
    return (
        <>
            <div id="header">Header</div>
            <div id="content">Content</div>
            <div id="footer">Footer</div>
        </>
    );
};

export default App;
import React from "react";

const App = () => {
    return (
        <React.Fragment>
            <div id="header">Header</div>
            <div id="content">Content</div>
            <div id="footer">Footer</div>
        </React.Fragment>
    );
};

export default App;

Output:

Fragments are a typical pattern introduced since React 16 was born. It allows you to return multiple elements from a component without generating unnecessary DOM elements. The effect of the empty <> tag is the same as that of the Fragment. I recommend using these two tags instead of a <div> tag to avoid creating unnecessary ones.

Putting elements into an array

In this way, we will put the child elements into an array. The program will automatically recognize the array and render each element in turn inside this array of elements. Let’s see how we use arrays to prevent the error JSX expressions must have one parent element in React in the following code.

Code:

import React from "react";

const App = () => {
    return [
        <div id="header">Header</div>,
        <div id="content">Content</div>,
        <div id="footer">Footer</div>,
    ];
};

export default App;

We need to use square brackets [] to enclose the HTML elements, and we have an array of elements. The code, after being fixed, will no longer have the error that JSX expressions must have a parent element in React. Good luck with the methods mentioned in the article.

Summary

In summary, the article has told you some solutions to the error JSX expressions must have one parent element in React. However, I recommend you to use wrapping JSX element in an enclosing tag solution because it is easier to use

Nathaniel Kirk

Hi, my name’s Nathaniel Kirk. I’m interested in learning and sharing knowledge about programming languages. My strengths are C, C++, Python, HTML, CSS, Javascript, and Reactjs. If you have difficulty with them, don’t worry. I’m here to support you.


Name of the university: PTIT
Major: IT
Programming Languages: C, C++, Python, HTML, CSS, Javascript, Reactjs

Problem Statement

Have you tried rendering multiple React components like this:

class ParentC extends React.Component {
    render() {
        return (
            <ChildC />
            <ChildC />
        )
    }
}class ChildC extends React.Component {
    render() {
        return (
            <h1>
                Child Component
            </h1>
        )
    }
}

or render a list of nodes like this:

class ChildComponent extends React.Component {
    render() {
        return (
            <h1>Hello Child Component</h1>
            <h1>Hello Child Component</h1>
        )
    }
}

If you are using VS Code with JSX support extensions you will have a warning showing: “JSX parent expressions must have one parent element”.

To make the warning go away you will be forced to add an extra div tag as the parent element to your JSX markup.

class ParentC extends React.Component {
    render() {
        return (
            <div>
                <ChildComponent />
                <ChildComponent />
            </div>
        )
    }
}class ChildComponent extends React.Component {
    render() {
        return (
            <div>
                <h1>Hello Child Component</h1>
                <h1>Hello Child Component</h1>
            </div>
        )
    }
}

The problem here is that the div tags is a bit awkward. There are cases in HTML where an extra div might destructure the DOM. For instance, when using a table in your components.

We want to render users details in tabular form using table element in HTML. We want to render the below code in React:

<table>
    <tr>
        <th>Name</th>
        <th>Occupation</th>
        <th>Age</th>
    </tr>
    <tr>
        <td>Chidume Nnamdi</td>
        <td>Software Dev</td>
        <td>27</td>
    </tr>
    <tr>
        <td>Row Ekemezie</td>
        <td>Software Dev</td>
        <td>? :)</td>
    </tr>
</table>

We would create components to render each facet of the table element. A HeaderComponent would render the table head. and a BodyComponent would render the body of the table. TableComponent would render the table skeleton with the HeaderComponent and BodyComponent like this:

class TableComponent extends React.Component {
    render() {
        return (
            <table>
                <tr>
                    <HeaderComponent />
                </tr>
                <tr>
                    <BodyComponent />
                </tr>
            </table>
        )
    }
}

Our HeaderComponent should look like his:

class HeaderComponent extends React.Component {
    render() {
        return (
            <th>Name</th>
            <th>Occupation</th>
            <th>Age</th>            
        )
    }
}

And BodyComponent would look like this:

class BodyComponent extends React.Component {
    render() {
        return (
            <td>Chidume Nnamdi</td>
            <td>Software Dev</td>
            <td>27</td>
        )
    }
}

The problem with HeaderComponent and BodyComponent is that they return multiple nodes. React would warn to enclose their markup in an enclosing tag.

So we would try to do something like this to remove the warning:

class HeaderComponent extends React.Component {
    render() {
        return (
            <div>
                <th>Name</th>
                <th>Occupation</th>
                <th>Age</th>                        
            </div>
        )
    }
}
class BodyComponent extends React.Component {
    render() {
        return (
            <div>
                <td>Chidume Nnamdi</td>
                <td>Software Dev</td>
                <td>27</td>            
            </div>
        )
    }
}

We enclosed the markup in a div tag. The output of the Table component would now be this:

<table>
    <tr>
        <div>
            <th>Name</th>
            <th>Occupation</th>
            <th>Age</th>
        </div>
    </tr>
    <tr>
        <div>
            <td>Chidume Nnamdi</td>
            <td>Software Dev</td>
            <td>27</td>
        </div>
    </tr>
</table>

The above is the wrong output of the table element. The div element shouldn’t be present. React components are meant to return elements but they must be enclosed in a parent tag, multiple elements cannot be returned. But adding extra node sometimes results in the wrong formatting of our html output as we saw above.

How do we solve this problem? How do we return enclosed JSX elements without affecting the rendered output on the DOM?

React provided a solution to it in the form of Fragments.

Solution — Fragments

Fragments lets you group a list of children without adding extra nodes to the DOM — Reactjs Blog

Using <React.Fragment>...</React.Fragment>, we can add a parent tag to our JSx elements without adding an extra node to the DOM. React.Fragment outputs no HTMLElement.

Let’s use React.Fragment to solve our first problem:

class ParentC extends React.Component {
    render() {
        return (
            <ChildC />
            <ChildC />
        )
    }
}class ChildC extends React.Component {
    render() {
        return (
            <h1>
                Child Component
            </h1>
        )
    }
}

Now, we will enclose:

return (
            <ChildC />
            <ChildC />
        )

in React.Fragment. It would now look like this:

class ParentC extends React.Component {
    render() {
        return (
            <React.Fragment>
                <ChildC />
                <ChildC />
            </React.Fragment>
        )
    }
}

Next, our second example:

class ParentC extends React.Component {
    render() {
        return (
            <div>
                <ChildComponent />
                <ChildComponent />
            </div>
        )
    }
}class ChildComponent extends React.Component {
    render() {
        return (
            <div>
                <h1>Hello Child Component</h1>
                <h1>Hello Child Component</h1>
            </div>
        )
    }
}

We would remove the div tags and add React.Fragment in their place:

class ParentC extends React.Component {
    render() {
        return (
            <React.Fragment>
                <ChildComponent />
                <ChildComponent />
            </React.Fragment>
        )
    }
}class ChildComponent extends React.Component {
    render() {
        return (
            <React.Fragment>
                <h1>Hello Child Component</h1>
                <h1>Hello Child Component</h1>
            </React.Fragment>
        )
    }
}

Then, in our third example, we replace the extra div tags in the BodyComponent and HeaderComponent with React.Fragment:

class HeaderComponent extends React.Component {
    render() {
        return (
            <div>
                <th>Name</th>
                <th>Occupation</th>
                <th>Age</th>                        
            </div>
        )
    }
}
class BodyComponent extends React.Component {
    render() {
        return (
            <div>
                <td>Chidume Nnamdi</td>
                <td>Software Dev</td>
                <td>27</td>            
            </div>
        )
    }
}    |
    |
    |
    vclass HeaderComponent extends React.Component {
    render() {
        return (
            <React.Fragment>
                <th>Name</th>
                <th>Occupation</th>
                <th>Age</th>                        
            </React.Fragment>
        )
    }
}
class BodyComponent extends React.Component {
    render() {
        return (
            <React.Fragment>
                <td>Chidume Nnamdi</td>
                <td>Software Dev</td>
                <td>27</td>            
            </React.Fragment>
        )
    }
}

The table would render like this:

<table>
    <tr>
        <th>Name</th>
        <th>Occupation</th>
        <th>Age</th>
    </tr>
    <tr>
        <td>Chidume Nnamdi</td>
        <td>Software Dev</td>
        <td>27</td>
    </tr>
</table>

As we want, with no extra div tags !!!

If writing React.Fragment every time is too long for you. React.Fragment has a shorthand syntax that you can use. It is <>...</>. So our BodyComponent and HeaderComponentcomponents:

class HeaderComponent extends React.Component {
    render() {
        return (
            <React.Fragment>
                <th>Name</th>
                <th>Occupation</th>
                <th>Age</th>                        
            </React.Fragment>
        )
    }
}
class BodyComponent extends React.Component {
    render() {
        return (
            <React.Fragment>
                <td>Chidume Nnamdi</td>
                <td>Software Dev</td>
                <td>27</td>            
            </React.Fragment>
        )
    }
}

can also be written like this:

class HeaderComponent extends React.Component {
    render() {
        return (
            <>
                <th>Name</th>
                <th>Occupation</th>
                <th>Age</th>                        
            </>
        )
    }
}
class BodyComponent extends React.Component {
    render() {
        return (
            <>
                <td>Chidume Nnamdi</td>
                <td>Software Dev</td>
                <td>27</td>            
            </>
        )
    }
}

Conclusion

In this post, we first saw a problem of not being able to return multiple elements and the solution to it using React.Fragment also we saw the shorthand syntax of React.Fragment and how to use it.

You see with React.Fragment, we enjoy the benefit of returning multiple elements without having to add extra tags or div tags that wrap our elements and clutter the DOM.

The React.js error “JSX expressions must have one parent element” occurs when you have a component that returns multiple rendered elements. JSX requires that all your expressions or adjacent jsx elements must be wrapped in an enclosing ‘<div>’ tag or a React fragment ‘<><p></p> <>’ so that it will be return as a single container. First, allow me to explain why this error occurs and how you can fix it?

JSX (JavaScript XML) is a JavaScript extension that makes it possible for developers to use HTML tags directly in JavaScript code. It helps to module the DOM elements that is required to be return from one component to another.

Why does JSX requires all expressions to be wrapped in an enclosing tag? The short answer is that each component needs to return a single value and not two or more. Example of how this error occurs when we return two parent elements…

export default function App() {
  // JSX expressions must have one parent element.
 // we have provided two 
  return (
    <h1>First heading</h1>
    <h2>Second heading</h2>
  );
}

The above JSX will be translated as…

function App() {
  return React.createElement("h1", null, "First heading")
  React.createElement("h2", null, "Second heading")
}

jsx expressions must have one parent-element in react

You can see from the JSX translation above that we’re returning two items which is not valid in Vanilla JavaScript and other object-oriented programming languages. You can only return a single item from a components/function and once the item is returned the function execution is terminated. When you want to return a multiple value from a function, you have to wrap it inside an array but not to return each separately (that’s the concept). If the above code was an expression and we’re passing an argument, it will be impossible for the other component to handle such parameters. What you need is to return a single parent element and include child elements in it.

Also, note that when you return an expression directly as shown in below, react will throw an error.

export default function App(){
  return(
    {'Hello world'}
  );
}

How do you solve the above ReactJS error? There’re two ways to fix it, wrap and return all element in a single React-fragment, DIV or another HTML tag.

Below is how you can fix the error “jsx expressions must have one parent element” using the concise syntax of React-fragment.

export default function App() {
  return (
    // wrap all element in react fragment
    <>
    <h1>First heading</h1>
    <h2>Second heading</h2>
    </>
  );
}

The two elements above have all been group in a fragment ‘<> </>’ here, the fragment represent a container with the two elements as it children’s. The main concept here is to make sure that you’re not adding any extra nodes to the DOM. If you do, there will be two or more values needed to be return from the function and that will cause the above error to occur.

If you want, you may also use the verbose syntax of fragments by using “React” and its inner class ‘Fragment” like how an HTML tag is used.

export default function App() {
  return (
    // wrap all element in react fragment
    <React.Fragment>
    <h1>First heading</h1>
    <h2>Second heading</h2>
    </React.Fragment>
  );
}

None, of the above approach is wrong, they all achieve the same result. However, the concise syntax is the most used one it supported by most code editors with VS-CODE (visual studio code) included.  All the elements grouped in the fragment are its children’s and the inner elements can also contain sub-tags.

Also, make sure not to be tempted to return two fragments separately as shown below…

export default function App() {
  return (
    // wrap all element in react fragment
    <>
    <h1>First heading</h1>
    <h2>Second heading</h2>
    </>

  // Wrong
    <>
    <h1>First heading</h1>
    <h2>Second heading</h2>
    </>
  );
}

Check also, how to disable button in angular on condition?

The next solution is to group your child elements in a <div> or another DOM element e.g. a ‘h1’.

export default function App() {
  return (
    <div>
      <h2>JSX CODE</h2>
      <h2>JSX BRACES</h2>
    </div>
  );
}

We now have a 2 <h2> child elements grouped in a <div> parent container. This will solve the error because the component returns a single parent container that contains multiple children. If adding a ‘div’ or other element will break your application layout, then safely use fragment because it does not add extra markup to the DOM.

When working with conditions in JSX, you will be presented with an expression error if you return multiple elements in one of the code paths at the same level. For example, if the condition is true, and you return 3 elements without grouping it in a parent container.

export default function App() {
  return (
    <div>
      {/* JSX expressions must have one parent element.ts(2657) */}
      {true ? (
        <h2>ReactJS tutorials</h2>
        <h2>Typescript</h2>
        <h2>JavaScript</h2>
      ) : null}
    </div>
  );
}

We have used ternary operator in the above code but you can see that the truthy path (the code that comes before the ‘?’ operator) returns 3 elements at the same level which will lead to an error. A workaround is to group the elements in a fragment or a div depending on your layout.

export default function App() {
  return (
    <div>
      {true ? (
        <>
        <h2>ReactJS tutorials</h2>
        <h2>Typescript</h2>
        <h2>JavaScript</h2>
        </>
      ) : null}
    </div>
  );
} 

This will fix the error, the truthy code-path now returns a single element as it value. You have to note that React components are just functions that returns a value. And you cannot return multiple values in a function at the same time, doing so will cause the error “JSX expressions must have one parent element.”  You either have to wrap it in an object or an array. If you want to see an example of wrapping elements in an array, then below is how it works.

export default function App() {
  return [<h3 key={0}>Hello</h3>, <h3 key={1}>World</h3>];
}

This will solve the error because everything is returned as an array which is a single value and it represent the parent element. But can you spot the extra work we did? We have to pass a unique ‘key’ prop as an attribute to each child element. If you fail to do that React will throw the error “should have a unique key prop” This will be a lot of work if we have 1000 elements to render. Fragment is more intuitive and readable, why not use it to make your life easy instead of the above unnecessary key array syntax?

export default function App() {
  return (
    <>
      <h2>Hello</h2>
      <h2>World</h2>
    </>
  );
}

Check also, How long it takes to learn JavaScript or ReactJS to get a job?

Question, ‘<div>’ and react fragment ‘<> </>’ which one should you use to solve the above error – JSX expressions must have one parent element?

One main significant of using fragment to solve the above error comes when we need not to wrap some elements in a container due to our application requirement. Ask yourself, what would you do if one of your components requires different element instead of an element grouped in a single container? For example, if component B renders <UL> or <OL> and it needs component A to render list of <li> and return to it. What will you do? You have to group the list of <li> tags in a <div> or return different list of <li> right? Wrong, that will be syntactically invalid because that’s not what the receiving component requires and if you return list of <li> it will throw the above error. Take a look at below react-code…

export default function App(){

  const ReturnManyLI = () => {
  // this will throw JSX expression error
    return(
      <li>Java programing language</li>
      <li>C++</li>
      <li>C#</li>
    )
  }

  return(
    <div>
      <ul>
        <li>JavaScript</li>
        < ReturnManyLI />
      </ul>
    </div>
  );
}

The above ‘ReturnManyLI’ component will throw an error when you run the application. Because we’re returning different elements without it being enclosed in a parent element. Also, within the last return expression above, the rendering of the ‘ReturnManyLI’ will not work even if the above error is overridden and the application successfully execute. Why because there won’t be any element returned, so definitely it will throw a second error. What if we wrap all the <li> in parent <div> tag? The above error will not be thrown but we will get syntactical invalid error, because <div> tags should not be used as a child element of <UL> or <OL>.

The solution to the above problem is to use <React.Fragment> or ‘<> </>’ component. If you want to enclose list of elements without rendering the parent container on the DOM, then fragment is what you need. So, let me show you how you can use it to solve above example…

export default function App(){

  const ReturnManyLI = () => {
    return(
      <React.Fragment> // or simply use <>
      <li>Java programing language</li>
      <li>C++</li>
      <li>C#</li>
      </React.Fragment> // or </>
    )
  }

  return(
    <div>
      <ul>	
        <li>JavaScript</li>
        < ReturnManyLI />
      </ul>
    </div>
  );
}

Does JSX need to be in parentheses? Yes, when working with conditions using ternary operators, it better to wrap all your parent container in a parenthesis. This makes your code clean and easy to debug doing code review.

export default function App() {
  return (
    <div>
      {true ? (
        <>
        <h2>first true tag</h2>
        <h2>second true tag</h2>
        </>
      ) : 
      (
     <h2>false tag</h2>
      )
    }
    </div>
  );
} 

Tagged jsx expressions must have one parent element Ezoic

Понравилась статья? Поделить с друзьями:
  • Just error dota 2 игрок
  • Just error 404 dota 2
  • Jsonconvert deserializeobject error
  • Json validation error list
  • Json rpc коды ошибок