I'm trying to pass an Array of Objects(Enums) from a son component to the father. But I'm quite not getting the trick.
Father Component:
const [openDialog, setOpenDialog] = useState(false);
const handleReturn = () => filtros;
const [filtros, setFiltros] = useState<Filtros[]>([]);
useEffect(() => {
setFiltros(handleReturn);
console.log(filtros);
}, [openDialog]);
<FiltrosDialog
openDialog={openDialog}
handleCloseDialog={() => setOpenDialog(false)}
filtrosSelec={filtros}
/>
Son Component (there's a lot of code here but trust me, the state is returning an Array of Filtros):
interface Props {
openDialog: boolean;
handleCloseDialog: () => void;
filtrosSelec: Filtros[];
}
export enum Filtros {
Ligacoes = "Ligações",
Tempo = "Tempo em chamada (min)",
Email = "E-mails enviados",
Reuniao = "Reuniões agendadas",
}
const FiltrosDialog: React.FunctionComponent<Props> = ({
openDialog,
handleCloseDialog,
filtrosSelec,
})=> {
const [checked, setChecked] = useState<Filtros[]>([]);
const [left, setLeft] = useState<Filtros[]>([
Filtros.Reuniao,
Filtros.Tempo,
Filtros.Email,
Filtros.Ligacoes,
]);
const [right, setRight] = useState<Filtros[]>(filtrosSelec);
const leftChecked = intersecao(checked, left);
const rightChecked = intersecao(checked, right);
...}
Basically, I'm not sure if my Filtros[] props is supossed to be a function or an array itself...
Your states are fine, but here's the logic for child/parent communication in terms of asking the child to change parent property.
cont Parent = () => {
const [count, setCount] = useState(0)
return <Child count={count} change={setCount} />
}
You can see the setCount
is passed it, not count
. A child can only change parent property through a method. Because in terms of setting the property, count = 3
is not going to make it due to that count
is a primitive value.
This is normally quite clear when you are creating an input component, such as the following.
<Input value={value} onChange={onChange} />
Just found out how to do it. I need to pass the setState as the function inside the child prop on the parent component. And the child prop need to be a void and its argument is the actual Array:
Parent:
const [filtros, setFiltros] = useState<Filtros[]>([]);
...
<FiltrosDialog
openDialog={openDialog}
handleCloseDialog={() => setOpenDialog(false)}
filtrosSelec={setFiltros} />
Child:
interface Props {
openDialog: boolean;
handleCloseDialog: () => void;
filtrosSelec: (arg: Filtros[]) => void;
}
const FiltrosDialog: React.FunctionComponent<Props> = ({
openDialog,
handleCloseDialog,
filtrosSelec,
}) => {
const [right, setRight] = useState<Filtros[]>([]);
useEffect(() => filtrosSelec(right));
...