zishu's blog

zishu's blog

一个热爱生活的博主。https://zishu.me

Placeholder Fragment in React

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 layer of div wrapping them. If we have nested components in our project, each layer will have an additional parent element div, which is not aesthetically pleasing and can be troublesome 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, world</h2>
            </Fragment>
        )
    }
}

When importing React, add the attribute Fragment, and then use <Fragment> </Fragment> as the only root element in the render() method. Now, when you look at the browser, there will be no extra tags displayed, only the <h2> tag.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.