Input attribute doesn't update when const change value

Viewed 189

The value of pickedTrue changes from false to true as the component is mounting. but the input defaultChecked doesn't update it just sets as false.

page.js:

function page() {
    return (
        <Checkbox checked={'1'} />
    )
}

export default page

checkbox component:

function Checkbox({checked}) {
 const pickedTrue = checked == '1' ? true : false

 console.log(pickedTrue)

 return (
     <input type="checkbox" defaultChecked={pickedTrue}/>
  )
 }

export default Checkbox

console.log(pickedTrue) output:

undefined

false

undefined

undefined

true

*note: if i use === instead of == it results in false either way.

4 Answers

You can handle it with useState. Because the state rerender every change.

  ...

  const [checked, setChecked] = useState(false);

  console.log(checked);

  return (
    <input
      type="checkbox"
      onChange={() => setChecked(!checked)}
      defaultChecked={checked}
    />
  );

demo

Use a state variable instead of a constant value. To effectively log changes to your variable you can best use useEffect with a dependency. In your dependency use checked instead of defaultChecked and add an onChange-function so your input will update when you click on the checkbox.

function Checkbox({defaultChecked}) {
  const [checked, setChecked] = useState(defaultChecked === '1');

  useEffect(() => {
    console.log(checked);
  }, [checked])

  return (
    <input type="checkbox" 
      checked={checked} 
      onChange={() => setChecked(!checked)}
    />
  )
}

You are trying to reassign the value of constant which cannot be done. as the value once assigned cannot be changed. And like most of the answers, you should use the state to store the value even when it is coming from the database. You can create a separate function and call it for the defaultChecked. You can do something like this -

function Checkbox({checked}) {
 const [checkedValue, setCheckedValue] = useState(checked === 1 ? true : false)

const setChecked = () => {
  setChecked(!checked)
}

 return (
     <input type="checkbox" defaultChecked={checkedValue} onClick={setChecked}/>
  )
 }

export default Checkbox

Always try using the === strict equality operator which sure the answer isn't anything else but the one with which its type is matched against. When you used the strict equality operator it returned false because you sent a string 1 as a prop and were checking it against the integer 1.

Related