Bigboss
Bigboss

Reputation: 365

How do I access this variable in react js?

Parent Component:

render(){
    console.log("here2");
    var temp = [];
    this.props.datarows.forEach((data, key) => {
            temp = this.props.datarows[key]  })
    return(
            <tr>
                <ListColumn col = { this.temp } />
            </tr>
        )
}

ListColumn.py

import React, { Component } from 'react';
import _ from 'lodash';

export default class ListColumn extends Component{

    render(){
        var columns = [];
        console.log("here3")
        console.log(this.props.col);
        // for (var key in this.props.col)
        // {
        //  columns.push(<td>this.props.col[key]</td>)
        // }
        // console.log(columns);
        // return(
        //  columns
        // )
        return(
                <td>a</td>
            )
    }
}

When I tried printing the value of this.props.col, it returns undefined, How do I access the variable temp? Thanks in advance.

Upvotes: 2

Views: 2167

Answers (2)

Mayank Shukla
Mayank Shukla

Reputation: 104359

Instead of

<ListColumn col = { this.temp } />

use

<ListColumn col = {temp } />

Reason: In JS this refers to the object that own the code, inside render method this will refer to the react component. If you use this.temp, it will not take the local variable (defined inside render method), So instead of this.temp use temp (local variable).

One more thing, if you use it like this:

this.props.datarows.forEach((data, key) => {
         temp = this.props.datarows[key]  })

temp will have the last value of this.props.datarows array. I think, you want something like this:

this.props.datarows.forEach((data, key) => {
      if(/*use some condition to filter out the value that you want to save in temp array*/){
           temp.push(data);
      }
}

or if you want to assign the same array to temp variable, looping is not required in that case.

Suggestion: In place of this.props.datarows[key] you can use data also, because data and this.props.datarows[key] will be same.

Upvotes: 1

Ved
Ved

Reputation: 12093

The problem is,temp decalared as var temp = []; but you passing this.temp change: <ListColumn col = { this.temp } />

to

<ListColumn col ={temp } />

So,

render(){
    console.log("here2");
    var temp = [];
    this.props.datarows.forEach((data, key) => {
            temp = this.props.datarows[key]  })//it should be temp.push(data) if you want to pass all datarows as props
    return(
            <tr>
                <ListColumn col = {temp } />
            </tr>
        )
}

2.

 for (var key in this.props.col)
    {
      columns.push(<td>this.props.col[key]</td>)
     }

Should be

 for (var key in this.props.col)
     {
        columns.push(<td key={key}>{this.props.col[key]}</td>)
     }

Upvotes: 0

Related Questions