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' ?
You can use React.Fragment
<React.Fragment>
"Rest of elements here"
</React.Fragment>
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 eg 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 />
]
);
}
We can use empty <>
tag as well
<>
Rest of markup here
</>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.