I'm trying to push an object {link:href}
to the state in my project. When I try to add href in {link:href}
it says it is undefined:
Here is my code:
class Download extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.inputRef = React.createRef();
this.state = {
files: []
};
}
handleClick = () => {
const node = this.inputRef.current;
const self = this;
let file;
let name;
let href;
node.addEventListener("change", function() {
const fileList = [];
for (let x = 0, xlen = this.files.length; x < xlen; x++) {
file = this.files[x];
name = file.name;
fileList.push({ name: name });
let reader = new FileReader();
reader.onload = e => {
href = e.target.result;
};
fileList.push({ link: href });
reader.readAsDataURL(file);
}
self.setState({ files: fileList });
console.log(self.state);
});
};
render() {
return (
<div className="input">
<input
onClick={this.handleClick}
id="upload-file"
className="inputName"
type="file"
multiple
ref={this.inputRef}
/>
<div>
<ul ref={this.ulRef}>
{this.state.files.map((file, index) => (
<li key={index}>
<Link to={file.link}>{file.name}</Link>
</li>
))}
</ul>
</div>
</div>
);
}
}
export default Download;
The reason I'm trying to push {link:href}
after the reader.onload function is because the reader.onload function gets loaded after the for loop runs x number of times and it only displays the last item.