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

I’m relatively new to React and I’m wondering what’s the standard here.

Imagine I have a react-router like this one:

<Router history={history}>
    <Route path="/" component={App}>
      <Route path="home component={Home} />
      <Route path="about" component={About} />
      <Route path="inbox" component={Inbox} />
      <Route path="contacts" component={Contacts} />
    </Route>
</Router>

And now I want to remove two routes if prop.mail is set to false, so a sane way of doing that would look like this:

<Router history={history}>
      <Route path="/" component={App}>
        <Route path="home component={Home} />
        <Route path="about" component={About} />

        { if.this.props.mail ? 
          <Route path="inbox" component={Inbox} />
          <Route path="contacts" component={Contacts} />
        : null }

      </Route>
 </Router>

But there are 2 routes and React returns error:

expressions must have one parent element.

I don’t want to use multiple ifs here. What’s the preferred React way of handling this?

Liam's user avatar

Liam

27.2k28 gold badges124 silver badges187 bronze badges

asked Feb 20, 2018 at 13:45

Wordpressor's user avatar

WordPressorWordPressor

7,06923 gold badges67 silver badges106 bronze badges

0

Put them in an array (assign the keys also):

{ if.this.props.mail ? 
    [
        <Route key={0} path="inbox" component={Inbox} />,
        <Route key={1} path="contacts" component={Contacts} />
    ]
: null }

With latest React version, you can try React.Fragment also, like this:

{ if.this.props.mail ? 
    <React.Fragment>
        <Route path="inbox" component={Inbox} />,
        <Route path="contacts" component={Contacts} />
    </React.Fragment>
: null }

Ronan Boiteau's user avatar

answered Feb 20, 2018 at 13:50

Mayank Shukla's user avatar

Mayank ShuklaMayank Shukla

99.6k18 gold badges157 silver badges142 bronze badges

7

You can leverage short hand fragments to return a list of children along with Logical ‘&&’ Operator for conditional rendering. Nice and clean! 😄

{this.props.mail && 
  <>
    <Route path="inbox" component={Inbox} />,
    <Route path="contacts" component={Contacts} />
  </>
}

answered Oct 29, 2019 at 14:09

Eoin Traynor's user avatar

1

You must been use a fragment tag e.g(div, <>,…).

Check this short solution:

{ if.this.props.mail ? 
 <>
   <Route path="inbox" component={Inbox} />
   <Route path="contacts" component={Contacts} />
 </>
 : null }

answered Jan 26, 2020 at 3:25

Alexandre Soria's user avatar

1

just try enclosing the code after the return statement in an element like <div>....code </div>,etc.

eg:-

const Div =()=>{
           return
            <div>
              <Button name="Save" ></Button>
              <Button name="Edit"></Button>
              <Button name="Cancel"></Button>  
            </div>}

answered Feb 2, 2020 at 23:56

Ritwik's user avatar

RitwikRitwik

711 silver badge3 bronze badges

0

2020 update

I have checked out every solution from answers. Here is the breakdown for regular React:

1. React Fragment

When i wanted to use it once, without adding additional DOM node — it worked. When i tried to use second React.Fragment got really bad errors. Wasn’t able to fix it.

2. View

I was unable to import View properly. I don’t know if this is only for Reactjs, or Native, but this does not work

3. Div

What actually worked was to put HTML into Div

answered Aug 24, 2020 at 10:33

Tom Smykowski's user avatar

Tom SmykowskiTom Smykowski

25.4k52 gold badges159 silver badges234 bronze badges

Faced the same error in a similar situation (React Native).

export default class App extends React.Component {
  render() {
    return (
      <StatusBar barStyle="default" />
      <AppContainer />
    );
  }
}

As indicated in the error prompt the JSX expression requires to have one parent element, hence wrap the elements in the return expression with a parent element. The flex: 1 style was added to allow the <View> element assume the height of the entire screen.

export default class App extends React.Component {
  render() {
    return (
      <View style={{flex: 1}}>
        <StatusBar barStyle="default" />
        <AppContainer />
      </View>
    );
  }
}

answered Feb 12, 2019 at 10:42

Jens Gerntholtz's user avatar

2

This one works for me.

<React.Fragment>
……..
</React.Fragment>

answered Nov 6, 2020 at 16:11

BMA88's user avatar

BMA88BMA88

3292 silver badges2 bronze badges

If you’re using <Switch>, then using <div> and <React.Fragment> to wrap your routes will break it.

I like the idea of a <ProtectedRoute> component:

import { Component } from 'react';
import { Redirect, Route } from 'react-router-dom';

