myaliasname3333
myaliasname3333

Reputation: 77

Prop is undefined when passed to functional component in react

I am trying to include PrintGrid functional component in my LoadGridData component. The PrintGrid should receive a document_id of firebase from LoadGridData. But inside the return statement of the LoadGridData, I try to pass the grid_id which is in a grid_data list to PrintGrid and it causes grid_id value to be undefined.

function PrintGrid(grid_id) {
  console.log('Print grid_id in PrintGrid: ', grid_id);

The below gives an error that it cannot access index 0 of undefined.

{grid_data && <PrintGrid grid_id={grid_data[0]} />}

With only the following statement, it updates the grid_data[0] value (grid_id) to the webpage.

{grid_data && <p> {grid_data[0]} </p>}

Upvotes: 0

Views: 1060

Answers (1)

varoons
varoons

Reputation: 3887

You are not passing the props object and just passing grid_id direct to PrintGrind function

Change

function PrintGrid(grid_id) {

to

function PrintGrid({grid_id}) {  

The above is the ES6 way of de-structuring objects and getting fields within directly.

You could also just do PrintGrid(props) and inside the function access props.grid_id

function PrintGrid(props) {  
    console.log(props.grid_id)
}

Upvotes: 4

Related Questions