0

In my react component I have :

 state = { title: '', content: '', file: '' } handleChange = (e) => { this.setState({ [e.target.id] : e.target.value }) } handleSubmit = (e) => { e.preventDefault(); console.log(this.state) } <form onSubmit={this.handleSubmit}> <input type="text" id="title" onChange={this.handleChange}/> <textarea id="content" onChange={this.handleChange}></textarea> <input type="file" id="file" onChange={this.handleChange}/> </form> 

and i am getting in console.log(this.state) only path to file, like : "C:\fakepath\title.jpg". How to set to state actual file? Thanks for help in advance!

1
  • do you mean display the selected file? Commented Nov 26, 2018 at 17:16

1 Answer 1

1

for read file from event you must be use e.target.files[0] bellow code works fine for you

state = { title: '', content: '', file: '' } handleChange = (e) => { this.setState({ [e.target.id] : e.target.value }) } handleOnFileChange = (e) => { let file = e.target.files[0]; this.setState({ [e.target.id] : file }) } handleSubmit = (e) => { e.preventDefault(); console.log(this.state) } <form onSubmit={this.handleSubmit}> <input type="text" id="title" onChange={this.handleOnFileChange}/> <textarea id="content" onChange={this.handleChange}></textarea> <input type="file" id="file" onChange={this.handleChange}/> </form>

Sign up to request clarification or add additional context in comments.

2 Comments

Now how can I reassign this stored file to the input file tag, because when I changed the state the file automatically deselect?
it will not, we are not controlling the file input by state

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.