Reputation: 2454
Instead of having a div element, I want an element like 'ng-container' in Angular to avoid useless div elements in the DOM.
What is the React equivalent of Angulars 'ng-container' ?
Upvotes: 14
Views: 5809
Reputation: 1535
Fragments let you group a list of children without adding extra nodes to the DOM.
function ChildA() {
return (
<h5>Child A</h5>
);
}
function ChildB() {
return (
<h5>Child B</h5>
);
}
function ChildC() {
return (
<h5>Child C</h5>
);
}
Method-1: React Fragments helps to add empty container to wrap list of children inside render method.
render() {
return (
<React.Fragment>
<ChildA />
<ChildB />
<ChildC />
</React.Fragment>
);
}
Method-2 A common pattern is for a component to return a list of children by wrapping children with any container element e.g div,p
render() {
return (
<div>
<ChildA />
<ChildB />
<ChildC />
</div>
);
}
Method-3 There is a new, shorter syntax you can use for declaring fragments.You can use <> the same way you’d use any other element except that it doesn’t support keys or attributes.
render() {
return (
<>
<ChildA />
<ChildB />
<ChildC />
</>
);
}
Method-4 React 16.0 added support for returning an array of elements from a component’s render method. Instead of wrapping the children in a DOM element, you can put them into an array:
function App() {
return (
[
<ChildA />,
<ChildB />,
<ChildC />
]
);
}
Upvotes: 6
Reputation: 406
You can use React.Fragment
<React.Fragment>
"Rest of elements here"
</React.Fragment>
Upvotes: 25