emzenophin
emzenophin

Reputation: 17

Element of array is defined in console.log, but not in return statement

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.loging the element words, trying to return the element yields TypeError: props.json is undefined.

Upvotes: 0

Views: 149

Answers (3)

emzenophin
emzenophin

Reputation: 17

Emile's comment led to the solution. I solved the problem by:

  1. Removing Footer from the main view.
  2. Redeclaring Footer in a separate file.
  3. Importing Footer back into the main view, and passing the main view's props to the newly imported Footer.

I don't know why this worked.

Upvotes: 1

Vikash Kumar
Vikash Kumar

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

Gabriel
Gabriel

Reputation: 19

Try to put some verification in this props variable:

return (
    <main>
        <Footer
            json={props.json && props.json}
        />
    </main>
)

Upvotes: 0

Related Questions