samedi 31 juillet 2021

React custom checkbox input component not rerendering

I'm extracting my checkbox input to separate custom component so I can easily reuse it later. But whenever the state on the parent changes, the checked value inside this custom component is not changing. It's actually changing when I move page first and open it later but not in real-time. But when I use default input component it works in real-time. Any idea how's this possible?

import React from 'react';

const Checkbox = ({ name, id, className, onValueChange, defaultChecked = false }) => {
  let classes = 'checkbox';

  if (className) {
    classes += ` ${className}`;
  }

  const valueChangeHandler = (event) => {
    if (onValueChange) {
      onValueChange(event.target.checked);
    }
  };

  return (
    <input 
      type="checkbox"
      name={ name }
      id={ id }
      className={ classes }
      defaultChecked={ defaultChecked }
      onChange={ valueChangeHandler }
    />
  );
};

export default Checkbox;



Aucun commentaire:

Enregistrer un commentaire