How I Can Access To Dom Node Inside Of Withstyle Component?
Solution 1:
What you are looking for is innerRef
property. Just replace ref
with innerRef
.
Example:
<TableHead innerRef={(header) => { this.header = header; }} head={head} />
Source (withStyles
docs):
Some implementation details that might be interesting to being aware of:
It adds a classes property so you can override the injected class names from the outside.
It adds an innerRef property so you can get a reference to the wrapped component. The usage of innerRef is identical to ref.
It forwards non React static properties so this HOC is more "transparent". For instance, it can be used to defined a getInitialProps() static method (next.js).
Solution 2:
I know it’s late, but for other people which might face this problem I provide my solution, too. Material UI has a RootRef API which you can use a as HOC the case you want to get the element DOM node:
First import the component:
importReactfrom'react';
importRootReffrom'@material-ui/core/RootRef';
Then wrap your entire element inside a RootRef component and create a React ref. But instead of adding a ref on your component and reference it to the ref like this ref={this.tableHeadRef}
, you should add rootRef
to the rootRef HOC and reference it to your ref like this: rootRef={this.tableHeadRef}
to get the current DOM node. This can be applied to any component that uses withStyles HOC.
classMyComponentextendsReact.Component {
constructor() {
super();
this.tableHeadRef = React.createRef();
}
componentDidMount() {
console.log(this.tableHeadRef.current); // DOM node
}
render() {
return (
<RootRefrootRef={this.tableHeadRef}><TableHead /></RootRef>
);
}
}
Post a Comment for "How I Can Access To Dom Node Inside Of Withstyle Component?"