Reputation: 11
So, I'm having a hard time trying to figure this out. Basically I have a component not related to React Final Form but inside the Form tags. The main approach is to when a user clicks on a button (in this case a tooth) its value changes and fills in with a purple color to show if its clicked - if not fills it with a white one. But when I fill in the Form and I click on the component that has the teeth the whole Form re-renders. Is there any way to handle this kind of behavior? Maybe I'm mistaken and it have something to do with my custom component.
Code got kinda big so i'll exemplify how it was built:
<Form
initialValues={exam}
onSubmit={onSubmit}
render={({ handleSubmit, form, submitting, pristine, values }) => (
<form onSubmit={handleSubmit}>
/*Custom component handling the teeth I mentioned*/
<ConeBeam onClick={toothClicked} color="white" data={teeth} />
/*TextField related to React-Final-Form using mui-rff*/
<TextField
label="Region"
name="clark_region"
size="small"
fullWidth
/>
</form>
)}
/>
/*toothClicked function*/
function toothClicked({ id }) {
const tooth = parseInt(id);
const el = document.getElementById(id);
if (!teeth.includes(tooth)) {
setTeeth([...teeth, tooth]);
el.setAttribute("class", classes.primary);
} else {
teeth.splice(teeth.indexOf(tooth), 1);
setTeeth([...teeth]);
el.setAttribute("class", classes.white);
}
}
SOLVED! I was using useState which re-renders to change its state. Just changed setTeeth to a simple variable using let.
Upvotes: 1
Views: 4187
Reputation: 21
You can use Form prop initialValuesEqual. For example: initialValuesEqual={() => true}
Upvotes: 2
Reputation: 22885
It seems like you need to use React.useCallabck()
for your callbacks especially onSubmit
which is a prop to Form
so on every parent re-render, your onSubmit
get a new function reference which causes re-render of Form.
const Parent = () => {
const onSubmit = React.useCallback(() => {
// do your submit logic here
});
return (
<Form onSubmit={onSubmit} ... />
);
}
Upvotes: 0
Reputation: 1013
The form will rerender since that is how React works - if you change state or props for a component, the component will rerender. Consider moving the ConeBeam
component into the parent if the rerender is an issue for your application.
Upvotes: 0