diff --git a/src/index.js b/src/index.js index 71f111f05..561a06aa9 100644 --- a/src/index.js +++ b/src/index.js @@ -271,6 +271,7 @@ class ReactTooltip extends React.Component { this.setState({ placeholder, isEmptyTip, + desiredPlace: e.currentTarget.getAttribute('data-place') || this.props.place || 'top', place: e.currentTarget.getAttribute('data-place') || this.props.place || 'top', type: e.currentTarget.getAttribute('data-type') || this.props.type || 'dark', effect: switchToSolid && 'solid' || this.getEffect(e.currentTarget), @@ -387,9 +388,9 @@ class ReactTooltip extends React.Component { // Calculation the position updatePosition () { - const {currentEvent, currentTarget, place, effect, offset} = this.state + const {currentEvent, currentTarget, place, desiredPlace, effect, offset} = this.state const node = ReactDOM.findDOMNode(this) - const result = getPosition(currentEvent, currentTarget, node, place, effect, offset) + const result = getPosition(currentEvent, currentTarget, node, place, desiredPlace, effect, offset) if (result.isNewState) { // Switch to reverse placement diff --git a/src/utils/getPosition.js b/src/utils/getPosition.js index 780003531..b02dcdecb 100644 --- a/src/utils/getPosition.js +++ b/src/utils/getPosition.js @@ -14,7 +14,7 @@ * - `newState` {Object} * - `position` {OBject} {left: {Number}, top: {Number}} */ -export default function (e, target, node, place, effect, offset) { +export default function (e, target, node, place, desiredPlace, effect, offset) { const tipWidth = node.clientWidth const tipHeight = node.clientHeight const {mouseX, mouseY} = getCurrentOffset(e, target, effect) @@ -151,6 +151,31 @@ export default function (e, target, node, place, effect, offset) { } } + // Change back to original place if possible + if (place !== desiredPlace) { + if (desiredPlace === 'top' && !outsideTopResult.result) { + return { + isNewState: true, + newState: {place: 'top'} + } + } else if (desiredPlace === 'left' && !outsideLeftResult.result) { + return { + isNewState: true, + newState: {place: 'left'} + } + } else if (desiredPlace === 'right' && !outsideRightResult.result) { + return { + isNewState: true, + newState: {place: 'right'} + } + } else if (desiredPlace === 'bottom' && !outsideBottomResult.result) { + return { + isNewState: true, + newState: {place: 'bottom'} + } + } + } + // Return tooltip offset position return { isNewState: false,