Guest User

Untitled

a guest
Jan 19th, 2018
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. import React from 'react'
  2. import PropTypes from 'prop-types'
  3. import KaTeX from 'katex'
  4.  
  5. class TeX extends React.Component {
  6. constructor(props) {
  7. super(props)
  8.  
  9. this.state = this.createNewState(null, props)
  10. }
  11.  
  12. componentWillReceiveProps(nextProps) {
  13. if (this.props.children !== nextProps.children) {
  14. this.setState(this.createNewState)
  15. }
  16. }
  17.  
  18. shouldComponentUpdate(nextProps) {
  19. return nextProps.children !== this.props.children
  20. }
  21.  
  22. createNewState(prevState, props) {
  23. try {
  24. const html = this.generateHtml(props)
  25. if (props.onChange) {
  26. props.onChange(null, html)
  27. }
  28. return { html, error: null }
  29.  
  30. } catch (error) {
  31. if (prevState && !prevState.error
  32. || (prevState.error && prevState.error.message !== error.message)) {
  33. if (props.onChange) {
  34. props.onChange(error)
  35. }
  36. return { ...prevState, error }
  37. }
  38. }
  39. }
  40.  
  41. generateHtml(props) {
  42. const { errorColor, throwOnError } = props
  43.  
  44. return KaTeX.renderToString(
  45. props.children,
  46. { displayMode: props.block, errorColor, throwOnError }
  47. )
  48. }
  49.  
  50. render() {
  51. if (this.state.html) {
  52. return this.props.block
  53. ? <div dangerouslySetInnerHTML={{ __html: this.state.html }} />
  54. : <span dangerouslySetInnerHTML={{ __html: this.state.html }} />
  55. }
  56.  
  57. throw this.state.error
  58. }
  59. }
  60.  
  61. TeX.propTypes = {
  62. block: PropTypes.bool,
  63. children: PropTypes.string.isRequired,
  64. errorColor: PropTypes.string,
  65. throwOnError: PropTypes.bool
  66. }
  67.  
  68. export default TeX
Add Comment
Please, Sign In to add comment