Bessem
Bessem

Reputation: 55

how to set the default value for the input from a db in React

I have an input of type checkout and I want to use firestore to get the default value and then put that value in the state and be able to change it and update the store. this is how I thought about it for now.

[visible,setVisible] = useState(false)
const data = commingFromFirebase();
return(
  <div>
   {
     data.map(el => <input type="checkbox" defaultValue={el.visible} value={visible} 
     onChange={e => setVisible(!visible)}/>
   }

  </div>
)

Upvotes: 1

Views: 741

Answers (2)

Adam Jenkins
Adam Jenkins

Reputation: 55623

defaultValue cannot be used with a controlled component - i.e. one where value is controlled by props or state.

defaultValue is only used on uncontrolled components

Because your input is of the controlled type - a change to props or state will change the state of the component - you cannot use defaultValue.

Note: In your case, you are using a checkbox so the props are checked (equivalent to value) and defaultChecked (equivalent to defaultValue), as indicated in the other answer.

Upvotes: 2

Anton L
Anton L

Reputation: 450

You can use a function that returns a boolean and pass it to the checkbox as a checked parameter. That way it will be marked if it returns true and unmarked if it is false.

Should be something like this:

<input type="checkbox" checked={isChecked}

Upvotes: 1

Related Questions