I am trying to design an about text of a profile that will have a option to read more / read less according to its length, calling function from home as
<AboutText text={aboutData}/>
AboutText Component
import React from 'react';
import './profile.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import 'font-awesome/css/font-awesome.min.css';
class AboutText extends React.Component {
state = {
showAll : false
}
showMore = () => {this.setState({showAll : true})};
showLess = () => {this.setState({showAll : false})};
render(){
const {text} = this.props;
if(text.length <= 150 ){
return(
<p className="about p-3 mt-2 text-dark">{text}</p>
)
}
if(this.state.showAll) {
return (<React.Fragment>
<p className="about p-3 mt-2 text-dark">{text}
<a className="ml-3" onClick={this.showLess}>Read less</a></p>
</React.Fragment>
) }
const toShow = text.substring(0,150)+".....";
return <div>
<p className="about p-3 mt-2 text-dark">{toShow}
<a className="ml-3" onClick={this.showMore}>Read more</a></p>
</div>
} }
export default AboutText;
when i am passing direct data as prop it works fine
<AboutText text="some long string"/>
but not working when passing state as prop ..it shows various errors such as text is undefined
substring is not a function ..thanks in advance
it's not clear enough ! but over all try declaration React.Component<aboutData:String>
before passing it. and do :
constractor(){
super(props)
....
}
If you want to use text
from State
, you need to initialise it in constructor as shown below:
constructor(props) {
super(props);
this.state = {
showAll : false,
text: props.text
}
}
Now, you can use text
from State
in render
as shown below:
render() {
const { text } = this.state;
...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.