How to Position a React Component Relative to Its Parent

How to position a React component relative to its parent?

The answer to this question is to use a ref as described on Refs to Components.

The underlying problem is that the DOM node (and its parent DOM node) is needed to properly position the element, but it's not available until after the first render. From the article linked above:

Performing DOM measurements almost always requires reaching out to a "native" component and accessing its underlying DOM node using a ref. Refs are one of the only practical ways of doing this reliably.

Here is the solution:

getInitialState() {
return {
styles: {
top: 0,
left: 0
}
};
},

componentDidMount() {
this.setState({
styles: {
// Note: computeTopWith and computeLeftWith are placeholders. You
// need to provide their implementation.
top: computeTopWith(this.refs.child),
left: computeLeftWith(this.refs.child)
}
})
},

render() {
return <div ref="child" style={this.state.styles}>Child</div>;
}

This will properly position the element immediately after the first render. If you also need to reposition the element after a change to props, then make the state change in componentWillReceiveProps(nextProps).

Place component on specific coordinates of a parent component in React Native

One way of achieving this is setting position property of child components to absolute. Then you can use top, left, right and bottom properties to put children to specific coordinates.

Also, you need to set position property of the parent component to relative.

Element's coordinates relative to its parent

You can use getBoundingClientRect(), simply subtracting the coordinates of the parent:

const parentPos = document.getElementById('parent-id').getBoundingClientRect();
const childPos = document.getElementById('child-id').getBoundingClientRect();
const relativePos = {};

relativePos.top = childPos.top - parentPos.top,
relativePos.right = childPos.right - parentPos.right,
relativePos.bottom = childPos.bottom - parentPos.bottom,
relativePos.left = childPos.left - parentPos.left;

console.log(relativePos);
// something like: {top: 50, right: -100, bottom: -50, left: 100}

Now you have the coordinates of the child relative to its parent.

Note that if the top or left coordinates are negative, it means that the child escapes its parent in that direction. Same if the bottom or right coordinates are positive.

Working example

var parentPos = document.getElementById('parent-id').getBoundingClientRect(),
childPos = document.getElementById('child-id').getBoundingClientRect(),
relativePos = {};

relativePos.top = childPos.top - parentPos.top,
relativePos.right = childPos.right - parentPos.right,
relativePos.bottom = childPos.bottom - parentPos.bottom,
relativePos.left = childPos.left - parentPos.left;

console.log(relativePos);
#parent-id {
width: 300px;
height: 300px;
background: grey;
}

#child-id {
position: relative;
width: 100px;
height: 200px;
background: black;
top: 50px;
left: 100px;
}
<div id="parent-id">
<div id="child-id"></div>
</div>

React app, absolutely positioned child not positioned relative to its relatively positioned parent (in Chrome)

I seem to have determined the problem. As is seen in the example code in my question I was dealing with tables and the react elements shown there will generate appropriate HTML TABLE elements. (Not divs styled as table etc but actual td tr etc.)
The table elements will not respond to position:relative in chrome as it is undefined in standard
https://www.w3.org/TR/CSS21/visuren.html#choose-position

' The effect of 'position:relative' on table-row-group,
table-header-group, table-footer-group, table-row, table-column-group,
table-column, table-cell, and table-caption elements is undefined. '

Can I position an element fixed relative to parent?

Let me provide answers to both possible questions. Note that your existing title (and original post) ask a question different than what you seek in your edit and subsequent comment.


To position an element "fixed" relative to a parent element, you want position:absolute on the child element, and any position mode other than the default or static on your parent element.

For example:

#parentDiv { position:relative; }
#childDiv { position:absolute; left:50px; top:20px; }

This will position childDiv element 50 pixels left and 20 pixels down relative to parentDiv's position.


To position an element "fixed" relative to the window, you want position:fixed, and can use top:, left:, right:, and bottom: to position as you see fit.

For example:

#yourDiv { position:fixed; bottom:40px; right:40px; }

This will position yourDiv fixed relative to the web browser window, 40 pixels from the bottom edge and 40 pixels from the right edge.

React Native get position of element relative to parent

Just use those functions I've implemented to get the relative-to-parent position.

  // This function measures specific nodes on the layout
const measureNode = (node) => {
/*
BUG - In the current React Native version (v. 0.61.4)
the x and y values are wrong on Android devices. So, I have decided to
use pageX and pageY (which are relative to the device's screen) and then
implement my own method for getting relative-to-parent positions.

https://github.com/facebook/react-native/issues/29526
*/
return new Promise((resolve, reject) => {
UIManager.measure(node, (x, y, width, height, pageX, pageY) => {
resolve({ x, y, width, height, pageX, pageY });
});
});
};

const getRelativeToParentPosition = async (childNode, parentNode) => {
// Get the relative-to-screen position of the child node
const { pageX: childX, pageY: childY } = await measureNode(childNode);

// Get the relative-to-screen position of the parent node
const { pageX: parentX, pageY: parentY } = await measureNode(parentNode);

/*
Substract those values to get the relative-to-parent position.
Pd: The child's position will be greater than the parent's one,
just because the chlid is inside the parent.
*/

return {
x: childX - parentX,
y: childY - parentY,
};
};


Related Topics



Leave a reply



Submit