class ProtectedRoute extends Component<any> {
  render() {
    const { component: Component, allow, ...props } = this.props;
    if (!allow) {
      return <Redirect to={{ pathname: '/signin' }} />;
    }
    return <Route {...props} render={(props) => <Component {...props} />} />;
  }
}

export default ProtectedRoute;

Then use it like below:

<Router history={history}>
  <Route path="/" component={App}>
    <Route path="home" component={Home} />
    <Route path="about" component={About} />

    <ProtectedRoute path="inbox" component={Inbox} allow={this.props.mail} />
    <ProtectedRoute path="contacts" component={Contacts} allow={this.props.mail} />

  </Route>
</Router>

answered May 19, 2021 at 15:36

Alisson Reinaldo Silva's user avatar

I am trying to toggle a Modal in react native. Each item in a flatlist should have a toggle option to open a modal.

I get the error:
JSX expressions must have one parent element.

I have tried to google for the right syntax but can’t find a solution.

class CategoriesScreen extends Component {

  state = {
    modalVisible: false,
  };

  setModalVisible(visible) {
    this.setState({ modalVisible: visible });
  }

  render() {
function Item({ title }) {
      return (
        <TouchableOpacity style={styles.item} onPress={() => {
          this.setModalVisible(true);
        }}>
          <View>
            <Text style={styles.title}>{title}</Text>
          </View>
        </TouchableOpacity> 
        <Modal
          animationType="slide"
          transparent={false}
          visible={this.state.modalVisible}
          onRequestClose={() => {
            Alert.alert('Modal has been closed.');
          }}>
          <View style={{ marginTop: 22 }}>
            <View>
              <Text>Hello World!</Text>

              <TouchableOpacity
                onPress={() => {
                  this.setModalVisible(!this.state.modalVisible);
                }}>
                <Text>Hide Modal</Text>
              </TouchableOpacity>
            </View>
          </View>
        </Modal>
    };
    return (
      <SafeAreaView style={styles.container}>
        <Text style={styles.heading}>Select a category for daily tasks.</Text>
        <Text style={styles.subheading}>{`You will receive a daily task in this category.nLet’s get consistent!`}</Text>
        <FlatList
          data={DATA}
          renderItem={({ item }) => <Item title={item.title} />}
          keyExtractor={item => item.id}
          numColumns={2}
        />
      </SafeAreaView>
    );
  }
}

I am trying to get open one unique modal for each item in the flatlist.

asked Oct 20, 2019 at 22:43

9minday's user avatar

1

You can only return a single entity. To fix this just surround your return in your Item function with a <Fragment/> element (from the react package).

Fragments let you group a list of children without adding extra nodes to the DOM.

This can be done like so:

import React, {Fragment} from 'react';
... 
function Item({ title }) {
    return (
      <Fragment>
        <TouchableOpacity style={styles.item} onPress={() => {
          this.setModalVisible(true);
        }}>
          <View>
            <Text style={styles.title}>{title}</Text>
          </View>
        </TouchableOpacity> 
        <Modal
          animationType="slide"
          transparent={false}
          visible={this.state.modalVisible}
          onRequestClose={() => {
            Alert.alert('Modal has been closed.');
          }}>
          <View style={{ marginTop: 22 }}>
            <View>
              <Text>Hello World!</Text>

              <TouchableOpacity
                onPress={() => {
                  this.setModalVisible(!this.state.modalVisible);
                }}>
                <Text>Hide Modal</Text>
              </TouchableOpacity>
            </View>
          </View>
        </Modal>
      </Fragment>
   )
};

Hope this helps,

answered Oct 20, 2019 at 22:51

Miroslav Glamuzina's user avatar

8

JSX, which stands for JavaScript XML, is a syntax extension for React that allows developers to write HTML-like code in their JavaScript files.

While working with JSX, beginners often encounter a common error that says, “JSX expressions must have one parent element”. This error occurs when multiple elements are returned in a single expression without being wrapped in a parent element.

This error is also very similar to the “Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>…</>?” error.

In this article, you will learn the different solutions that you can use to avoid this common roadblock when working with React.

What Causes the “JSX expressions must have one parent element” Error?

In JSX, there is a rule that states that it must always return a single element. This rule applies to React, which means that every component can only return a single root element.

This is because when you render a component, React creates a virtual DOM tree corresponding to the HTML that is ultimately rendered to the page. If there are multiple root elements in the JSX, React doesn’t know how to handle them, which results in the “JSX expressions must have one parent element” error or “Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>…</>?”

For example, if you try to render the following JSX code:

function App() {
    return (
        <h1>Hello, world!</h1>
        <p>This is a paragraph.</p>
    )
}

You’ll get the “JSX expressions must have one parent element” error:

JSX expressions must have one parent element error message

JSX expressions must have one parent element error

Or the “Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>…</>?” error:

Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>? error message

Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>…</>?

This is because two root elements (<h1> and <p> are returned.

JSX operates similarly to a function because functions cannot return multiple values (unless they are enclosed in an array, which is considered a single value).

function myFunc() {
  return value1;
  return value2;
}

The second return statement in the render function is unreachable because the first return statement will always execute, making it impossible for the second one to be executed.

New to React? Beware of this error! 🚧 Learn how to fix it here 👇Click to Tweet

3 Ways To Fix the “JSX expressions must have one parent element” Error

There are three major ways to fix this error, these methods are:

  • Using a Div Wrapper
  • Using a Fragment (<> and </>)
  • Using React.Fragment component

1. Wrap All Element With a Div Wrapper

One of the most straightforward solutions to the “JSX expressions must have one parent element” error is to wrap the multiple JSX elements in a single parent element, such as a <div>.

Doing this lets you group and render the elements as a single unit. For example, consider the component below:

function App() {
    return (
        <div>
            <h1>Hello, world!</h1>
           <p>This is a paragraph.</p>
        </div>
    )
}

In this example, the <h1> and <p> elements are wrapped in a <div> element, which serves as the parent element.

2. Wrap All Element With a Fragment

Another way to fix the “JSX expressions must have one parent element” or “Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>…</>?” error is to use a JSX Fragment.

A Fragment is a built-in feature of React that allows you to group a list of children without adding extra nodes to the DOM. You can use a Fragment to wrap the multiple elements in a single parent element without adding an extra DOM node to the rendered HTML. For example, here is a component:

function App() {
    return (
        <>
            <h1>Hello, world!</h1>
            <p>This is a paragraph.</p>
        </>
    )
}

In this example, a JSX Fragment (<> and </>) is used to wrap the multiple elements. This Fragment acts as a parent element.

3. Wrap All Element With React.Fragment

Finally, another way to fix the “JSX expressions must have one parent element” error is to use the React.Fragment component instead of a regular

element.

This works similarly to using a JSX Fragment, but it’s a bit more explicit and can be useful if you want to give your parent element a specific key or other props. For example, here is a component:

function App() {
    return (
        <React.Fragment>
            <h1>Hello, world!</h1>
            <p>This is a paragraph.</p>
       </React.Fragment>
    )
}

In this example, the React.Fragment component is used instead of a regular

element to serve as the parent element. It wraps multiple elements inside the tags, which allows you to group the elements together without adding an extra node to the rendered HTML.

The React.Fragment component will require you to import React. It also allows you to add props, and also className, style, and id to the fragment itself, which is useful when you want to apply styles or other attributes to the group of elements within the fragment.

How To Fix the “JSX expressions must have one parent element” Error in Conditionals

When working with conditional statements using the ternary operators in React, it’s common to encounter the error message “JSX expressions must have one parent element” or “Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>…</>?”.

This happens when multiple elements are returned from within a conditional statement. In that case, React won’t be able to render them correctly, and it will result in either of the errors.

function App() {
    return (
        <div>
            {condition ? (
                <h1>Heading 1</h1>
                <p>Paragraph 1</p>
                        ) : (
                <h2>Heading 2</h2>
                <p>Paragraph 2</p>
            )}
        </div>
    )
}

You can fix this error with any of the three methods explained in this article. Preferably you can use the React fragment (<> and </>) or <div> element.

function App() {
    return (
        <div>
            {condition ? (
                <>
                    <h1>Heading 1</h1>
                   <p>Paragraph 1</p>
                </>
            ) : (
                <>
                    <h2>Heading 2</h2>
                    <p>Paragraph 2</p>
                </>
            )
            }
        </div>
    )
}

Avoid this common error in React by wrapping multiple elements in a parent element. Here’s how to do it 💪Click to Tweet

Summary

The “JSX expressions must have one parent element” error or “Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>…</>?” is a common roadblock that beginners face when learning React.

Using a <div> wrapper is the easiest solution, but it can add unnecessary divs to the DOM. Fragments provide a cleaner solution without adding extra nodes to the DOM.

Now it’s your turn: Have you ever encountered this issue? How did you solve it? Are there any other approaches you used that are not covered in this article? Let us know in the comments!

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

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

Понравилась статья? Поделить с друзьями:

Не пропустите также:

  • Как найти прогнозируемую выручку
  • Как в гта онлайн найти сервер
  • Как найти на айпаде геолокацию
  • Как составить анкету для воспитателей
  • Как найти s20 в геометрической прогрессии

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии