/

Using React Portals for Better Component Rendering

Using React Portals for Better Component Rendering

Discover how React Portals can improve your component rendering process.

React 16 introduced a powerful feature called Portals. With Portals, you can render an element outside of its component hierarchy, in a separate component. This means that even though the element is rendered elsewhere in the DOM tree, it is still managed by the React component hierarchy.

To use React Portals, you can make use of the ReactDOM.createPortal() API, which takes two arguments: the element to render and the DOM element where it should be rendered.

One common use case for React Portals is modal windows. Modals often need to be rendered outside of their parent component so they can be styled properly using CSS. By creating a Modal component and using ReactDOM.createPortal(), you can render the modal in a separate DOM tree while still having its events handled by the parent component.

Here’s an example of how you can implement a Modal component and render it using React Portals:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class Modal extends React.Component {
constructor(props) {
super(props);
this.el = document.createElement('div');
}

componentDidMount() {
document.getElementById('modal').appendChild(this.el);
}

componentWillUnmount() {
document.getElementById('modal').removeChild(this.el);
}

render() {
return ReactDOM.createPortal(
this.props.children,
this.el
);
}
}

class App extends React.Component {
constructor(props) {
super(props);
this.state = { showModal: false };

this.handleShow = this.handleShow.bind(this);
this.handleHide = this.handleHide.bind(this);
}

handleShow() {
this.setState({ showModal: true });
}

handleHide() {
this.setState({ showModal: false });
}

render() {
const modal = this.state.showModal ? (
<Modal>
<div>
The modal <button onClick={this.handleHide}>Hide</button>
</div>
</Modal>
) : '';

return (
<div>
The app <button onClick={this.handleShow}>Show modal</button>
{modal}
</div>
);
}
}

ReactDOM.render(<App />, document.getElementById('app'));

You can check out the full example on CodePen.

By utilizing React Portals, you can achieve cleaner component hierarchy management and better control over rendering elements outside of their natural position in the DOM. Give it a try and see how it can enhance your React applications.

tags: [“React”, “React Portals”, “Component Rendering”, “DOM Management”]