Pulasthi Aberathne
Pulasthi Aberathne

Reputation: 428

Adjacent JSX elements must be wrapped in an enclosing tag - JSX tag already wrapped but keep omitting the error

import React, { useState } from 'react';
import ReactDOM from 'react-dom';

function DataList(props) {

  //creating the ListItem
const dataList = data.map(data => (
  <><span>{data.name}</span>nbsp;<span>{data.age}</span></>
))
const data = [
  { name: 'Daniel', age: 25 },
  { name: 'John', age: 24 },
  { name: 'Jen', age: 31 },
];

  return (
    <h2><span>Name</span>nbsp;<span>Age</span></h2>
    <div>{dataList}</div>
  );
}


ReactDOM.render(
  <DataList data={ data } />,
  document.getElementById('root')
);

This keeps omitting

Adjacent JSX elements must be wrapped in an enclosing tag (7:4)

I wrapped everything but can't figure out the issue

Upvotes: 0

Views: 1090

Answers (3)

jam j
jam j

Reputation: 576

Simply I am using div tag, here is the code example for above problem-

 return (
    <div>
         <h2><span>Name</span>nbsp;<span>Age</span></h2>
         <div>{dataList}</div>
    </div>
 );

Upvotes: -1

DecPK
DecPK

Reputation: 25406

1) You need to wrap your returning JSX into a single parent component, You can also use Fragments here as

CODESANDBOX

<>
  <h2>
    <span>Name</span>
    nbsp;
    <span>Age</span>
  </h2>
  <div>{dataList}</div>
</>

2) Since you are using const to declare data then, you should declare it at the starting of the function.

variables declared using let and const cannot be accessed before they are declared.

  const data = [
    { name: "Daniel", age: 25 },
    { name: "John", age: 24 },
    { name: "Jen", age: 31 }
  ];

  //creating the ListItem
  const dataList = data.map((d) => (
    <>
      <span>{d.name}</span>
      <span>{d.age}</span>
    </>
  ));

Upvotes: 1

Mert
Mert

Reputation: 142

I don't recommend @decpk that answer like to using empty <> tag. You should use <Fragment> tag. This way increase readability.

Upvotes: 1

Related Questions