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?
CodePudding user response:
You can use URL.createObjectURL
handleDataChange = event => {
if (event.target.files && event.target.files[0]) {
this.setState({
data: URL.createObjectURL(event.target.files[0])
});
}
}
CodePudding user response:
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().
