Here is the question. I want to pass index of each child element to the function handleChange, but I can’t get it))) When I click on TabPanelItem appears error handleChange is not a function What’s the problem?
Parent Element:
JavaScript
x
32
32
1
const TabPanel = () => {
2
3
const tabsPanelData = [
4
{label: 'tab1'},
5
{label: 'tab2'},
6
{label: 'tab3'}
7
];
8
9
const [tabIndex, settabIndex] = useState(0);
10
11
const handleChange = (index) => {
12
console.log(index);
13
}
14
15
16
return (
17
<StyledTabPanel>
18
19
{tabsPanelData.map((tabPanelItem, i) => {
20
const {label, handleChange} = tabPanelItem;
21
return (
22
<TabPanelItem
23
key={i}
24
label={label}
25
handleChange={handleChange(i)}
26
/>
27
)
28
})}
29
</StyledTabPanel>
30
)
31
}
32
and my child component:
JavaScript
1
12
12
1
const TabPanelItem = ({ label, handleChange }) => {
2
3
4
return (
5
<StyledTabPanelItem
6
7
onClick={handleChange}>
8
{label}
9
</StyledTabPanelItem>
10
)
11
}
12
Advertisement
Answer
you made a mistake in this line
JavaScript
1
2
1
const {label, handleChange} = tabPanelItem;
2
you dont handleChange in the tablePanelItem
it should be
JavaScript
1
2
1
const {label} = tabPanelItem;
2
and you are executing the function handleChange
by doing this
JavaScript
1
6
1
<TabPanelItem
2
key={i}
3
label={label}
4
handleChange={handleChange(i)}
5
/>
6
you either pass the handleChange
function as the body of an arrow function as the props of the TabPanelItem
JavaScript
1
6
1
<TabPanelItem
2
key={i}
3
label={label}
4
handleChange={() => handleChange(i)}
5
/>
6
then on click that arrow function would be executed