Skip to content

Instantly share code, notes, and snippets.

@Liooo
Created December 13, 2017 06:27
Show Gist options
  • Save Liooo/3bd6c79d5b4bdcded9927bbdd9133af0 to your computer and use it in GitHub Desktop.
Save Liooo/3bd6c79d5b4bdcded9927bbdd9133af0 to your computer and use it in GitHub Desktop.
[react-select-plus] Rendering option dropdown as a direct child of body using react-portal
// https://github.com/HubSpot/react-select-plus
// rough sample code for rendering dropdown menu outside the Select DOM
import {Component} from 'react';
import {createPortal, findDOMNode} from 'react-dom';
import Select from 'react-select-plus';
class Selector extends Component {
constructor(props){
super(props);
this.state = {
value: 1,
options: [{label: 'hey', value: 1}, {label: 'yo', value: 2}]
};
}
componentDidMount(){
this.setState({elem: findDOMNode(this.selector)});
}
buildPortalToBody() {
return (props) => {
if(!this.state.elem) return props.children;
const rect = this.state.elem.getBoundingClientRect();
const style = {
position: 'absolute',
top: rect.top + rect.height,
left: rect.left,
width: rect.width,
zIndex: 9999999 // you might not need this
};
return createPortal(
<div style={style}>{props.children}</div>,
document.getElementsByTagName('body')[0]
);
}
}
render() {
return (
<Select
ref={(r) => this.selector = r}
value={this.state.value}
options={this.state.options}
dropdownComponent={this.buildPortalToBody()}
/>
);
}
}
@jeffmcaffer
Copy link

Nice, this helped me put a Select in a row of a react-virtualized list. Care to put a license (say MIT) on this?

There is an issue if you resize the window while the dropdown is down. the position is not recalculated so the dropdown gets orphaned in space. Thoughts on how to address that?

BTW, I did not need the zIndex.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment