Avoiding unnecessary tags using fragments

Let's take a look at the WithFragments component now:

import React, { Component, Fragment } from 'react';

class WithFragments extends Component {
render() {
return (
<Fragment>
<h1>With Fragments</h1>
<p>Doesn't have any unused DOM elements.</p>
</Fragment>
);
}
}

export default WithFragments;

Instead of wrapping the component content in a <div>, the <Fragment> element is used. This is a special type of element that indicates that only its children need to be rendered. You can see the difference compared to the WithoutFragments component if you inspect the DOM:

Notice how you had to import Fragment from React in the previous example? This is because not all transpilers such as Babel understand the Fragment element yet. In future versions, there will actually be a shorthand way to express fragments in JSX: <>My Content</>. But for now, React.Fragment should work with all React tooling.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.142.115