I am trying to change a parent component state by passing the setter function setAccountNumberFilter to the child and resetting it there. I got the error
Account.js:47 Uncaught TypeError: accountNumberFunction is not a
function
I tried all syntax variations of passing it to the child component through props (not redux). What am I missing?
app file (Parent)
import Header from "./Header";
import Account from "./Account";
import { createRoot } from "react-dom/client";
import React from "react";
const App = () => {
const [accountNumberFilter, setAccountNumberFilter] = useState(0)
return (
<React.StrictMode>
<div>
<Header />
<Account accountNumberFunction={() => setAccountNumberFilter(accountNumber)}/>
<ActivityPanel accountNumberFilter={accountNumberFilter}/>
</div>
</React.StrictMode>
);
};
const root = createRoot(document.getElementById("app"));
root.render(<App />);
export default App;
Account File (Child)
import React, { useEffect, useState } from "react";
const Account = (accountNumberFunction) => {
const [accounts, setAccounts] = useState([]);
useEffect(() => {
fetch("http://localhost:8000/api/account/get_all")
.then((res) => {
return res.json();
})
.then((data) => {
setAccounts(data.accounts);
});
}, []);
return (
<div
className="accountContainer"
style={{
width: "100%",
display: "flex",
justifyContent: "space-around",
}}
>
{accounts.map((accountObj, indx) => {
return (
<div
style={{
width: "300px",
backgroundColor: "white",
display: "flex",
justifyContent: "center",
boxShadow:
"inset 0 3px 6px rgba(0,0,0,0.16), 0 4px 6px rgba(0,0,0,0.45)",
borderRadius: "10px",
}}
key={accountObj.fields.accountNumber + indx}
>
<div>
<h2>
<button
onClick={() =>
accountNumberFunction(accountObj.fields.accountNumber)
}
>
<a>{accountObj.fields.type}</a>
</button>
</h2>
</div>
</div>
);
})}
</div>
);
};
export default Account;
>Solution :
To be able to use accountNumberFunction the way you are using it you will need to modify the account component to destructure in place
const Account = ({accountNumberFunction}) => {}
and when your passing it from parent change
<Account accountNumberFunction={setAccountNumberFilter}/>