Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React from 'react'
- import PropTypes from 'prop-types'
- import KaTeX from 'katex'
- class TeX extends React.Component {
- constructor(props) {
- super(props)
- this.state = this.createNewState(null, props)
- }
- componentWillReceiveProps(nextProps) {
- if (this.props.children !== nextProps.children) {
- this.setState(this.createNewState)
- }
- }
- shouldComponentUpdate(nextProps) {
- return nextProps.children !== this.props.children
- }
- createNewState(prevState, props) {
- try {
- const html = this.generateHtml(props)
- if (props.onChange) {
- props.onChange(null, html)
- }
- return { html, error: null }
- } catch (error) {
- if (prevState && !prevState.error
- || (prevState.error && prevState.error.message !== error.message)) {
- if (props.onChange) {
- props.onChange(error)
- }
- return { ...prevState, error }
- }
- }
- }
- generateHtml(props) {
- const { errorColor, throwOnError } = props
- return KaTeX.renderToString(
- props.children,
- { displayMode: props.block, errorColor, throwOnError }
- )
- }
- render() {
- if (this.state.html) {
- return this.props.block
- ? <div dangerouslySetInnerHTML={{ __html: this.state.html }} />
- : <span dangerouslySetInnerHTML={{ __html: this.state.html }} />
- }
- throw this.state.error
- }
- }
- TeX.propTypes = {
- block: PropTypes.bool,
- children: PropTypes.string.isRequired,
- errorColor: PropTypes.string,
- throwOnError: PropTypes.bool
- }
- export default TeX
Add Comment
Please, Sign In to add comment