


One of the few attributes/props that a React.Fragment will support is the key prop. Once again there is an exception to this which is when it comes to React keys.Ī React Key is just a way that React can track components in lists across renders to prevent strange behavior ( read more about keys here). Where a React.Fragment does not get rendered into the DOM it can’t support these things and you will therefore have to make use of an actual html element such as a div. There might be many edge cases to this but some of the main situations that this might occur is when you need to apply styling, add event handlers or add attributes to the root element. When to use a div over a React.FragmentĪs mentioned in the above section, sometimes you can’t always use a react fragment in place of a div because there might be certain things you need the wrapping element to have.Īnd these are the times when you will want to make use of a div (or any other relevant html element) over a React.Fragment. The problem is, it is not always possible to use a React.Fragment in place of a div element because there might be certain things that you will need the wrapping element to have which we will get into in the next section.īut for the most part if you just need to group some components or elements together in a React application then React.Fragment is almost always the better choice to reduce the overall DOM size. When to use a React.Fragment over a divįor the most part it is safe to assume that you will always want to use a React.Fragment over a div wherever possible in order to keep the size of the DOM down. Whilst this is only a small difference here, when looked at across an entire React application it can make a big difference. As you can see by using the fragment we have been able to remove the additional div element from our DOM tree.
