Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid extra wrapping <div> in React?

This requirement was removed in React version (16.0)]1, so now you are able to avoid that wrapper.

You can use React.Fragment to render a list of elements without creating a parent node, official example:

render() {
  return (
    <React.Fragment>
      <ChildA />
      <ChildB />
      <ChildC />
    </React.Fragment>
  );
}

More here: Fragments


Update 2017-12-05: React v16.2.0 now fully supports rendering of fragments with improved support for returning multiple children from a components render method without specifying keys in children:

render() {
  return (
    <>
      <ChildA />
      <ChildB />
      <ChildC />
    </>
  );
}

If you are using a React version prior to v16.2.0, it is also possible to use <React.Fragment>...</React.Fragment> instead:

render() {
  return (
    <React.Fragment>
      <ChildA />
      <ChildB />
      <ChildC />
    </React.Fragment>
  );
}

Original:

React v16.0 introduced returning an array of elements in render method without wrapping it in a div: https://reactjs.org/blog/2017/09/26/react-v16.0.html

render() {
  // No need to wrap list items in an extra element!
  return [
    // Don't forget the keys :)
    <li key="A">First item</li>,
    <li key="B">Second item</li>,
    <li key="C">Third item</li>,
  ];
}

At the moment, a key is required for each element to avoid the key warning but this could be changed in future releases:

In the future, we’ll likely add a special fragment syntax to JSX that doesn’t require keys.


You can use:

render(){
    return (
        <React.Fragment>
           <div>Some data</div>
           <div>Som other data</div>
        </React.Fragment>
    )
}

For further details refer to this documentation.


Use [], instead of ()'s to wrap the entire return.

render: function() {
  return[
    <div className="DeadSimpleComponent__time">10:23:12</div >
    <div className="DeadSimpleComponent__date">MONDAY, 2 MARCH 2015</div>
  ]
}

I created a component to wrap child components without a DIV. It's called a shadow wrapper: https://www.npmjs.com/package/react-shadow-wrapper