In React projects, the render method can only have one root element, usually <div> <div/>
, and then we write our components inside it. When rendered in the browser, in addition to the components we want to display, there is also an extra div wrapping them. If we nest many components in the project, each layer will have an additional parent element div, which is not aesthetically pleasing and can be cumbersome when adjusting styles.
Therefore, React provides a placeholder Fragment, which is written as:
// index.js
import React, { Component,Fragment } from 'react'
export default class index extends Component {
render() {
return (
<Fragment>
<h2>hello,wolrd</h2>
</Fragment>
)
}
}
When importing React, add the attribute Fragment, and then use <Fragment> </Fragment>
to replace the only root element under the render()
method. Now, when you look at the browser, there will be no extra tags displayed, only the <h2>
tag will be shown.