I am currently doing the following to keep my component props updated with the state of my component, however I feel like I am making this more complicated than it needs to be.. Is there a simpler way to update the prop checked in this example and keep it in sync with state.isChecked without having to write to it every time like this? Needing to call the props.write as well as the this.setState right beside each other is the part I am mostly curious about.
export interface CheckboxProps {
text?: string;
checked?: boolean;
}
export class Checkbox extends Component<ComponentProps<CheckboxProps>, any> {
constructor(props: ComponentProps<CheckboxProps>) {
super(props);
this.state = {
isChecked: props.props.checked || false
};
}
handleCheckboxChange = (event: React.ChangeEvent<HTMLInputElement>) => {
this.props.store.props.write('checked', event.target.checked);
this.setState({
isChecked: event.target.checked
});
}
render() {
const { props: { text, checked }, emit } = this.props;
return (
<div {...emit()}>
<label>
<input
type="checkbox"
checked={checked}
onChange={this.handleCheckboxChange}
/>
{text}
</label>
</div>
);
}
}
Also, a separate question. Is it a best practice to use the props or the state when rendering the component? I could imagine that in some scenarios I want state elements that aren't props, in which I would need to use the state. However in this scenario I am curious if I have a state element that I have "synchronized" to a prop?