2019年3月28日 星期四

React: Portal

Usage

A normal react component tree normally looks like this:

And due to this cluster pattern, the bottom UI components' styling got influenced by their parents components.

To solve this restriction, React portal helps us to achieve this: 
So we could have an independent root element to do the "document.querySelector" that we can build another component tree under it without been influenced by the main branch or component tree.

Tips:

  • stopPropagation: prevent the event to bubble up to parent elements

1
2
3
4
5
6
7
<div onClick={props.onDismiss} className="ui dimmer modals visible active">
      <div onClick={e => e.stopPropagation()} className="ui standard modal visible active">
        <div className="header">{props.title}</div>
        <div className="content">{props.content}</div>
        <div className="actions">{props.actions}</div>
      </div>
</div>

  • React.Fragment: Blank HoC to wrap elements without side effect on styling 

1
2
3
4
<React.Fragment>
        <button className="ui button negative">Delete</button>
        <button className="ui button">Cancel</button>
</React.Fragment>

<...>

沒有留言:

張貼留言

Git: How to clone only part of the repo (specific directory)

 https://stackoverflow.com/a/60729017/5721873