0

In my react component I have this type of code :

state = {
    title: '',
    file: ''
}

handleTextChange = (e) => {
    this.setState({
        [e.target.id] : e.target.value
    })
}

handleFileChange = (e) => {
    this.setState({
        [e.target.id] : e.target.files[0]
    })
}

render(){
    return(
        <input type="text" id="title" defaultValue={title} onBlur={this.handleTextChange}/>
        <input type="file" id="file" onChange={this.handleFileChange}/>
    )
}

Now the problem is when I change text, the selected file automatically deselect and I have to select again it. I have to do this thing every time when I change the text in textbox.

How can I set default value in the file the same as I can do in textbox so every time I do not have to select the same file.

1 Answer 1

2

You have to concern about immutability here. Your state is an object. so every time you are setting state, you should only change, changing property only.

state = {
    title: '',
    file: ''
}

handleTextChange = (e) => {
    this.setState({
        ...state,
        [e.target.id] : e.target.value
    })
}

handleFileChange = (e) => {
    this.setState({
        ...state,
        [e.target.id] : e.target.files[0]
    })
}

render(){
    return(
        <input type="text" id="title" defaultValue={title} onBlur={this.handleTextChange}/>
        <input type="file" id="file" onChange={this.handleFileChange}/>
    )
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.