0

I want to get the data from an input file in react. I have created a class with the data as a state. The idea is that the data should be updated every time the input changes. As this happens, an image should load with the input data.

The code below is what I have created, but it does not work.


class ImagePicker extends React.Component {
    constructor(props){
        super(props);

        this.state = {
            data: null
        }
    }

    handleDataChange = e => {
        this.setState({
            data: e.target.value
        })
    }

    render(){
        return(
            <div>
                <input type='file' onChange={this.handleDataChange} />
                <img src={this.state.data}></img>
            </div>
        )
    }
}

I don't know what the problem is, could you help?

2 Answers 2

2

You can use URL.createObjectURL

handleDataChange = event => {
  if (event.target.files && event.target.files[0]) {
    this.setState({
      data: URL.createObjectURL(event.target.files[0])
    });
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Also use URL.revokeObjectURL() to release the previous one, otherwise it will cause a memory leak.
0

This solves the problem:

class ImagePicker extends React.Component {
    constructor(props){
      super(props)
      this.state = {
        file: null
      }
      this.handleChange = this.handleChange.bind(this)
    }
    handleChange(event) {
      this.setState({
        file: URL.createObjectURL(event.target.files[0])
      })
    }
    render() {
      return (
        <div>
          <input type="file" onChange={this.handleChange}/>
          <img src={this.state.file}/>
        </div>
      );
    }
  }

When picking a file you pick a Url to that file. You can turn this url into a png file by using URL.createObjectURL().

2 Comments

While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.