How to avoid extra wrapping
in React?

前端 未结 10 851
孤独总比滥情好
孤独总比滥情好 2020-12-02 12:04

Today I have started learning ReactJS and after an hour faced with the problem.. I want to insert a component which has two rows inside a div on the page.A simplified exampl

相关标签:
10条回答
  • 2020-12-02 12:20

    There is workaround too. The below block code generates fragment without the need of React.Fragment.

    return [1,2,3].map(i=>{
    if(i===1) return <div key={i}>First item</div>
    if(i===2) return <div key={i}>Second item</div>
    return <div key={i}>Third item</div>
    })
    
    0 讨论(0)
  • 2020-12-02 12:22

    This requirement was removed in React version (16.0)]1, so now you are able to avoid that wrapper.

    You can use React.Fragment to render a list of elements without creating a parent node, official example:

    render() {
      return (
        <React.Fragment>
          <ChildA />
          <ChildB />
          <ChildC />
        </React.Fragment>
      );
    }
    

    More here: Fragments

    0 讨论(0)
  • 2020-12-02 12:26

    This is still required, BUT React now make sure to create elements without creating an additional DOM element.

    The extra wrapping needed (normally with a parent div) because Reacts createElement method require a type parameter which is either a tag name string (such as 'div' or 'span'), a React component type (a class or a function). But this was before they introduce React Fragment.

    Refer this NEW api doc for createElement

    React.createElement : Create and return a new React element of the given type. The type argument can be either a tag name string (such as 'div' or 'span'), a React component type (a class or a function), or a React fragment type.

    here is the official example, Refer React.Fragment.

    render() {
      return (
        <React.Fragment>
          Some text.
          <h2>A heading</h2>
        </React.Fragment>
      );
    }
    
    0 讨论(0)
  • 2020-12-02 12:31

    You won't be able to get rid of that div element. React.render() needs to return one valid DOM node.

    0 讨论(0)
提交回复
热议问题