Does anybody know why I get this error? I want to pass the setCookie function to ParseUserCookie but I get an error "Uncaught TypeError: Cannot read properties of undefined (reading 'setCookie')"
function TicTacToe(){
const [cookie, setCookie] = useState(null);
<button onClick={() => handleMultiplayerClick(setCookie)}>
.....
}
const handleMultiplayerClick = (props) => {
promptUserCookie();
let cookie = parseUserCookie(props.setCookie); //Cannot read properties
...
}
Uncaught TypeError: Cannot read properties of undefined (reading 'setCookie')
CodePudding user response:
first of all, handleMultiplayerClick is not a react component, it's a function, those are called parameters not props. But you can call the parameters whatever you want, the problem is that you are dealing with the value as it is an object. In functions, you can access the parameters like this:
function myFun(param1, param2){
console.log(param1);
console.log(param2):
}
But it will work your way if you pass an object instead of passing directly a value:
function myFun(props){
console.log(props.param1);
}
myFun( { param1:10 } );
So either you do it like this:
function TicTacToe(){
const [cookie, setCookie] = useState(null);
<button onClick={() => handleMultiplayerClick(setCookie)}>
.....
}
const handleMultiplayerClick = (setCookie) => {
promptUserCookie();
let cookie = parseUserCookie(setCookie);
...
}
Or like this:
function TicTacToe(){
const [cookie, setCookie] = useState(null);
<button onClick={() => handleMultiplayerClick( { setCookie } ) }>
.....
}
const handleMultiplayerClick = (params) => {
promptUserCookie();
let cookie = parseUserCookie(params.setCookie);
...
}
CodePudding user response:
So as to pass a function as a prop, you should wrap the button
in a child component, like this:
export default function App() {
const [cookie, setCookie] = useState(null);
const handleMultiplayerClick = (updateCookie) => {
console.log(updateCookie);
};
const ChildComp = (props) => {
return (
<button onClick={() => handleMultiplayerClick(props.updateCookie)}>
setCookie
</button>
);
};
return (
<div className="App">
<ChildComp updateCookie={setCookie} />
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
You can play a bit on the codesandbox here: https://codesandbox.io/s/props-to-child-elem-h2u5nr