Reputation: 17
I am trying to access an element of a prop. I can access the element with a console.log
, but not in a return
.
function Viewer(props) {
// Step 1: Viewer receives a prop called "json".
const Footer = (props) => {
console.log(props.json.lines[1]) // Step 3: This successfully logs the second element of the array.
return (
{ props.json.lines[1] } // Step 4: "TypeError: props.json is undefined" (but it's not)
)
}
// Step 2: Viewer calls Footer, passing prop.json to Footer.
return (
<main>
<Footer
json={props.json}
/>
</main>
)
}
This code seems quite straightforward, but doesn't work. Even though console.log
ing the element words, trying to return the element yields TypeError: props.json is undefined
.
Upvotes: 0
Views: 149
Reputation: 17
Emile's comment led to the solution. I solved the problem by:
I don't know why this worked.
Upvotes: 1
Reputation: 1
I got a different error than the Type error you mentioned.
error: unknown: Unexpected token, expected "," (8:20)
6 | return (
7 | // Step 4: "TypeError: props.json is undefined" (but it's not)
> 8 | { props.json.lines[1] }
| ^
9 | )
10 | }
11 |
if you change { props.json.lines[1] }
to <main>{ props.json.lines[1] }<main>
, then you can see that json is defined.
Reasoning might be that the return from a component should be an react element object, but {props.json.lines[1]}
is event not an object.
Upvotes: 0
Reputation: 19
Try to put some verification in this props variable:
return (
<main>
<Footer
json={props.json && props.json}
/>
</main>
)
Upvotes: 0