reactjs - React, get bound parent dom element name within component -
within component, how can access name of parent component nested inside?
so if render thus:
reactdom.render( <radialsdisplay data={imagedata}/>, document.getelementbyid('radials-1') );
how can retrieve id
name #radials-1
within component itself?
it makes sense pass property, if really need programmatically, , inside component, can wait component mount, find dom node, , @ parent.
here's example:
class application extends react.component { constructor() { super(); this.state = { containerid: "" }; } componentdidmount() { this.setstate({ containerid: reactdom.finddomnode(this).parentnode.getattribute("id") }); } render() { return <div>my container's id is: {this.state.containerid}</div>; } } reactdom.render(<application />, document.getelementbyid("react-app-container"));
working demo: https://jsbin.com/yayepa/1/edit?html,js,output
if lot, or want really fancy, utilize higher-order component:
class containeriddetector extends react.component { constructor() { super(); this.state = { containerid: "" }; } componentdidmount() { this.setstate({ containerid: reactdom.finddomnode(this).parentnode.getattribute("id") }); } render() { if (!this.state.containerid) { return <span />; } else { return react.cloneelement( react.children.only(this.props.children), { [this.props.property]: this.state.containerid } ); } } } containeriddetector.proptypes = { property: react.proptypes.string.isrequired } // takes optional property name `property` , returns function. // returned function takes component class , returns new 1 // that, when rendered, automatically receives id of parent // dom node on property identified `property`. function withcontainerid(property = "containerid") { return (component) => (props) => <containeriddetector property={property}> <component {...props} /> </containeriddetector> }
here, withcontainerid
function takes argument called property
, returns new function. function can take component type argument, , returns higher-order component. when rendered, new component render passed component, original props, plus additional prop specifying parent container's id on property specified property
argument.
you can use them es7 decorators (as implemented) if wish, or via regular function call:
@withcontainerid() class application extends react.component { render() { return <div>my containers id is: {this.props.containerid}</div>; } } // or, if don't use decorators: // // application = withcontainerid()(application); reactdom.render(<application />, document.getelementbyid("react-app-container"));
working demo: https://jsbin.com/zozumi/edit?html,js,output
Comments
Post a Comment