Ad

How To Position A React Component Relative To Its Parent?

- 1 answer

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?

Ad

Answer

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).

Ad
source: stackoverflow.com
Ad