For styled-components, how can I fetch the height of any particular div? For e.g.., in the below example, how can I get the height(100px) of Outer tag,
import React from "react";
import ReactDOM from "react-dom";
import styled from "styled-components";
import "./styles.css";
function App() {
const Outer = styled.div`
height: "100px";
border: 1px solid black;
`;
return (
<div className="App">
<Outer>Inside</Outer>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
I have tried Outer.height()
but it doesn't work. How can I get the height of Outer tag?
You can add reference to get size of Outer
and do this.outerRef.current.clientHeight
Something like that :
const Outer = styled.div`
height: 100px;
background: red;
`;
export default class App extends React.Component {
constructor(props) {
super(props);
this.outerRef = React.createRef();
this.state = {
outerHeight: 0
};
}
componentDidMount() {
this.setState({ outerHeight: this.outerRef.current.clientHeight });
}
render() {
return (
<Outer ref={this.outerRef}>
{this.state.outerHeight}
</Outer>
);
}
}
You can check on : https://codesandbox.io/embed/6yq239ljlk?fontsize=14
This works but I don't know if it's on this way you need height.