-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
85 lines (79 loc) · 2.25 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import React from 'react';
import { TouchableOpacity, Text, View } from 'react-native';
/**
* @param text: could be string or component (for nested Text)
* @param readMoreText: custom read more component
* @param showLessText: custom show less component
* @param lineHeight: line height, used to calculate lines presented
* @param numberOfLines: max allowed lines
*/
const defaultLineHeight = 20
const defaultNumberOfLines = 3
export default class RNSimpleReadMore extends React.PureComponent {
constructor(props) {
super(props)
this.state = {
expanded: false,
calculated: false,
truncated: false,
lineHeight: props.lineHeight || defaultLineHeight,
numberOfLines: props.numberOfLines || defaultNumberOfLines
}
}
updateView(height) {
//magic is here
let isTruncated = (Math.floor(height / this.state.lineHeight) > this.state.numberOfLines)
this.setState({
calculated: true,
truncated: isTruncated
})
}
tryMeasure(height) {
if(!this.state.calculated) {
this.updateView(height)
}
}
onLayout(e) {
let { width, height } = e.nativeEvent.layout
if(width != 0) {
this.tryMeasure(height)
}
}
render() {
let { calculated, truncated, expanded, counter } = this.state
var lines = this.state.numberOfLines
if(!calculated) {
lines = this.state.numberOfLines + 1
} else if(truncated && expanded) {
lines = 0
}
let buttonTextStyle = {
color: "#1c7fce",
marginTop: 2,
fontWeight: 'bold'
}
return (
<View style={{alignSelf: 'stretch'}}>
<Text style={{lineHeight: this.state.lineHeight}}
numberOfLines={lines}
ref={ref => {
this.textRef = ref
}}
onLayout={this.onLayout.bind(this)}
>
{this.props.text}
</Text>
<View style={(truncated && !expanded) ? {} : {display: 'none'}}>
<TouchableOpacity onPress={() => {this.setState({expanded: true})}}>
<Text style={buttonTextStyle}>{this.props.readMoreText || "Read more"}</Text>
</TouchableOpacity>
</View>
<View style={(truncated && expanded) ? {} : {display: 'none'}}>
<TouchableOpacity onPress={() => {this.setState({expanded: false})}}>
<Text style={buttonTextStyle}>{this.props.showLessText || "Show less"}</Text>
</TouchableOpacity>
</View>
</View>
)
}
}