Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { Component } from 'react'
- import ReactJson from 'react-json-view'
- import FormField from 'grommet/components/FormField'
- export default class JsonArea extends Component {
- static isValid(str, warn = false) {
- try {
- JSON.parse(str)
- return true
- }
- catch (e) {
- warn && alert('Invalid JSON format!')
- }
- }
- constructor(...args) {
- super(...args)
- const { input } = this.props
- this.state = {
- isEditing : false,
- changeValue : JSON.stringify(input.value, undefined, 4),
- isInvalid : false
- }
- }
- handleToggle = () => {
- this.setState({ isEditing : !this.state.isEditing })
- }
- handleTexareaChange = ({ target : { value } }) => {
- const { input } = this.props
- this.setState({
- changeValue : value
- })
- if (JsonArea.isValid(value))
- input.onChange(JSON.parse(value))
- }
- handleTexareaBlur = ({ target : { value } }) => {
- const { input } = this.props
- if (JsonArea.isValid(value)) {
- input.onChange(JSON.parse(value))
- this.setState({
- changeValue : value,
- isInvalid : false
- })
- }
- else
- this.setState({ isInvalid : true })
- }
- handleChanges = ({ updated_src : updatedSrc }) => {
- const { input } = this.props
- this.setState({
- changeValue : JSON.stringify(updatedSrc, undefined, 4)
- })
- input.onChange(updatedSrc)
- }
- render () {
- const { input, meta } = this.props
- const { isEditing, changeValue, isInvalid } = this.state
- return (
- <FormField error={meta.touched ? meta.error : undefined}
- className={`jsonArea ${isInvalid && 'grommetux-form-field--error'}`}>
- {isInvalid &&
- <span className="grommetux-form-field__error">Invalid JSON - Will use last valid state</span>
- }
- <button type="button" onClick={this.handleToggle}>{isEditing ? 'Pretty' : 'RAW'}</button>
- {isEditing &&
- <textarea
- onChange={this.handleTexareaChange}
- onBlur={this.handleTexareaBlur}
- value={changeValue} />
- }
- {!isEditing &&
- <ReactJson src={input.value}
- theme="ocean"
- iconStyle="triangle"
- indentWidth="2"
- displayObjectSize={false}
- displayDataTypes={false}
- onEdit={this.handleChanges}
- onAdd={this.handleChanges}
- onDelete={this.handleChanges} />
- }
- </FormField>
- )
- }
- }
Add Comment
Please, Sign In to add comment