i have here a component,
const ParentComponent = () => {
const [state, setState] = useState();
const toggleState = (id) => {
setState(); //setting some stuff
};
const list = data.map((datas) => (
<ComponentOne>
{datas.children === undefined ? (
<ComponentTwo>Not Found</ComponentTwo>
) : (
datas.children.map((datasTwo) => (
<ComponentTwo state={state} toggleState={toggleState}>
Found
</ComponentTwo>
))
)}
</ComponentOne>
));
return <>{list}</>;
};
- in that component im returning a variable that consist of a
<ComponentOne />
that im looping through with the map function - inside of that
<ComponentOne />
i also have a ternary to check if something is defined or not, - if its defined, i am going to map another component, which is
<ComponentTwo />
- in
<ComponentTwo />
i have props defined forstate
andtoggleState
from<ParentComponent />
if i then run the code, there will be an Uncaught runtime errors: ERROR playButtonState is undefined
But, if i do only one map like this,
const ParentComponent = () => {
const [state, setState] = useState();
const toggleState = (id) => {
setState(); //setting some stuff
};
const list = data.map((datas) => (
<ComponentTwo state={state} toggleState={toggleState}>
found
</ComponentTwo>
));
return <>{list}</>;
};
no ones throwing me an error, thoughts?
2
Answers
Actually your question doesn’t provide enough information about your problem, but it seems that inside of your
ComponentTwo
component, you’re assigning thestate
prop to a variable calledplayButtonState
and you’re using it somewhere that causes theundefined
error.Based on that assumption, when the
datas.children === undefined
condition istrue
, you are returning the<ComponentTwo>Not Found</ComponentTwo>
, so the value ofstate
prop isundefined
and you get the error, so you should take a look at theComponentTwo
component and add a couple ofif
statements or something else to control the situation that theplayButtonState
isundefined
The reason you are getting the error "playButtonState is undefined" is because you are passing the
state
andtoggleState
props to theComponentTwo
component inside a nested map function. This means that thestate
andtoggleState
props are not being passed down to all instances ofComponentTwo
, only to the instances that are directly inside the inner map function.To fix this error, you need to pass the
state
andtoggleState
props down to all instances ofComponentTwo
. One way to do this is to move the inner map function into a separate component that receives thestate
andtoggleState
props as props, and then map over the children inside that component. This way, the props will be passed down to all instances ofComponentTwo
.Here’s an example of how the code could look like:
In this updated code, the
ComponentTwoList
component receives thestate
,toggleState
, andchildren
props, and maps over thechildren
props to render theComponentTwo
component with the props passed down to all instances ofComponentTwo
.