From 8a284ec37e676c17f26bff3e8ee7c1e02eeda648 Mon Sep 17 00:00:00 2001 From: vtsybulin Date: Thu, 3 Dec 2020 12:33:08 +0200 Subject: [PATCH] Add dynamic children prop support Add dynamic children prop support so if children was changed it's being taken into account while setting component state leading to proper "Show more", "Show less" buttons behaviour --- index.js | 35 ++++++++++++++++++++++++++--------- 1 file changed, 26 insertions(+), 9 deletions(-) diff --git a/index.js b/index.js index 2321165..d2c579f 100644 --- a/index.js +++ b/index.js @@ -1,12 +1,17 @@ import React from "react"; import { StyleSheet, Text, View } from "react-native"; +const initialState = { + measured: false, + shouldShowReadMore: false, + showAllText: false +}; export default class ReadMore extends React.Component { - state = { - measured: false, - shouldShowReadMore: false, - showAllText: false - }; + state = {...initialState}; + + resetState() { + this.setState({...initialState}); + } async componentDidMount() { this._isMounted = true; @@ -16,6 +21,22 @@ export default class ReadMore extends React.Component { return; } + this.compareTextHeightMeasurements() + } + + async componentDidUpdate(prevProps) { + if (this.props.children !== prevProps.children) { + this.resetState(); + await nextFrameAsync(); + this.compareTextHeightMeasurements(); + } + } + + componentWillUnmount() { + this._isMounted = false; + } + + async compareTextHeightMeasurements() { // Get the height of the text with no restriction on number of lines const fullHeight = await measureHeightAsync(this._text); this.setState({ measured: true }); @@ -37,10 +58,6 @@ export default class ReadMore extends React.Component { } } - componentWillUnmount() { - this._isMounted = false; - } - render() { let { measured, showAllText } = this.state;