javascript - Dynamically load and render react component with input[type=file] -
i'd load react js component dynamically through html file input. essentially, i'd achieve same effect if had done import foo ./foo.js
i can read file text after onchange event of html element, don't know it? possible achieve goal? thanks!
onchange(e) { var fr = new filereader() fr.addeventlistener('load', f => { window.console.log(f.target.result.substring(0, 500)) // yields: import react, { component } 'react' ... class foo extends component { ... // what? }) fr.readastext(e.target.files[0]) }
so, ended getting work babel-standalone. i'm able use stateless, functional components, however, , feel though implementation improved. example, don't how have string.prototype.replace
.
anyway, here's worked me, might you, too.
// filetobeloaded.js const elem = () => <h1>hello, world!</h1> // foo.js import react, { component } 'react' import { transform } 'babel-standalone' class foo extends component { constructor(props) { super(props) this.state = { elem: undefined } this.handlechange = this.handlechange.bind(this) } handlechange(e) { let fr = new filereader() fr.addeventlistener('load', e1 => { let s = e1.target.result let result = transform(s, { presets: ['es2015'], plugins: ['transform-react-jsx'] }) let s1 = result.replace(`'use strict'; let elem = function elem(props) {`, 'elem = function(props) {') let elem = () => {} elem = eval(s1) this.setstate({elem}) }) fr.readastext(e.target.files[0]) } render() { const elem = this.state.elem ? this.state.elem : () => <h1>no elem!</h1> return ( <div> <input type="file" onchange={this.handlechange} <elem /> </div> ) } }
wiki
Comments
Post a Comment