0

I want to use two tr tags in a return as below:

render() {
  return<tr>row1</tr><tr>row2</tr>
}

and it gives me error: Adjacent JSX elements must be wrapped in an enclosing tag.

I know that we need to wrap these in a common component. But if I wrap there in a div tag for example:

return <div><tr>row1</tr><tr>row2</tr></div>

then my layout changes.

Is there any way to achieve the required.

Chris
  • 57,622
  • 19
  • 111
  • 137
aman
  • 36
  • 7

1 Answers1

1

If you really want to render two rows without parent wrapping them (like a td, table or so), I suggest you to create a second component which "wraps" its children accordingly. However, this works only from React16 onwards.

const Main = props => {
 return props.children
}

in your render method:

render() {
  return (
    <Main> 
      <tr>Row 1</tr>
      <tr>Row 2</tr>
    </Main>
  )
}

There's also a npm package which handles that if you want: https://github.com/gajus/react-aux

Hemerson Carlin
  • 7,354
  • 1
  • 27
  • 38
  • I seriously doubt this works. The `Main` component is still a React component and in your code example you are returning `children`, which is an array with two React Components. Arrays are not a valid React element (unless React v16 which is still in RC). That said, if I'm missing something and you can demo this with a working example I'll happily change my downvote into an upvote. – Chris Sep 12 '17 at 11:34
  • You are correct to say that `Main` is a react compoent. However it's not a DOM element (which is what you want to achieve). You can also check `react-aux` repo and read its docs. It says exactly what I just answered :) – Hemerson Carlin Sep 12 '17 at 11:38
  • Well, here's my test: https://jsfiddle.net/f4x8knuy/ and if you look at the console it complains about invalid React element being returned. – Chris Sep 12 '17 at 11:42
  • @Chris You are correct. This is a mistake. It works for React 16 only :) – Hemerson Carlin Sep 12 '17 at 11:53