Last active
August 30, 2016 00:14
-
-
Save FallOutChonny/819b5988eb9473b752ed53b8da49b14c to your computer and use it in GitHub Desktop.
ReadMore Component for React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <reference path="../../../typings/index.d.ts" /> | |
import * as React from "react"; | |
export interface IReadMoreProps { | |
text?: string | |
showChar?: number | |
} | |
export interface IReadMoreStates { | |
moreText?: string, | |
lessText?: string, | |
isToggle?: boolean | |
} | |
export class ReadMore extends React.Component<IReadMoreProps, IReadMoreStates> { | |
constructor(props: IReadMoreProps) { | |
super(props); | |
this.state = { | |
lessText: null, | |
moreText: null, | |
isToggle: false | |
}; | |
this.toggleLines = this.toggleLines.bind(this); | |
this.collapseLines = this.collapseLines.bind(this); | |
} | |
public static defaultProps: IReadMoreProps = { | |
showChar: 35 | |
} | |
public componentDidMount() { | |
if (this.props.text.length > this.props.showChar) { | |
var c = this.props.text.substr(0, this.props.showChar); | |
var h = this.props.text.substr(this.props.showChar, this.props.text.length - this.props.showChar); | |
this.setState({ | |
lessText: c, | |
moreText: h | |
}); | |
} else { | |
this.setState({ | |
lessText: this.props.text | |
}); | |
} | |
} | |
public toggleLines(event: Event) { | |
event.preventDefault(); | |
this.setState({ isToggle: true }); | |
} | |
public collapseLines(event: Event) { | |
event.preventDefault(); | |
this.setState({ isToggle: false }); | |
} | |
public render() { | |
return ( | |
<span> | |
{this.state.lessText} | |
{this.state.moreText != null ? | |
(!this.state.isToggle ? | |
<span> | |
...<br /> | |
<a onClick={(e: Event) => this.toggleLines(e) } style={{ cursor: 'pointer' }}>Read More...</a> | |
</span> : | |
<span> | |
{this.state.moreText} | |
<a onClick={(e: Event) => this.collapseLines(e) } style={{ cursor: 'pointer' }}>Show Less</a> | |
</span>) | |
: null | |
} | |
</span> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment