Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.js Error "Adjacent JSX elements must be wrapped in an enclosing tag"

I have the below code is react.js which is throwing an error

"Adjacent JSX elements must be wrapped in an enclosing tag". It looks like React isnt accepting same tags next to each other how do I display tabular data?

var TestRecords = React.createClass({    
  render: function() {
      return(
        <table>
          <tr>
            {this.props.records.map(record=>{
              return <td>{record.title}</td><td>record.id</td>
            }
          )}
        </tr>
      </table>
    );    
  }  
});
like image 484
Jay Avatar asked May 01 '16 05:05

Jay


2 Answers

With React, you may only provide two things to a component tree - a node (element) or a collection of nodes.

Here you're providing two nodes (two tds). You need to either wrap them in a tr, or return them as an array (with key attributes). Also less ideal in this example since it appears that your generator should probably include tr in the first place.

Try

return (
  <table>
    {this.props.records.map(record => ( // implicit return
      <tr key={record.id}>
        <td>{record.title}</td>
        <td>{record.id}</td>
      </tr>
    )}
  </table>
)
like image 106
Atticus Avatar answered Sep 30 '22 04:09

Atticus


Can you try as below,

var TestRecords = React.createClass({    
  render: function() {
      return(
        <table>
          <tr>
            {this.props.records.map(record=>{
              return 
              <tr>
                <td>{record.title}</td>
                <td>record.id</td>
              </tr>
            }
          )}
        </tr>
      </table>
    );    
  }  
});

Error is because the map is trying to return two td elements. Which could be the reason for the error

like image 28
anoop Avatar answered Sep 30 '22 04:09

anoop