Reputation: 6842
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?
Upvotes: 35
Views: 125238
Reputation: 9961
To position a React component relative to its parent, you can use CSS and specify the positioning properties.
Here's an example:
import React from 'react'; import './Component.css';
const Component = () => {
return (
<div className="parent">
<div className="child">Hello, World!</div>
</div>
);
};
export default Component;
Create a CSS file named Component.css and add the following styles:
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
In this CSS code, we set the parent component's position to relative. This establishes the parent as the positioning context for its child elements.
For the child component, we set its position to absolute. This removes it from the normal document flow and positions it relative to the nearest positioned ancestor (which, in this case, is the parent component).
The top: 50% and left: 50% properties center the child component horizontally and vertically within its parent.
The transform: translate(-50%, -50%) property ensures that the child component is precisely centered by moving it 50% of its own width and height in the opposite direction.
With these CSS styles, the child component will be positioned in the center of its parent component. You can adjust the positioning values (such as top, left, and transform) as needed to achieve the desired position.
Upvotes: 1
Reputation: 4515
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>
Upvotes: 5
Reputation: 6842
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)
.
Upvotes: 23
Reputation: 258
The right way to do this is to use CSS. If you apply position:relative
to the parent element then the child element can be moved using top
and left
in relation to that parent. You can even use percentages, like top:50%
, which utilizes the height of the parent element.
Upvotes: -3