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>
);
}
}
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>
);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With