Home > Blockchain >  Accessing image upload form without clicking form on React app
Accessing image upload form without clicking form on React app

Time:05-23

I'm attempting to add a hidden image upload form to my page, that I'll later open with a function (Rather than clicking the form directly).

This is what I'm trying to do, but it says "cannot read properties of null, reading click."

What's the right way to do this?

import React, { Component } from 'react';
import SimpleForm from "./components/chatbot/SimpleForm";
var img_upload_form = document.getElementById('imgupload')

function selectImageUpload() {
  img_upload_form.click()
}

class App extends Component {
  render() {
    return (
      <div>
      <SimpleForm />
      <input type="file" id="imgupload" style="display:none"/>
      <button id="OpenImgUpload">Image Upload</button>
      </div>
    );
  }
       
}

export default App;

CodePudding user response:

that happend because u want to get dom object before it's exist. id "imgupload" only exist after react create it. use createRef to get dom object instead

import React, { Component, createRef } from 'react';
import SimpleForm from "./components/chatbot/SimpleForm";

class App extends Component {
constructor(props){
  super(props);
  this.myRef = createRef();
}
doUpload(){
  this.myRef.current.click()
}
componentDidMount(){
 //this.myRef.current.click()
}
  render() {
    return (
      <div>
      <SimpleForm doUpload={doUpload.bind(this)}/>
      <input ref={this.myRef} type="file" id="imgupload" style={{display:'none'}}/>
      <button id="OpenImgUpload">Image Upload</button>
      </div>
    );
  }
       
}

export default App;

inside SimpleForm

class App extends Component {
    constructor(props){
      this.doUpload = props.doUpload
    }
    render(){
      return (<button onClick={this.doUpload} id="OpenImgUpload">Image    Upload</button>)
   }
  }
  • Related