How to position a React component relative to its parent?
Solution 1
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)
.
Solution 2
This is how I did it
const parentRef = useRef(null)
const handleMouseOver = e => {
const parent = parentRef.current.getBoundingClientRect()
const rect = e.target.getBoundingClientRect()
const width = rect.width
const position = rect.left - parent.left
console.log(`width: ${width}, position: ${position}`)
}
<div ref={parentRef}>
{[...Array(4)].map((_, i) => <a key={i} onMouseOver={handleMouseOver}>{`Item #${i + 1}`}</a>)}
</div>
Seth
Updated on October 12, 2021Comments
-
Seth over 2 years
I have a parent React component that contains a child React component.
<div> <div>Child</div> </div>
I need to apply styles to the child component to position it within its parent, but its position depends on the size of the parent.
render() { const styles = { position: 'absolute', top: top(), // computed based on child and parent's height left: left() // computed based on child and parent's width }; return <div style={styles}>Child</div>; }
I can't use percentage values here, because the top and left positions are functions of the child and parent's widths and heights.
What is the React way to accomplish this?
-
Seth over 8 yearsI can't use percentages; I updated the question to clarify this.
-
Brett over 8 years@Seth Did you try applying
position: relative
to the parent? -
backdesk about 8 yearsEven if it's relative the parent elements might have varying heights in situations where you have multiple levels of nested elements.
-
Simon Hessner over 4 yearsAre
computeTopWith
andcomputeLeftWith
react functions? Do I need to import them? -
Seth over 4 years@SimonH the
compute...
functions are just placeholders; you need to provide the logic. -
vsync almost 4 years@Seth - you should have stated that they are placeholders in a comment, it's misleading.
-
Oliver Dixon about 3 yearsCan you complete the answer?