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:
const TabPanel = () => { const tabsPanelData = [ {label: 'tab1'}, {label: 'tab2'}, {label: 'tab3'} ]; const [tabIndex, settabIndex] = useState(0); const handleChange = (index) => { console.log(index); } return ( <StyledTabPanel> {tabsPanelData.map((tabPanelItem, i) => { const {label, handleChange} = tabPanelItem; return ( <TabPanelItem key={i} label={label} handleChange={handleChange(i)} /> ) })} </StyledTabPanel> ) }
and my child component:
const TabPanelItem = ({ label, handleChange }) => { return ( <StyledTabPanelItem onClick={handleChange}> {label} </StyledTabPanelItem> ) }
Advertisement
Answer
you made a mistake in this line
const {label, handleChange} = tabPanelItem;
you dont handleChange in the tablePanelItem
it should be
const {label} = tabPanelItem;
and you are executing the function handleChange
by doing this
<TabPanelItem key={i} label={label} handleChange={handleChange(i)} />
you either pass the handleChange
function as the body of an arrow function as the props of the TabPanelItem
<TabPanelItem key={i} label={label} handleChange={() => handleChange(i)} />
then on click that arrow function would be executed