Guest User

Untitled

a guest
Oct 12th, 2018
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. import React, { Component } from 'react'
  2. import ReactJson from 'react-json-view'
  3. import FormField from 'grommet/components/FormField'
  4.  
  5. export default class JsonArea extends Component {
  6. static isValid(str, warn = false) {
  7. try {
  8. JSON.parse(str)
  9. return true
  10. }
  11. catch (e) {
  12. warn && alert('Invalid JSON format!')
  13. }
  14. }
  15.  
  16. constructor(...args) {
  17. super(...args)
  18. const { input } = this.props
  19. this.state = {
  20. isEditing : false,
  21. changeValue : JSON.stringify(input.value, undefined, 4),
  22. isInvalid : false
  23. }
  24. }
  25.  
  26. handleToggle = () => {
  27. this.setState({ isEditing : !this.state.isEditing })
  28. }
  29.  
  30. handleTexareaChange = ({ target : { value } }) => {
  31. const { input } = this.props
  32. this.setState({
  33. changeValue : value
  34. })
  35. if (JsonArea.isValid(value))
  36. input.onChange(JSON.parse(value))
  37. }
  38.  
  39. handleTexareaBlur = ({ target : { value } }) => {
  40. const { input } = this.props
  41.  
  42. if (JsonArea.isValid(value)) {
  43. input.onChange(JSON.parse(value))
  44.  
  45. this.setState({
  46. changeValue : value,
  47. isInvalid : false
  48. })
  49. }
  50. else
  51. this.setState({ isInvalid : true })
  52. }
  53.  
  54. handleChanges = ({ updated_src : updatedSrc }) => {
  55. const { input } = this.props
  56. this.setState({
  57. changeValue : JSON.stringify(updatedSrc, undefined, 4)
  58. })
  59. input.onChange(updatedSrc)
  60. }
  61.  
  62. render () {
  63. const { input, meta } = this.props
  64. const { isEditing, changeValue, isInvalid } = this.state
  65.  
  66. return (
  67. <FormField error={meta.touched ? meta.error : undefined}
  68. className={`jsonArea ${isInvalid && 'grommetux-form-field--error'}`}>
  69. {isInvalid &&
  70. <span className="grommetux-form-field__error">Invalid JSON - Will use last valid state</span>
  71. }
  72. <button type="button" onClick={this.handleToggle}>{isEditing ? 'Pretty' : 'RAW'}</button>
  73. {isEditing &&
  74. <textarea
  75. onChange={this.handleTexareaChange}
  76. onBlur={this.handleTexareaBlur}
  77. value={changeValue} />
  78. }
  79. {!isEditing &&
  80. <ReactJson src={input.value}
  81. theme="ocean"
  82. iconStyle="triangle"
  83. indentWidth="2"
  84. displayObjectSize={false}
  85. displayDataTypes={false}
  86. onEdit={this.handleChanges}
  87. onAdd={this.handleChanges}
  88. onDelete={this.handleChanges} />
  89. }
  90. </FormField>
  91. )
  92. }
  93. }
Add Comment
Please, Sign In to add comment