I have 2 js files as below
mainpage.js
import * as React from 'react';
import Filter from '../components/filterPane.js';
export default function MainPage() {
const handleSubmit = () => {
alert('inside submit');
}
return (
<div>
<Header />
<br/>
<div className='rowC'>
<Filter handleSubmit={handleSubmit}/>
</div>
</div>
);
}
and filterPane.js
import * as React from 'react';
import Button from '@mui/material/Button';
export default function ComplexGrid( {handleSubmit}) {
const submitFilter = () => {
handleSubmit(); // Call the parent function
};
return (
<Button variant="contained" onClick={()=>{submitFilter()}}>Submit</Button>
);
}
I want to call the handleSubmit() function in mainPage.js from the onclick() event in filterPane.js.
When I trigger the click event it gives me an error in console as Uncaught TypeError: handleSubmit is not a function.
Any help is much appreciated
Thanks,
2
Answers
In mainpage.js you import Filter from ‘../components/filterPane.js’;
In filterPane.js you export the React component as "ComplexGrid" instead of "Filter". Change the exported name to Filter.
(in mainpage.js you also use a but this is missing an import)
Here’s the corrected code, along with explanations for the changes:
mainpage.js:
filterPane.js:
corrected to ../components/filterPane.js to match the file structure.
MainPage to Filter. This allows Filter to access and call the parent
function.
access the handleSubmit function.
submitFilter. There’s no need to wrap it in another anonymous
function.
ComplexGrid to Filter to match the export name and usage in
mainpage.js.
"handleSubmit is not a function" error, allowing you to call
handleSubmit from the onClick event in filterPane.js.