javascript - How to position a React component relative to its parent? -


i have parent react component contains child react component.

<div>   <div>child</div> </div> 

i need apply styles child component position within parent, position depends on size of parent.

render() {   const styles = {     position: 'absolute',     top: top(),    // computed based on child , parent's height     left: left()   // computed based on child , parent's width   };   return <div style={styles}>child</div>; } 

i can't use percentage values here, because top , left positions functions of child , parent's widths , heights.

what react way accomplish this?

the answer question use ref described on refs components.

the underlying problem dom node (and parent dom node) needed position element, it's not available until after first render. article linked above:

performing dom measurements requires reaching out "native" component , accessing underlying dom node using ref. refs 1 of practical ways of doing reliably.

here solution:

getinitialstate() {   return {     styles: {       top: 0,       left: 0     }   }; },  componentdidmount() {   this.setstate({     styles: {       top: computetopwith(this.refs.child),       left: computeleftwith(this.refs.child)     }   }) },  render() {   return <div ref="child" style={this.state.styles}>child</div>; } 

this position element after first render. if need reposition element after change props, make state change in componentwillreceiveprops(nextprops).


Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

c - Unrecognised emulation mode: elf_i386 on MinGW32 -