Reputation: 1000
I need to fit text in two rows. I have React component but I can't get updated height - only height after element rendered. This is my component
constructor (props) {
super(props)
this.state = {
text: props.text
}
}
componentDidMount() {
let element = ReactDOM.findDOMNode(this)
let parent = element.parentNode
let originalText = element.innerText
let containerHeight = parent.offsetHeight
let temp = originalText
if (containerHeight < element.offsetHeight) {
while(containerHeight < ReactDOM.findDOMNode(this).offsetHeight) {
temp = temp.substr(0, temp.length-1)
this.setState({
text: temp
})
i++
console.log(temp,containerHeight,ReactDOM.findDOMNode(this).offsetHeight);
}
temp = temp.substr(0, temp.length-4) + '...'
this.setState({
text: temp
})
}
}
render() {
return (
<span>
{this.state.text}
</span>
)
}
How I can get element height after each re-render?
PS I found problem:
I should use componentDidUpdate() here and I don't need to use while
in componentDidUpdate() method, because it's triggered each time when I updated state.
Upvotes: 1
Views: 762
Reputation: 3336
componentDidMount
is being called only once, after the component has been mounted. Check react lifecycle documentation for more information.
The methods that are being called again when your component state has been updated and is being re-rendered are(in that order):
componentWillReceiveProps()
shouldComponentUpdate()
componentWillUpdate()
render()
componentDidUpdate()
Since you need to re-calculate the height after your component has been re-rendered put your logic inside componentDidUpdate
and you should be set.
Upvotes: 0
Reputation: 7344
You registered the trigger componentDidMount
. You should register also componentDidUpdate
.
Check this document to understand the lifecycle in react:
https://busypeoples.github.io/post/react-component-lifecycle/
Upvotes: 1