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:
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.