0

i defined multiple state for my app like this:

 const 
 [state,setstate]=React.useState({headerpic:'',Headerfontfamily:'',Subheaderfontfamilty:''})

and i use a input as follows for getting an image from my device:

 <Button variant='contained' color='primary' className={styler.buttons} name='headerpic' 
 >Header Pic
 <input type='file' value={state.headerpic } style= 
 {{width:'100%',height:'auto',opacity:'0',position:'absolute',top:'0px'}} onChange= 
 {(e)=>fileuploader(e)}></input>
 </Button>

i defined fileuploader like below:

 const fileuploader=()=>{
 if (e.target.files && e.target.files[0]) {
      let img = e.target.files[0];
      console.log(URL.createObjectURL(img))
       setstate({
        
        headerpic: URL.createObjectURL(img)
        
         });
     
       } }

when i click on button and choose the desired pic i got below error:

A component is changing a controlled input of type text to be uncontrolled. Input elements should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info:

any idea for solving this problem?

moein
  • 21
  • 2

2 Answers2

0

An input component that gets changed from controlled to uncontrolled generally means that your <input> goes from having a value to being undefined/null. This is most likely happening when an img gets removed in your case. The easiest fix would be to add a guaranteed value to your input field incase your state is undefined.

<input type='file' value={state.headerpic || ''} ... />

Does this resolve your issue?

Dax
  • 767
  • 4
  • 11
  • 29
0

It would be good if you let us know what it is you're exactly trying to do :/ and also some fuller code (the code given above, doesn't work!!)

If you're trying to make a file uploader I would recommend googling something like

"How to make file upload with react hooks"

Here's one I found earlier ;)

https://www.educative.io/edpresso/file-upload-in-react

which has a nice simple example of creating a file input and saving it in state with react hooks.

NathTech
  • 51
  • 4