Skip to content

Instantly share code, notes, and snippets.

@bjoerge
Created June 13, 2019 09:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjoerge/763706832f2356f81e9f7bf98e4c9773 to your computer and use it in GitHub Desktop.
Save bjoerge/763706832f2356f81e9f7bf98e4c9773 to your computer and use it in GitHub Desktop.
SvgFileToStringInput.jsx
import React from 'react'
import PropTypes from 'prop-types'
import {PatchEvent, set} from 'part:@sanity/form-builder/patch-event'
import FormField from 'part:@sanity/components/formfields/default'
export default class SvgFileToStringInput extends React.Component {
inputRef = React.createRef()
static propTypes = {
value: PropTypes.string,
type: PropTypes.object,
level: PropTypes.number,
onChange: PropTypes.func
}
focus() {
this.inputRef.current.focus()
}
handleChange = event => {
const file = event.target.files[0]
if (file.type !== 'image/svg+xml') {
window.alert(`The type of the selected file is not svg: ${file.type}`)
return
}
const reader = new FileReader()
reader.onload = readerEvent => {
this.props.onChange(PatchEvent.from(set(readerEvent.target.result)))
}
reader.readAsText(file)
}
render() {
const {value, type, level} = this.props
return (
<FormField label={type.title} level={level} description={type.description}>
<input
ref={this.inputRef}
type="file"
placeholder={type.placeholder}
onChange={this.handleChange}
/>
{value && (
<div>
<div>Current value:</div>
<textarea style={{width: '100%'}} value={value} />
</div>
)}
</FormField>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment