Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
    );
  }
}
like image 665
bgmaster Avatar asked Mar 01 '17 11:03

bgmaster


1 Answers

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>
    );
  }
}
like image 119
mxstbr Avatar answered Oct 25 '22 21:10

mxstbr