I want to get the plain text of a render method without rendering it into DOM:
class Test from React.Component {
getPlainText = () => {
const plainText = /* some method */(this.renderParagraph())
console.log(plainText) // output in console: <p>I'm text from props of Text ponent!</p>
}
renderParagraph () {
return <p>{this.props.text}</p>
}
render () {
return <button onClick={this.getPlainText}>click me will print {this.props.text} in console</button>
}
}
I didn't find a possible React or ReactDom API to acplish this requirement.
I want to get the plain text of a render method without rendering it into DOM:
class Test from React.Component {
getPlainText = () => {
const plainText = /* some method */(this.renderParagraph())
console.log(plainText) // output in console: <p>I'm text from props of Text ponent!</p>
}
renderParagraph () {
return <p>{this.props.text}</p>
}
render () {
return <button onClick={this.getPlainText}>click me will print {this.props.text} in console</button>
}
}
I didn't find a possible React or ReactDom API to acplish this requirement.
Share Improve this question edited Jan 21, 2018 at 11:44 Zheeeng asked Jan 19, 2018 at 3:21 ZheeengZheeeng 68210 silver badges22 bronze badges 3- it's actually unclear what you want to do with that text – kg2152 Commented Jan 19, 2018 at 3:37
- There are many mistakes in your code. – Hemadri Dasari Commented Jan 19, 2018 at 4:04
- @kg2152 as example shows, I need to log out the stringify html. More accurately, we can feed these text to a keywords parsers, table to excel converter, html structure displayer. – Zheeeng Commented Jan 21, 2018 at 11:50
1 Answer
Reset to default 7I find that ReactDOMServer.renderToString provides this feature.
import ReactDOMServer from 'react-dom/server'
class Test from React.Component {
getPlainText = () => {
const plainText = ReactDOMServer.renderToString(this.renderParagraph())
console.log(plainText) // output in console: <p>I'm text from props of Text ponent!</p>
}
renderParagraph () {
return <p>{this.props.text}</p>
}
render () {
return <button onClick={this.getPlainText}>click me will print {this.props.text} in console</button>
}
}