How can I get all states of children from parent element?
I created a page, and there are a few elements, the most important is this component list.
Here is the parent element:
const Home = () => {
const walls = [1, 2, 3, 4];
return (
<Layout>
{walls.map(wall => {
return <Wall key={wall} index={wall} />;
})}
</Layout>
);
};
As you can see, it generates a list of elements with map.
So, how can I get all children states from parent element?
This is the child component:
const Wall = ({ index }: IWall) => {
const { doors, windows, handleWindows, handleDoors } =
useWall();
return (
<div>
<input .../>
<input .../>
...
</div>
);
};
And it's hooks:
export const useWall = () => {
const [doors, setDoors] = useState(0);
const [windows, setWindows] = useState(0);
const handleWindows = (value: number) => {
if (value < 0 || value > 50) return;
setWindows(value);
};
const handleDoors = (value: number) => {
if (value < 0 || value > 50) return;
setDoors(value);
};
return { doors, windows, handleWindows, handleDoors };
};
CodePudding user response:
It's generally considered a React anti-pattern for parent components to reach into children components to access state and functions. The solution is to