Skip to content

Commit

Permalink
lesson 04: using portal to render components outside
Browse files Browse the repository at this point in the history
  • Loading branch information
wangshijun committed Oct 8, 2017
1 parent a90b9f2 commit 32ff1a0
Show file tree
Hide file tree
Showing 4 changed files with 81 additions and 1 deletion.
4 changes: 4 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ module.exports = {
'no-mixed-operators': 'off',
'no-use-before-define': 'off',
'no-unused-expressions': 'off',
'jsx-a11y/no-static-element-interactions': 'off',
'jsx-a11y/click-events-have-key-events': 'off',
'max-len': ['warn', 120],
'no-param-reassign': ['error', { props: false }],
camelcase: 'off',
Expand All @@ -46,5 +48,7 @@ module.exports = {
tracker: true,
constants: true,
navigator: true,
document: true,
window: true,
},
};
50 changes: 50 additions & 0 deletions src/ReactPortals.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class Overlay extends Component {
constructor(props) {
super(props);

this.container = document.createElement('div');
document.body.appendChild(this.container);
}

componentWillUnmount() {
document.body.removeChild(this.container);
}

render() {
return ReactDOM.createPortal(
<div className="overlay">
<span className="overlay__close" onClick={this.props.onClose}>
&times;
</span>
{this.props.children}
</div>,
this.container
);
}
}

class App extends Component {
constructor(props) {
super(props);

this.state = { overlayActive: true };
}

closeOverlay() {
this.setState({ overlayActive: false });
}

render() {
return (
<div>
<h2>Dashboard</h2>
{this.state.overlayActive && <Overlay onClose={this.closeOverlay.bind(this)}>overlay content</Overlay>}
</div>
);
}
}

export default App;
26 changes: 26 additions & 0 deletions src/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,29 @@ button {
font-size: 24px;
line-height: 1.5em;
}

.overlay {
box-sizing: border-box;
position: fixed;
top: 50%;
left: 50%;
width: 260px;
height: 200px;
margin-left: -130px;
margin-top: -100px;
padding: 10px;
background-color: #fff;
outline: 9999px solid rgba(0, 0, 0, 0.5);
}

.overlay__close {
position: absolute;
top: 10px;
right: 10px;
color: red;
cursor: pointer;
}

.overlay div {
display: inline;
}
2 changes: 1 addition & 1 deletion src/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './TextOnlyComponent';
import App from './ReactPortals';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<App />, document.getElementById('root'));
Expand Down

0 comments on commit 32ff1a0

Please sign in to comment.