bgmaster
bgmaster

Reputation: 2333

React Styled Components - How to access raw html

I have a ref on a component I am converting over to a styled component in my app. The ref is used to access the offsetHeight and scrollHeight properties on the raw html element of the component. Once I switched this component to a styled component, the ref now points to the styled component instead of the raw html element, and I'm unsure how to reference the base element. Can this be done?

example:

const TextArea = styled.textarea`
  display: block;
  margin: 0 0 0 18%;
  padding: 4px 6px;
  width: 64%;
  font-size: 1rem;
  color: #111;`;

export default class Input extends Component {
  componentDidMount() {
    const height = this.textInput.scrollHeight;
    // do something....
  }
  render() {
    return (
      <div>
        <TextArea
          ref={(input) => this.textInput = input}
        ></TextArea>
      </div>
    );
  }
}

Upvotes: 9

Views: 7357

Answers (2)

mxstbr
mxstbr

Reputation: 11477

Passing ref to a styled component will give you a ref to the styled-components wrapper, not the DOM node. To get a ref to actual DOM node pass the innerRef prop. (see the docs)

This is what you need to do:

const TextArea = styled.textarea``;

export default class Input extends Component {
  componentDidMount() {
    const height = this.textInput.scrollHeight;
    // do something....
  }
  render() {
    return (
      <div>
        <TextArea
          innerRef={(input) => this.textInput = input}
        ></TextArea>
      </div>
    );
  }
}

Upvotes: 24

Deividas
Deividas

Reputation: 6507

Yes it can be done. You can access raw html using ReactDOM.findDOMNode(). However, bear in mind that the use of this method is discouraged. You can read more about this in the referenced page.

Upvotes: 0

Related Questions